Method "jumping" return statement

(Sorry for my bad English)
Hi, i have a method that makes comparison between Strings, here it is :
    public String comparacion(String cc,String ci,int tlnm,int ndc){              
              int te = ci.indexOf(' ');                                         
              if( te != -1 ){
                  String[] palabras = ci.split(" ");
                  int index = palabras.length - 1;                                                                                                                    
                  String nombre = "";                                    
                  int indice = 0;               
                  for( int k = 0; k <= index; k++ ){                                              
                       for( int lcc = cc.length() - 1,lci = palabras[k].length() - 1 ;
                                lci >= 0 && lcc >= 0;
                                lcc--,lci-- ){
                            char ccc = cc.charAt(lcc);
                            char cci = palabras[k].charAt(lci);
                            if( ccc != cci ){
                                break;                               
                            if( "DE".equals(palabras[k]) || "DEL".equals(palabras[k]) ||
                                "LA".equals(palabras[k]) || "LOS".equals(palabras[k]) ||
                                "SAN".equals(palabras[k]) ){
                                indice++;
                                //System.out.println(index + " " + indice );                                   
                                break;
                            if( ccc == cci ){                     
                                if( lci == 0 ){                                                                                           
                                    nombre += palabras[k] + " ";                                                     
                                    indice++;                                   
                                    //System.out.println("Afuera = " + index + " " + indice + " " + nombre);                                                                  
                            if( indice == index ){
                                System.out.println(index + " " + indice);
                                return null;
                            if( tlnm - 1 == ndc  ){                                   
                                //System.out.println(index + " " + indice );                                   
                                System.out.println("Posible nombre mal escrito en el catalogo : " + ci );                                       
              if( te == -1 ){                                      
                  for( int lcc = cc.length() - 1,lci = ci.length() - 1; lci >= 0 && lcc >= 0; lcc--, lci-- ){
                       char ccc = cc.charAt(lcc);
                       char cci = ci.charAt(lci);
                       if( ccc != cci ){
                           //Son diferentes
                           //System.out.println(cci + " es diferente de " + ccc);
                           //return "Es doble supongo : " + cc ;                                     
                           break;
                       if( ccc == cci ){                     
                           //System.out.println(cci + " " + ccc);
                           if( lci == 0 ){
                               //System.out.println("Son iguales : " + ci + " " + cc);                                      
                               //return "Son iguales : " + ci + " y " + cc;                               
              return null;
       }The problem is in the if that evaluates if indice is equal as index if true and if my understanding of the return statement is right, then it should stop there and return to the
function where it was called from right? Unfortunately this is not happening, in fact i tested with the System.out.println and it enters when the condition is true but it seems
it skips the return and keeps going on the rest of the code. Any idea of what could be the issue ?
-Daniel

Hello Daniel,
IMHO your code has several issues wich make it hard to read and therefore hard to debug:
1. choose better variable names. Variable names should clearly express what they contain or what meaning they have. e.g.: int te = ci.indexOf(' '); // bad
int indexOfSpace = ci.indexOf(' '); // better
// but in your case it really should have been:
boolean isSingleWord = -1 == ci.indexOf(' ');2. you schould never return null unless null is a valid member of the result set (and not some kind of error indikator).
I understand that you plan to have it return something but my impression is that String meight not be the appropriate return type. The other option is that the name of this method is not appropriate.
3. what keep you from using <b>StringTokenizer</b>?
4. why do you iterate over the single characters yourself instead of relying on <b>String.equals()</b>?
5. the line if( te == -1 ) expresses the opposit of the first <b>if</b>, so you should turn it into <b>else</b>.
6. you should extract the bodies of <tt>if( te != -1 )</tt> and <tt>if( te == -1 )</tt> (after turning it to else) to their own methods.
7. the part if( "DE".equals(palabras[k]) || "DEL".equals(palabras[k])
      "LA".equals(palabras[k]) || "LOS".equals(palabras[k]) ||
      "SAN".equals(palabras[k]) )should better be written this way:private static final List<String> KEYWORD_LIST = Arrays.asList(new String[]{ "DE","DEL","LA", "LOS","SAN"]);
if(KEYWORD_LIST.contains(palabras[k]))8. The keyword check that does not depend on anything declared in the inner loop so it shuld be moved out of it.
9. the check of the input parameters tlnm and ndc do not depent on anything in both of the loops so it should be moved behind (or before) them.
10. if( ccc != cci ){
    break;                               
if( ccc == cci ){
} again this is the opposit so instead of breaking the loop you should have formed a better <b>if</b>.
hope this helps.
bye
TPD

Similar Messages

  • Returning the result of method in return statement.

    hi,
    If I write the following line of code then will there be any problem or what issues will arise
    return method(x,y);Is it a good programming practice, if not why?

    It's perfectly valid syntax. This is a stylistic concern. Opinions on style vary far and wide according to each programmer's bias, personality, past experience, and what they had for lunch that day.
    Personally, I would be fine with return foo(); if:
    - It were the only line in the methodO_o
    Why would that matter?
    - The name of foo made it reasonably clear what it was doingSounds good, but shouldn't all method have good names?
    >
    I would avoid it if:
    - It was likely that the method calling foo would be frequently changed to expand its functionalityWhy does it matter?
    - foo returned a type of variable that should be named as a local variable simply to improve readabilityDoesn't matter what I eat to lunch, I would never agree on that :)

  • 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?

  • Using return statement in jsp

    Hi all,
    I am using return statement in JSP page after a redirect to stop executing that page. If the data bean is not present then it must go to previous page. When this return statement is executed the previous page is displayed but url in browser remains same. Why it is so ?. Is there any other way to tell a JSP page to stop executing and redirect to another page.
    rgds
    Antony Paul

    Hi Antony,
    do you use the "forward()" method or the "redirect()" method???
    rgds
    Howy

  • "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

  • Methods that return more than one object.

    Hello everyone,
    I don't know if this has ever been proposed or if there's an actual solution to this in any programming language. I just think it would be very interesting and would like to see it someday.
    This is the thing: why isn't it possible for a method to return more than one object. They can receive as many parameters as wanted (I don't know if there's a limit), but they can return only 1 object. So, if you need to return more than one, you have to use an auxiliary class...
    public class Person {
       private String name;
       private String lastName;
       public Person(String name, String lastName) {
          this.name = name;
          this.lastName= lastName;
       public String getName() {
           return name;
       public String getLastName() {
           return lastName;
    }So if you want to get the name of somebody you have to do this, assuming "person" is an instance of the object Person:
    String name = person.getName();And you need a whole new method (getLastName) for getting the person's last name:
    String lastName = person.getLastName();Anyway, what if we were able to have just one method that would return both. My idea is as follows:
    public class Person {
       private String name;
       private String lastName;
       public Person(String name, String lastName) {
          this.name = name;
          this.lastName= lastName;
       public String name, String lastName getName() {
           return this.name as name;
           return this.lastName as lastName;
    }And you would be able to do something like:
    String name = person.getName().name;and for the last name you would use the same method:
    String lastName = person.getName().lastName;It may not seem like a big deal in this example, but as things get more complicated simplicity becomes very useful.
    Imagine for example that you were trying to get information from a database with a very complex query. If you only need to return 1 column you have no problem, since your object can be an array of Strings (or whatever type is necessary). But if you need to retrieve all columns, you have three options:
    - Create 1 method per column --> Not so good idea since you're duplicating code (the query).
    - Create and auxiliary object to store the information --> Maybe you won't ever use that class again. So, too much code.
    - Concatenate the results and then parse them where you get them. --> Too much work.
    What do you think of my idea? Very simple, very straight-forward.
    I think it should be native to the language and Java seems like a great option to implement it in the future.
    Please leave your comments.
    Juan Carlos García Naranjo

    It's pretty simple. In OO, a method should do one thing. If that thing is to produce an object that contains multiple values as part of its state, and that object makes sense as an entity in its own right in the problem domain--as opposed to just being a way to wrap up multiple values that the programmer finds it convenient to return together--then great, define the class as such and return an instance. But if you're returning multiple values that have nothing to do with each other outside of the fact that it's convenient to return them together, then your method is probably doing too much and should be refactored.
    As for the "if it increases productivity, why not add it?" argument, there are lots of things that would "increase productivity" or have some benefit or other, but it's not worth having them in the language because the value they add is so small as to no be worth the increase in complexity, risk, etc. MI of implementation is one great example of something that a lot of people want because it's convenient, but that has real, valid utility only in very rare cases. This feature is another one--at least in the domain that Java is targetting, AFAICT.

  • Missing return statement - Java noob here

    Hi to everyone! I'll just like to ask if anyone of you can check out my code and see why I can do to correct this 'Missing return statement' problem with my code.
    From what I've been noticing, the compiler returns this statement when the return statements are inside conditional clauses. Usually I've been able to remedy it by storing it into another variable that's been instantiated outside my usual 'if' statements. But this time, it was my first time to use a 'try' statement since FileReader and FileWriter won't work without it. I tried to use the same remedy but it just doesn't work. Here's the part of the code I'm having problems with:
    public String[] sortWordList()
             try
                  FileReader fReader = new FileReader("initlist.txt");
                  BufferedReader bReader = new BufferedReader(fReader);
                  String output = bReader.readLine();
                  String[] words = output.split(",");
                  for(int counter1 = 0; counter1 < words.length; counter1++)
                        for(int counter2 = counter1 + 1; counter2 < words.length; counter2++)
                                  if(words[counter2].compareToIgnoreCase(words[counter1]) < 0)
                                       String temp = words[counter1];
                                       words[counter1] = words[counter2];
                                       words[counter2] = temp;
                   String temp = "";
                   for(int counter1 = 0; counter1 < words.length; counter1++)
                        FileWriter fWriter = new FileWriter("initlist.txt");
                       fWriter.write(words[counter1] + "," + temp);     
                       fWriter.close();
                       temp = bReader.readLine();
                   String output2 = bReader.readLine();
                  String[] words2 = output.split(",");
                  return words2;
             catch(IOException ioe)
        }The compiler points the 'Missing return statement' at the last bracket.
    BTW, just for those who are wonder what we're making, our teacher gave us a machine project where we have to make a basic dictionary (words only, we'll be doing the definitions and other stuff that's associated with the word some other time I think) with input and sort functions.
    Thanks guys!
    - Alphonse

    T.B.M wrote:
    By doing this, we're subverting the exception mechanism and totally defeating the purpose of exceptions. If you're going to catch an exception, you should handle it. Just smothering it and returning null is not handling it. If you're not going to handle it, then don't catch it, or else catch it and wrap it in a more layer-appropriate exception and re-throw.Then ideally there should be some *"return String[];"* statement inside "catch", not after it.No. Not unless there's some meaningful default value to use when the file can't be read, which does not appear to be the case here.
    If you return null, or an empty String[], then the caller will have to do an if test to know that something went wrong and that the method failed to do what it was supposed to do, and then what is the caller supposed to do in that case? The point of exceptions is to avoid those explicit tests for errors and let the "happy path" code just go on under the assumption that things are fine. If something goes wrong, an exception will be thrown and the happy path code will stop excuting, without having to explicitly test for an error condition.

  • 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 error

    public class Member
             public int Member(String memberid, String memberpw)
         String cs = "jdbc:oracle:thin:@255.255.255.255:1000:a123stud";
             String user = "123456";
             String pass = "123456";
              String member = "member_id";
             try
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   //Connection conn = DriverManager.getConnection("jdbc:odbc:myOracle");
                   Connection conn = DriverManager.getConnection(cs,user,pass);
                   Statement stmt = conn.createStatement();
                   String query = "SELECT * FROM members";
                   ResultSet rs = stmt.executeQuery(query);
                 // ResultSet rs = stmt.executeQuery("SELECT * FROM members WHERE member_id = 'M0001'");
                        int counter = 0;
                        while(rs.next())
                             member = rs.getString("member_id");
                             counter++;
                             if (counter == 0)
                             return 0;
                             else
                             return 1;
                        //System.out.println("\nOracle10g at 255.255.255.255 is working!");
              catch(SQLException e)
                   System.out.println("\n\nException Occured " +
                             "(Incorrect IP address, Server may be down, or SQL Exception)");
                   e.printStackTrace();
              catch(ClassNotFoundException e)
                   System.out.println("\n\nException Occured (CLASSNOTFOUND Exception)");
    }It says i am missing the return statement,but i do have set return something,whats the error? thx for helping

    For example, what happens if the SQL query doesn't
    return any rows, and rs.next() is never true?The while() loop will be skipped and the if statement
    will execute, which has two branches, one of which is
    guaranteed to return?Oops. My bad.
    I thought the ifs were inside the while.
    Okay, the problem here is with the exception handling. Catching and logging and doing nothing else is usually almost as bad as just smothering them. In this case it's especially true because the method then just continues after the catch blocks, in which case there's no return.
    You have to actually handle the exceptions if you're not going to propagate them. In this case, that would mean returning some reasonable default value. I'd say that's not a good idea here, and you're better off to just let the exceptions be thrown, or wrap and rethrow in your own exception.

  • 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 !

  • Switch statesment in  return statement

    Hello, how do i effectively use a switch statement in a method that returns a string, below is my understanding but this implementation will not compile
    public String toString(int format){
         return switch(format){
                             case 0: System.out.print(year+" "+month+" "+day);
                                       break;
                             case 1: System.out.print(month+" "+day+" "+year);
                                       break;
                             case 3: System.out.print(day+" "+month+" "+year);
                   default: System.out.print("that is not a valid format");

    If you are new to Java I suggest using the New to Java forum in future.
    The problem also appears to be that you haven't used any of the constructs correctly.
    BTW: Why is there no format #2
    public String toString(int format){
        switch(format) {
              case 0: return year+" "+month+" "+day;
              case 1: return month+" "+day+" "+year;
              case 3: return day+" "+month+" "+year;
              default: throw new IllegalArgumentException("that is not a valid format");
    }There are allot of ways you could do this better but it requirements more advanced programming.

Maybe you are looking for

  • How to create a theme with more than one master-slide size defined?

    I would like to create a Keynote theme that has more than one size of page defined - for example one for on-screen show, and one for printing. I noticed that the stock themes, and those from theme vendors, come with multiple page dimensions, and that

  • Flash Player movies not activating in Internet Explorer

    I had Internet Explorer 6.0 and now 7.0... same thing occurs in both programs... PROBLEM: I have a very simple webpage with Flash Buttons for navigation. When I load the page in IE, the buttons are NOT activated. When I put my mouse over the control,

  • Functional Specifications for ABAP Developments

    Dear All, We are implementing negative time management. We require data to be transferred from the Time Recording Terminal to the SAP system. We are planning to adopt for ABAP program to transfer data from Time Recording System to SAP. Can anyone pro

  • Can't write large files to my WebDAV server

    Hi, yesterday I set up a WebDAV directory on my mini using Apache 2.0.56 with digest authentication. Everything works fine when I connect from home, however, when I tried to access it from work I got some very strange reactions. Connection worked out

  • Ugent native compoenent in applet

    I have written an applet which uses jdic browser on Windows platform (InternetExplorer). So I have a browser in a browser :-) But while loading i get always an exception : org.jdesktop.jdic.init.JdicInitException: java.lang.UnsatisfiedLinkError: no j