0

This below operation providing errors while i'm adding outside of the method,

the below mentioned code declared as instance variable,and i performed addition inside the class and outside the method,

int a=10; a=a+10;

if i add this inside method then there will be no compilation errors,why??

3
  • You are trying to add up outside of method? Commented Sep 8, 2020 at 10:32
  • If your question is why you cannot simply start writing instructions anywhere in the java class the answer is simple: because java wasn't designed that way and it doesn't make sense. When would you expect those lines of code to be executed and in what order? Commented Sep 8, 2020 at 10:34
  • In a class body you can only have: member definitions and initializer blocks. The only place to put statements is within method and constructor bodies and initializer blocks. a = a+10 is a statement. Commented Sep 8, 2020 at 10:38

2 Answers 2

1

In Java, methods have the responsibility to perform operations on the instance variables. If an instance variable needs to be initialized, you can use constructor or initializer block. You can do as below:

 int a = 0; { a = a + 1; } 
Sign up to request clarification or add additional context in comments.

Comments

0

In Java int a=10; a=a+10; is not possible. but you can try this, may be helpful for you.

public class AddOutsideMethod { private static int i = 10; private static int j = i + 10; public static void main(String[] args) { System.out.println(j); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.