+ 2

Do I actually have to use brackets {} in 'for' loops and 'if' statement?

Just realised that a 'for' loop or an 'if' statement doesn't actually need curly brackets (similar to c++) if there's only one line of code to execute/run. Is it considered bad coding practice not to use them? example:- for(int i = 0; i < arr.length; i++) System.out.print(arr[i]);

19th Oct 2019, 11:52 AM
rodwynnejones
rodwynnejones - avatar
3 Answers
+ 6
Using braces is recommended , even if they are not necessary. It improves code redability šŸ˜Š It's completely your choice whether to use them or not when there is single statement. But I think using them is most of the times good practice. https://www.leepoint.net/flow/if/30if-braces.html
19th Oct 2019, 11:58 AM
šŸ‡®šŸ‡³OmkaršŸ•‰
šŸ‡®šŸ‡³OmkaršŸ•‰ - avatar
+ 5
I've been wavering between using and not using them. On the one hand, the code is a bit shorter. On the other hand, if you later decide you need another line in that block (happens all the time), you'll manually have to add the curlies. And if you want to be consistent, you'll have to remove them, if you redecide to use just one line. Now, as I'm writing it down, contrary to what I've been doing, it seems plausible to just always use them. šŸ˜…
19th Oct 2019, 12:04 PM
HonFu
HonFu - avatar
+ 2
Thank you for you responses,. I'll probably use them them/not use them as appropriate, I just think the code looks 'neater'... less cluttered. Here's an example with an if..else inside a 'for' loop. (might be of interest to someone else.) int [] arr ={1, 2, 3, 4, 5, 6, 7, 8, 9}; for(int i = 0; i < arr.length; i++) if(arr[i] >= 6) arr[i] += 10; else arr[i] += 100; for(int i = 0; i < arr.length; i++) System.out.println(arr[i]);
19th Oct 2019, 12:48 PM
rodwynnejones
rodwynnejones - avatar