I have written small java code, and want to use same object which I have created in main method in other methods as well in a class. Is there any way ? I dont want to create every time new object in Checklength method just to call digitSum. I want use same o object created in main method.
Note: Without changing method properties
public class UserMainCode {
public int digitSum(int input1) {
int num = input1;
int sum = 0;
int output = 0;
int length = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
output = sum;
length = Integer.valueOf(Integer.toString(output).length());
Checklength(length, output);
return length;
}
public static void Checklength(int length, int sum) {
if (length > 1) {
UserMainCode b = new UserMainCode();
b.digitSum(sum);
}
else {
System.out.println(sum);
}
}
public static void main(String[] args) {
UserMainCode o = new UserMainCode();
o.digitSum(976592);
}
}
Any ideas ?