Java function calling and return value in Android

android, function, java

Solution

if(flag==1)
    {
        Log.d("Flag value", "flag= "+flag);
        //System.out.println("Read have "+read());
        String tt=read();
        s1=tt;
    }

in above code `read()` method is calls twice. And inside `read()` method variable "temp" is declared global and you are concat the data like

temp = temp + Character.toString((char)c);

so value is concat twice in temp variable.

To Resolve the issue declare temp as local variable like

public String read(){
          String temp="";
          try{
             FileInputStream fin = openFileInput(file);
             int c;

             while( (c = fin.read()) != -1)
             {
                temp = temp + Character.toString((char)c);
             }
          }
          catch(Exception e)
          {

          }
          Log.d("INSIDE READ FUNC", "temp have "+temp);
        return temp;
       }

Problem

I have a Java class with some code to be operated based on flag value, below is my code which works as flag value is 1 ``` if(flag==1) { Log.d("Flag value", "flag= "+flag); System.out.println("Read have "+read()); String tt=read(); s1=tt; } ``` From this above function the value in the variable "s1" is some string value returned by read() function. the output of this code is returning two times of read() function, like s1 having "StringString" Here is my read function code ``` public String read(){ try{ FileInputStream fin = openFileInput(file); int c; while( (c = fin.read()) != -1) { temp = temp + Character.toString((char)c); } } catch(Exception e) { } Log.d("INSIDE READ FUNC", "temp have "+temp); return temp; } ``` While I omitted this "System.out.println("Read have "+read());" by below code ``` if(flag==1) { Log.d("Flag value", "flag= "+flag); //System.out.println("Read have "+read()); String tt=read(); s1=tt; } ``` And I got the perfect output like s1 having "String" How come the code works like this? I called the read() function only once to store to "tt" variable. And storing the tt variable to s1 variable. But when I use System.out.println("Read have "+read()); its invoking and storing the returned string value in array and in the second time I am storing to the "tt" String variable and its appending the last returned string from the read() function to the "tt" String variable. So the "tt" String variable having two times of read() function Returned String. How it is storing two times?

Original source