+ 1
Hello can you help me in java ?
static int sum(intval1 ,intval2){ return val1+val2; public static void main (string[]args){ int x=sum(2 , 5); System.out.println(x);}} why do i use also "static int sum" when i could get the same result using only the main method ? why i cant do directly : public static void main (string[]args){ int x=2; int y=5; system.out.println(x+y);} or public static void main (string[]args){ int sum= 2+5; system.out.println (sum);} ?? thankyouu
3 ответов
+ 3
well methods provide more flexibility than doing operations directly.Imagine you had to make several sums,would you use...
int a=5;
int b=6;
int c=a+b;
int d=7;
int e=12;
int f=d+e;........
that is sooo not neat,using methods would be better like..
int c=sum(5,6);
int f=sum(7,12);
that saves more space,less variables are required and looks very neat
+ 2
so we use more methods for convenience. so we do not have to write many variables and the code is ordered. it's right?
+ 2
Absolutely. Reuse code, don't copy and paste it. The more you write the more room there is for error, but if you can spot the common patterns and abstract the code correctly then you have a cleaner and more robust code. Further, if you test a single method well you can be confident it works in many cases, whereas if you write lots of very similar code you can't really have the same assurance