I have very silly doubt that why we use return statement in method . Without using return statement in method we can also get required value
as example
package testing;
public class ReturnMethod {
static int a = 10;
static int b = 5;
static int c;
static int d;
public static void add() {
c = a + b;
}
public static int returnAddValue() {
d = a + b;
return d;
}
public static void main(String[] args) {
add();
System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In above example in both the cases i am getting output
c: 15
value: 15
So i am having doubt when to use return statement and why is neccessary
With return statement, the return value is not necessary to be saved in any global, external or member variable.
However, without return statement you have to prepare kind of outer variable value to track that.
If you assign the result of a method to a static variable (and, indeed, pass in the "parameters" of the method by setting static variables), you have problems when that method is called by two threads concurrently, since the variables are shared for all invocations of the method:
Thread t1 = new Thread(() -> {a = 1; b = 2; add(); }); t1.start();
Thread t2 = new Thread(() -> {a = 3; b = 4; add(); }); t2.start();
t1.join(); t2.join();
You don't know which of these threads run first, or even if they run at the same time; so you don't know what the value of a or b is when you call add(), and nor do you know whether the value in c afterwards is the result of the invocation in the first or second thread (or a mixture of the two).
The value stored in c afterwards could be any of 3, 5 or 7 (or any other value, if there is another thread which is also invoking add() concurrently outside this code.
This problem of thread interference just completely goes away if you keep values localized to the stack, by passing a and b as method parameters, and receiving the result as a return value.
Even if your code is single-threaded, it's simply ugly to have to write:
a = 1;
b = 2;
add();
int result = c;
rather than
int result = add(1, 2);
You should use a return statement, when you need the method to return a value.
In your case, both methods work.
But you can, and should use returning methods, when you don't want a field of your class to be changed by another class.
For example, you want money to be only seen, and not changed, when you are making a bank-account related software. So, you make money private, and make a method which returns the money. In this way, other classes can only see money, but not change it.
First, your functions are different, as you see
public static **void** add()
public static **int** returnAddValue()
First one does not return anything, because it has void as return type and the second one has int as return type.
First one works, because c is a global variable.
You typically would use return when you don't store the result in a (static) variable of your class.
public class ReturnMethod {
static int a = 10;
static int b = 5;
public static void add() {
int c = a + b;
}
public static int returnAddValue() {
int d = a + b;
return d;
}
public static void main(String[] args) {
add();
//not possible to access c here
//System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In that modified example, there would be no way for you to access the result of the add() method.
You should probably read about Scopes in Java.
You have a class variable c & d. These variables are associated with the class and stored in heap. If you assign a value back to it and you can access it without a explicit return statement. But if you have declared d inside the method then return statement is required to give the value back to the caller.
The reason that you are able to access the value of class variable c is that it has been initialized as static. Had this not been the case the information in the c variable would be lost as soon as the add method ends. The reason methods have return value is that they user can get the updated value , if there are any manipulation in the object data. In this case there is a very small, what if there is series of manipulation with the data. In that case the final value has to be returned to the calling object which without return statement is not possible.
Its totally depends upon our requirement whether to return a value from our method or update instance variable. Some time we just want to process a value and get back the result in and result will be used in different manner, in this case we need to return value from method.
For example
java.lang.Math.sqrt(double a) method return a value and we use returned value as per our need OR requirement. Can you think if this method does not returned any value then what it should update, I think this method useless if it does not returned any value.
The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists. So you can print the value of Variable C outside the method.
However, if you had declared a local variable in the method add(), then print statement System.out.println("c: " + c); will print the default value for variable c. That is zero in this case.
Related
I am pretty new to coding, I want to write a static method to set a count value to 1000.
I tried doing things like
public static int setCounter(){
return 1000;
}
When try to use this method in another to increment the count
such as someVariable = symbolic constant + setCounter()++;
return someVariable, it gives me an unexpected type error, required variable, found value. What am i doing wrong?
edit*
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static int resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method
An static property is associated with the definition of the class, and there is only ever one definition of the class. An instance is created whenever you use the new keyword on the class. All instances are keep their own private data from the static class. When using a class instance you can access the static variables but not the other way around.
You use the term constant, but I think you might have a bit of a misunderstanding of what that implies. Constants are often declared as static final values that are immutable (they can never be changed). You should not be able to modify a constant. A static value can be mutable if you so desire, and this is what we would sometimes refer to as a stateful singleton.
Consider these two examples... one modifies an instance variable, the other a static variable.
class InstanceFoo {
int i = 1000;
int resetCounter() {
i = 1000;
return i;
}
int getAndIncrement() {
return i++;
}
}
class StaticFoo {
static int i = 1000;
static int resetCounter() {
i = 1000;
return i;
}
static int getAndIncrement() {
return i++;
}
}
In the first example you need to use an instance to access the variables.. i.e. you need to instantiate it with new:
InstanceFoo foo = new InstanceFoo();
System.out.println(foo.resetCounter()); // 1000
System.out.println(foo.getAndIncrement()); // 1000
System.out.println(foo.getAndIncrement()); // 1001
System.out.println(foo.getAndIncrement()); // 1002
System.out.println(foo.resetCounter()); // 1000
In the second you access the static value. Statics can be referred to by to the class definition:
System.out.println(StaticFoo.resetCounter()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1001
System.out.println(StaticFoo.getAndIncrement()); // 1002
System.out.println(StaticFoo.resetCounter()); // 1000
In your example you are trying to increment the counter by doing resetCounter()++. This will not work for a separate reason entirely from being static or instance. Primitive values in Java (like ints, doubles, floats, etc) are pass by value, not pass by reference.
In a very simplistic sense, this means that once you return a primitive from a method like resetCounter, you are actually passing a copy of the value. You then incremented the copy, but the value associated with the class remains the same (because you incremented only the copy of the variable). You need to call the postfix operator ++ on the variable itself, not the value returned by the method. i.e. If I have
class StaticFoo {
static int i = 1000;
static int get() {
return i;
}
}
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1. the copy is then destroyed
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1, the copy is then destroyed
System.out.println(StaticFoo.i); // prints 1000
System.out.println(StaticFoo.i++); // prints 1000 and now a postfix is applied to the static variable
System.out.println(StaticFoo.i++); // prints 1001 and another postfix is applied to the static variable
System.out.println(StaticFoo.get()); // prints 1002 because two postifx operators were applied to StaticFoo.i.
Hope this helps you get started.
I think that you are assigning value to a non compatible data type varaiable.
See my code for reference:
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int a = 10 + setCounter();
System.out.println(a);
}
public static int setCounter(){
return 1000;
}
}
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static void resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method
Here's a Interview question.
Question:
public class test {
public static void main(String[] args) {
int a= 10;
int b=10;
method(a,b);
System.out.println(a);
System.out.println(b);
}
public static void method(int a,int b){
//**Under the premise of not changing the original question, how to write this function in the main function to output a=100,b=200?**
}
}
Answers:
import java.lang.reflect.Field;
class Text
{
public static void main(String[] args) throws Exception
{
int a = 10;
int b = 10;
method(a,b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
private static void method(Integer a, Integer b) throws Exception
{
Field fielda = a.getClass().getDeclaredField("value");
fielda.setAccessible(true);
fielda.set(a,100);
System.out.println("a = " + a);
Field fieldb = b.getClass().getDeclaredField("value");
fieldb.setAccessible(true);
fieldb.set(b,200);
System.out.println("b = " + b);
System.exit(0);
}
}
And we can overwrite function print. in function 'method. etc...
So, my questions are:
Why a.getClass().getDeclaredField("value") can get variabe "a" from method main? I checked each item of a.getClass().getDeclaredFields returned array in debug mode, but did not find any regularities.
Are there any refers about every item meaning of a.getClass().getDeclaredFields returned array.
I know that methods' inner variables save in stack memory,and shared in the same thread. Can we change variable main's "a" value through Reflection or Using a new Java classloader?
The solution is a big disguise. It doesn’t change the variables of the main method at all. Note that it also changed the question’s method declaration from void method(int a,int b) to void method(Integer a, Integer b) (I’m not sure whether this is allowed for solutions), to enforce a boxing conversion from int to Integer. (It also added throws Exception declarations that weren’t in the original code).
Therefore, the a.getClass().getDeclaredField("value") expression doesn’t access anything from the main method, but the value field of the wrapper class java.lang.Integer. Then, access override is used to modify the value field.
But note that this nasty hack still has no effect on the main method. Since the main method uses int primitives, these values are unaffected by any manipulation of the java.lang.Integer instances. That’s why the solution uses another trick—it does the printing itself using the lines
System.out.println("a = " + a);
and
System.out.println("b = " + b);
followed by
System.exit(0);
Since these print statements are using the Integer objects, they are affected by the hack, whereas the System.exit(0) call ensures that the method never returns to the main method, so the main method’s print statements are never executed.
Once you understand the “do the printing yourself and exit the JVM” part, you recognize that the entire Reflection hack is entirely unnecessary. You can achieve exactly the same using
public static void method(int a, int b) {
System.out.println("a = 100");
System.out.println("b = 200");
System.exit(0);
}
This does exactly the same as the solution and it doesn’t even need to change the question’s method signature. But, of course, without the distracting Reflection hack, it’s more obvious what’s actually going on.
That said, Reflection doesn’t offer any way to access local variables. You would need a debugger for that. Since you also asked for a ClassLoader, you can manipulate the code of a class to use different values, but that wouldn’t fulfill the question’s requirement of doing it inside of method, i.e. while the code in question is already running.
Is it necessary to always initialise the result variable in the function
For example
Public class Calculator
result=addition(a,b);
Public static int addition(int a, int b)
int result;
result =a+b;
return result;
You don't need to have a result variable at all. You need to make sure that every possible way that execution can reach the end of your function (without just throwing an exception) means you get to a return statement, and every return statement has an appropriate express to evaluate, but that doesn't mean you need a separate variable. Your example could be written as:
public static int addition(int a, int b) {
return a + b;
}
If you do use a variable, you'll need to make sure it's definitely assigned before you can read from it, including in a return statement. For example, this won't work because result hasn't been definitely assigned:
public static int addition(int a, int b) {
int result;
if (a < b) {
result = a + b;
}
return result; // Invalid! result may not have a value
}
Where possible, it's generally a good idea to initialize a variable at the point of declaration. So if I were writing this code and wanted a result variable, I'd have:
public static int addition(int a, int b) {
int result = a + b;
return result;
}
Now, looking at your sample code again, you've got another variable used when you call the method:
result=addition(a,b);
It's not clear where that variable would be declared (which is one reason to avoid just posting pseudo-code in questions) but it's completely separate from the result variable in addition, which is local to the addition method. The two variables happen to have the same name, but they're otherwise unrelated. For example, you could easily have:
int sum = addition(a, b);
or call another method with the result instead of assigning it to a variable:
System.out.println(addition(a, b));
Or you could just ignore it entirely:
addtion(a, b); // Valid, but pointless unless there are side-effects
This is the code I have, please look at it before you read the question
package ict201jansem2012;
public class Qn3b {
public static void main(String[] args) {
int a = 1;
int b[] = {4,5};
String s = "Good luck!";
method1(b[1]);
System.out.println("(1) b[0] = "+b[0]+"; b[1] = "+b[1]);
method2(b);
System.out.println("(2) b[0] = "+b[0]+"; b[1] = "+b[1]);
method3(a);
System.out.println("(3) a = " + a );
method4(s);
System.out.println("(4) s = " + s );
}
public static void method1(int b) {
b = 7;
}
public static void method2(int[] b) {
b[0] = 3;
}
public static void method3(int a) {
a = 3;
}
public static void method4(String s) {
s = "UniSIM";
}
}
Output:
(1) b[0] = 4; b[1] = 5
(2) b[0] = 3; b[1] = 5
(3) a = 1
(4) s = Good luck!
So my question is ,
This is intresting for me to know as learning programmer. The int b array 0 index value has changed, but not the other variables like the String s and int a. Before i ran this program I roughly thought in my mind that the variable will change their values as the methods are called ,this is because the method is being called and the main method vairable such as a,s and b array are passed and then they are being modified.
So in a nutshell why is that the b array 0 index is changed while the other variables are not changed?
Because you said you were a beginner programmer, I'll do a little writeup to explain (or try to explain) exactly what is happening.
It is because you are passing an argument to your method1 - method4 methods
These arguments, themselves, are references to other objects.
When you use the assignment operator, an equals sign, you overwrite that reference for the value in the current scope - where variables can be 'seen'.
In your code:
In the case of method1 you are creating a new reference, the variable can only be seen within that scope. That is, when you then go b = << expr >> you are assigning the variable b within method1's scope the value, not b in the main scope. The same is true of your method3 and method4 methods, you are assigning a new value to the respective variables within that scope, as you are creating new references rather than altering the original objects.
But, method2's code behaves differently, this is because you are mutating the object inside that code. You are altering the object directly - rather than creating a new reference inside that scope.
Consider the code below
int[] array = new int[] {1, 2};
public void test()
{
method1(array);
System.out.println(array[0] + ", " + array[1]);
method2(array);
System.out.println(array[0] + ", " + array[1]);
}
// because we are working with objects, the identifier, can be different to the arrays identifier
// in this case, I've chosen to use 'a' instead of 'array' to show this
public void method1(int[] a)
{
// this mutates the array object
a[0] = 2;
}
public void method2(int[] array)
{
// this overwrites the method2.array but not the global array
array = new int[] { 1, 2, 3 };
}
We create a new array, with identifer 'array' in the global scope. (In Java, this would be the classes own scope)
In method1, we take an argument, which is the same object being passed as the global array object, so when we mutate it, both objects will change. So, the first print statement will be
"2, 2"
Where array[0] has been altered
N.B. Because we dealing with objects, the 'name' of the variable doesn't matter - it will still be a reference to the same object
However, in method2, we take an argument, like in method1, but this time we use the assignment operator to assign that variable to a new value in the scope that it's currently in - so the global array isn't altered, so we still print out
"2, 2"
For a beginner programmer, I would personally write a few test programs where you get to fully understand how variables and scopes work.
But just know, everytime you create a new block of code, a new scope is created, local variables to that scope can only be seen in that scope and ones below it.
For instance:
public void test()
{
int a = 5;
method1(a);
System.out.println(a); // prints 5
}
public void method1(int a)
{
// a is only viewable in the method1 scope
// and any scopes below it, that is, any scopes created within method1
// and since we use an assignment operator, we assign method1.a a value, not global 'a' a value
a = 123;
if (true)
{
// this is a new scope, variables created in this block cannot be seen outside it
// but can see variables from above it
System.out.println(a); // prints 123
}
}
Here, we create a new scope inside method1 inside the if statement, which can see a above it. However, because method1 and test's scopes are both independent, when we use the assignment operator, we assign the value of a to the local scope. So a is different in both test and method1
I hope you understand better now.
I'm not very good at conveying things, but if it even helped a little bit in understanding scopes I did well, plus, it was fun.
Java is pass-by-value, but most values (everything that's not a primitive, in this case int[] and String) are references, which means they act like pass-by-reference.
Here's a nice writeup: http://javadude.com/articles/passbyvalue.htm
arrays are special type of objects and memory will be allocated on HEAP. When you pass array as parameter to method it will be pass as reference-value (copy of the reference).
This means initial b and this new reference points to same object. Unless new reference points to another object, changes on this reference will reflect on same object. That is why you are seeing value reflected on original array.
All of the values were passed TO the inner methods, but the inner methods returned nothing. However, method2 modified the internal value of the array that was passed to it, so that inner value appeared modified on return.
Note that method2 is the only one where you did not assign to the variable (parameter) itself, but rather assigned to an element of the object whose reference was passed in.
There is a critical difference between modifying the reference (pointer) to an object, and modifying the object itself.
If this class is used in multi-threaded environment and say 100 threads calling this method at same time .
Case 1 : instance method
public class test {
public int add(int a , int b ){
return a+b ;
}
}
case 2: static method
public class test {
public static int add(int a , int b ){
return a+b ;
}
}
Please answer both cases .
Since you are not using any state/instance variable you do not need to synchronize the method or the object.
A friendly suggestion: make the method static. Ans call it on the class.
It does not need any synchronization because all the variables are local. i.e, no variable is actually shared between any of the callers.
If you did this, you would need sync because var c is shared. Before c was retrieved in the final 'return c' another thread may have already modified it.
public class test {
int c = 0;
public int addKeep(int a , int b ){
c = a + b;
return c;
}
}
An other answer here says to make it static. Well, it depends on what you need to do. If the add(int a, int b) is a behaviour that subclasses could override, then keep it as an instance method. If it was part of a Math.class per-se, then make it static as it will likely never be needed to be over-riden.
If object is mutable and you are doing read-update operations then only we need to use synchronization block for getter and setters(i.e. mutating methods ).