I feel somehow I don't understand point of using "return" value, so I will give you two examples and maybe someone will clear that up for me.
What is the difference between this method:
int giveSecret(){
return 42;
}
//code in between
int theSecret = life.giveSecret();
System.out.println(theSecret);
(my expected console output):
42
and this method:
void giveSecret(){
//code that "resets" variable to value 42
}
//code in between
int theSecret = life.giveSecret();
System.out.println(theSecret);
(my expected console output):
42
Sure, languages could work like your latter example. Every function could have a global variable associated with it where the "result" is stored. You would call the function then read the result from the global variable. However:
It's disgusting. Why need to have another global name? Why have to somehow know what variable is associated with which function?
It's not thread-safe. Multiple threads might call the function at the same time. Now, which thread's result is present in the global variable?
Language designers figured this stuff out long ago, and it has stuck.
Related
What does following Java method - method1 do in general? It doesn't have return parameter (because void). Does it just modify input parameter (int a) to the value stated in body of the method (6)? Or does it just take some int a as input and modify some global parameter a to the input value? What is the point of such methods?
public void method1 (int a){
a = 6;
}
Yes, that code snippet is senseless, when considered out of context. Likely there is a larger lesson being taught in your textbook, but we can only guess as to what that might be since we don’t have your textbook.
The method receives a primitive (not an object) variable holding some number. The only line of that method then discards that passed value, and replaces it with the number 6. This makes no sense for two reasons:
We discarded the value being sent to us by the calling programmer. That calling programmer is trying to message us, but we ignore the content of that message.
We do no further work. After assigning six to the variable, it goes out of scope, to be garbage-collected eventually. No productive work was accomplished.
Be clear that we did not change anything in the calling programmer’s state. When our method completes its execution, our variable a goes out of scope, and our value 6 disappears in a puff of smoke.
By the way, adding final to that argument declaration would tell the compiler to flag the re-assignent of the argument variable to a different value.
public void method1 ( final int a ){ …
The point is probably to talk about call by value, and the subtle differences that come into play when using primitive types, as in your example, or reference types, like here.
int someA[] = ...
foo(someA);
with
void foo(int a[]) { a[0] = 1;
or
List<Whatever> someA = ...
foo(someA)
void foo(List<Whatever> a) { a.clear()
will actually have an effect in the place that foo() is called.
In other words: the method shown in the question is really a no-op, it doesn't do anything that can be observed outside (nicely explained in the other answer).
When we say
public static void task(int number)
{
(you can give any example)
}
what is the function of parameter there ? I understand that when we give task.subtring(0,5) here the parameters are telling us the place value of the character. How does it work in "int"..
If you are confused about the general idea of parameters, they are a message you pass to a method. Think of a method or a function for that matter as a labeled block of code the you can execute somewhere else using that label. Now, parameters are a way of giving a different input to that block of code. They are variables that get used inside that block of code and that you can set from outside of it by passing in a different value when you use that label. For example, I can pass an int (integer number) to a method that multiplies it by 2 and returns the result:
int multiplyBy2(int number){
return number*2;}
Now, I can pass different numbers into that method and get different outputs. What could be confusing about that method you've shown is that it doesn't return a value and can't access class fields, so it might seem useless. However, that method can be doing a lot of other stuff with that integer. A few examples: the method can be printing some string to the screen that changes based on the integer, it could be writing to a file, it could be modifying static fields, and many other possible tasks.
In the example you posted you would pass in the value of a single int; maybe to get a single character, maybe to read a specific line from a file; anything that needs that single int. In the example you understand there are two int parameters.
Your question is for the idea of parameters at all, aren't you? Parameters make methods more dynamic. for example you want to add a number to an existing int in an object. you will do it in this way (it is only a part of a class):
int all;
....
public void add(int i){
all += i;
}
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
So I have to write a program for an invoice where I define the variables locally, instead of globally. So it kinda looks like this the way I have it.
public void setAmount(int anyAmount)
{
int amount;
amount = anyAmount;
}
I then do the display method like this and get an error saying cannot find symbol
public void displayInvoice()
{
System.out.println("Amount: " + amount);
I can easily do this globally, but having troubles with this. Thank you!
When you declare a variable inside a function, such as in your setAmount, it only exists for as long as that function is executing; it only exists between the { and }. That's why you're unable to reference it later in the second function, as it no longer exists. Essentially, what you're doing is setting it, and then getting rid of it right away, through no effort on your code, but simply through the way memory is allocated and used in programs.
The way to get around this would be to use a "global" as you've said, or to pass it back after you set it, and put it into another variable, which you then send to your displayInvoice function. The last method requires that the setAmount and displayInvoice are part of a larger function themselves, and the intermediary variable is declared inside it. Over all, a "global" as you've said, is the easiest and probably best solution given what you've explained.
Unworking Example:
main() {
int amount = 0;
amount = setAmount(5);
displayInvoice(amount);
}
In doing so though, you may as well forgo the setAmount function, as you can see it's fairly redundant. Keeping set amount, you'd need to change it to
Public int setAmount(int anyAmount)
When you declare a variable inside a method it becomes local meaning it's only visible in that method, that is why you are getting that error, you can correct that by making it global.
I have helper class with this static variable that is used for passing data between two classes.
public class Helper{
public static String paramDriveMod;//this is the static variable in first calss
}
this variable is used in following second class mathod
public void USB_HandleMessage(char []USB_RXBuffer){
int type=USB_RXBuffer[2];
MESSAGES ms=MESSAGES.values()[type];
switch(ms){
case READ_PARAMETER_VALUE: // read parameter values
switch(prm){
case PARAMETER_DRIVE_MODE: // paramet drive mode
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));
System.out.println(Helper.paramDriveMod+"drive mode is selectd ");
//here it shows the value that I need...........
}
}
//let say end switch and method
}
and the following is an third class method use the above class method
public void buttonSwitch(int value) throws InterruptedException{
boolean bool=true;
int c=0;
int delay=(int) Math.random();
while(bool){
int param=3;
PARAMETERS prm=PARAMETERS.values()[param];
switch(value){
case 0:
value=1;
while(c<5){
Thread.sleep(delay);
protocol.onSending(3,prm.PARAMETER_DRIVE_MODE.ordinal(),dataToRead,dataToRead.length);//read drive mode
System.out.println(Helper.paramDriveMod+" drive mode is ..........in wile loop");//here it shows null value
}
//break; ?
}
}
//let say end switch and method
}
what is the reason that this variable lose its value?
Could I suggest that to pass data between classes, you use separate objects instead of a global variable?
It's not at all clear how you expect the code in protocolImpl to get executed - as templatetypedef mentions, you haven't shown valid Java code in either that or the param class (neither of which follows Java naming conventions).
A short but complete example would really help, but in general I would suggest you avoid using this pattern in the first place. Think in terms of objects, not global variables.
As I understand it, a "Class" (Not just an instance but the entire class object) Can be garbage collected just like any other unreferenced object--a static variable in that class instance won't prevent the GC from collecting your class.
I just came here because I think I'm seeing this behavior in a singleton and I wanted to see if anyone else noticed it (I've never had to research the problem before-and this knowledge is like a decade old from the back of my brain so I'm unsure of it's reliability at this point).
Going to go continue research now.
Just found this question, check the accepted answer--looks like it's unlikely that a static will be lost due to GC, but possible.
Are static fields open for garbage collection?
A Variable never "loses" its value. You set it to "null" somewhere, but your code here is not enough to tell whats going on. The only place here where you set it is this line:
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));
But if you pass "null" to toString() you get some null pointer exception...so I would assume that this line never gets hit and so you get the "null" value as you dont initialize paramDriveMod with some other value.
Don't use static variable until you are in some critical situation. You can use getter setter instead
Could it be that you may be confusing static with final? Static variables' values can change. Final variables' values can not.
The execution flow not shown - may be the 3rd code:
while(c<5){
Thread.sleep(delay);
protocol.onSending(3,prm.PARAMETER_DRIVE_MODE.ordinal(),dataToRead,dataToRead.length);//read drive mode
System.out.println(Helper.paramDriveMod+" drive mode is ..........in wile loop");//here it shows null value "
is executed before the second code
switch(ms)
{
case READ_PARAMETER_VALUE: // read parameter values
switch(prm){
case PARAMETER_DRIVE_MODE: // paramet drive mode
Helper.paramDriveMod =(Integer.toString(((USB_RXBuffer[4]<< 8)&0xff00)));