I'm kind of new to Java. I want a method that will use submethods(?). I want something like this:
Math.Addition(1, 1, X in this case, integer of users choice for the output);
The output would be stored in the variable X. But I also want to do something like this:
Math.Subtraction(2, 1, X);
How would I do this?
Create a class called Math.
and Have two methods inside it named 'Addition' and 'Subtraction' with required arguments and put the logic for each inside the method.
public class Math {
public static int X;
public static int Addition(int a, int b, String choice) {
X = a+b;
return X;
}
public static int Substraction(int a, int b, String choice) {
X = a-b;
return X;
}
}
You'll probably need to return the value in order to assign to x. e.g.
X = myClass.add(1,1);
Related
This question already has an answer here:
Returning a value from one method to another method
(1 answer)
Closed 4 years ago.
public static void main(){
getNumber();
printNumber();
int x;
}
public static int getNumber(){
int x = 5;
return(x);
}
public static void printNumber(){
System.out.println(x);
}
I am a total beginner, sorry for such a simple question. The above fragment of code is what I tried.
public class Test {
public static void main(String[] args) {
int x = getNumber();
printNumber(x);
}
public static int getNumber() {
int x = 5;
return x;
}
public static void printNumber(int x) {
System.out.println(x);
}
}
First of all:
public static int getNumber(){
int x = 5;
return(x);
}
Creates another local variable x. So that assignment affects only the x that "belongs" to getNumber(). The static field x of your enclosing class stays at its initial value of 0.
But there you go:
public static void printNumber(){
x = getNumer();
System.out.println(x);
}
Of course, a first step for writing more reasonable code: you decide whether you want to have that "global" field that all methods of your class can use, or if you want to not do that.
Meaning: either you use that field, then your method just updates x, and the other method prints it. Or your class doesn't have that field, and your two methods work by getNumber() returning a value, and then printing that returned result.
Can you firstly explain, what you want to do by this code?
Let's go through your code:
I concider method printNumber() to be excess because It's just wrapper for System.out.println method, we can use it derectly in our code.
Method getNumber() could receive some paramater, for example getNumber(int a). With such improvement we would be able to call getNumber from our main method and pass to it variable that we define in main method. Than getNumber could perform some operation, forexample a * a and return this result.
Also main method of java programm must look like below.
public static void main(String[] args) {
int x = 5;
int resultOfGetNumber = getNumber(x);
System.out.println(resultOfGetNumber);
}
public static int getNumber(int a){
return(a * a);
}
So we define variable x in our main method and passes it to the getNumber method, which returns the square of received variable. Then in main method we assing result of getNumber method to the int variable resultOfGetNumber. Then we pass resultOfGetNumber to the System.out.println method, which prints this variable to the console.
i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.
Say I have two methods in class 1. Can I pass a parameter to class 1 constructor which would then pass the parameter to both of the methods? Something like the example code below:
class stuff{
int c;
stuff(x){
c = x;
}
public static int sum(int a, int b){
stuff self = new stuff();
return c*(a + b);
}
public static int mult(int a, int b){
return c*(a*b);
}
}
class test{
public static void main(String args[]){
stuff foo = new stuff(5);
System.out.println(stuff.sum(1, 2));
System.out.println(stuff.mult(1, 2));
}
}
So from class test I want to access both methods from class stuff, while passing the parameters for the methods, but I also want to pass a global class parameter (5 in this case). How can I do this?
First two important things :
Constructors are designed to create instances.
Class names should start with an uppercase.
As you write :
class Stuff{
int c;
Stuff(x){
c = x;
}
...
}
Here you assign x to a c field.
But sum() and mult() are static methods.
They cannot use the c field.
Make these methods instances methods and you could use c in these methods.
public static void main(String args[]){
Stuff foo = new Stuff(5);
System.out.println(foo.sum(1, 2));
System.out.println(foo.mult(1, 2));
}
And use the current instance in these instance methods to sum or multiply current value with passed parameter values :
public int sum(int a, int b){
return c*(a + b);
}
public int mult(int a, int b){
return c*(a*b);
}
Just remove 'static' keyword from your methods, and do not create new instance of 'stuff' in a sum method. Instead just create instance of stuff in test#main method like you do right now, and it will work like you wanted.
Since Java 8, the Integer class has a static sum method that adds two integers:
public static int sum(int a, int b) {
return a + b;
}
I can pass this method to higher-order functions via Integer::sum which I find more readable than (a, b) -> a + b.
Is there a similar static method for multiplication, so I don't have to write (a, b) -> a * b? I couldn't find one in the Integer class.
You can make it yourself:
public static int mult(int a, int b) {
return a * b;
}
This might seem obvious in retrospect but outside of that I don't believe there's actually a jdk-included method which multiplies for you, except for Math#multiplyExact (Math::multiplyExact), though this might be more than you need.
Math::multiplyExact
static int multiplyExact(int x, int y)
Returns the product of the arguments, throwing an exception if the result overflows an int.
I realize that if I pass an object as a parameter of a function and do changes to it, the changes "stay" with the object. But it is not the case for an integer.
public void start() {
int x = 100;
modify(x);
// I would like x to be 200 now. But it isn't :(
}
public void modify(int y) {
y *= 2;
}
So basically, is there a way to achieve what I wanted in the code above? Is it possible to modify an integer like that (like an object reference)?
While working with primitives there is no concept of "reference". But you may achieve what you want by doing something like below:
x = modify(x); may be code want.
Now x contains the results of modify(x) method invocation.
You cannot do that. Primitives are passed by value. (References are also passed by value. You can't modify an object reference; you can only modify the object that is referenced.) The best you can do is:
public void start() {
int [] x = {100};
modify(x);
// x[0] is now 200 :)
}
public void modify(int []y) {
y[0] *= 2;
}
The array reference x is passed by value, but you can modify the array elements. Note that passing an Integer won't help, because Integer objects are immutable.
Alternatively, you can redesign your method to return the doubled value and assign it in the calling code (as Nambari suggests).
A third possibility, beside passing an array or using a return value, would be to pass an object of some ValueHolder class with a getter and setter:
public class IntValueHolder
{
private int value;
public int getValue()
{
return this.value;
}
public void setValue(final int value)
{
this.value = value;
}
}
This is technically very similar to passing an array, but is IMHO a bit cleaner, i.e. it better describes your intent.
One thing you can do is get the return value of the modify() method and assign it to the variable as follows.
public void start() {
int x = 100;
x=modify(x);
}
public int modify(int y) {
return y *= 2;
}