0

I am currently struggling with memory handling. I have an if statement and each case instantiate a new object from a class. Does this affect the memory allocation in java?

switch()
{
case 1:
test t1 = new test();

case 2:
test t2 = new test();

case 3:
test t3 = new test();

case 4:
test t4 = new test();

case 5:
test t5 = new test();

case 6:
test t6 = new test();

}
  • 2
    Note that your cases have no break: unless you end each case with a break statement, execution will "fall through" to the next case. More info: docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html – Daan Wilmer Nov 11 '13 at 16:02
  • Also note that, in Java, class names should start with a capital letter. And you must place a variable in the switch brackets, of course. – mgoeminne Nov 12 '13 at 6:52
4

No, it doesn't.

Each time your case is executed, exactly one object is allocated (except if you pass in an unhandled value, in which case nothing happens). The fact that there are a lot of new statements in your code doesn't change that; what counts is how often an allocation statement is executed, not when its byte code is loaded.

  • Thanks. got nosebleed on this "how often an allocation statement is executed, not when its byte code is loaded.". Can you site a piece of code. ) – rahstame Nov 11 '13 at 9:40
  • 3
    It's very important that you master the difference between compile-time and run-time events. Any code that changes the state of your program (not just allocation, but assignment, I/O and every other change) has that effect only when the control flow actually reaches it. If your code is within an if (or case) that is never executed, this never happens. If it is executed multiple times, it happens several times. this is why static analysis of program texts is so limited in what it can predict about program behaviour (it isn't even possible to predict wether a program terminates). – Kilian Foth Nov 11 '13 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.