Nested If in Java

Java’da iç içe bir if ifadesi( nested if  ), başka bir if veya else ifadesinin hedefi olan bir if ifadesine atıfta bulunur. Bu, iç if ifadesinin yalnızca dış if ifadesinin test ifadesi doğruysa yürütüldüğü anlamına gelir.

Java’da iç içe bir if ifadesinin sözdizimi aşağıdaki gibidir:

if (test expression 1) {

// Executes when the test expression 1 is true

if (test expression 2) {

// Executes when the test expression 2 is true

}

}

Bu örnekte, iç if ifadesi yalnızca dış if ifadesinin test ifadesi doğruysa yürütülür.

İç içe if ifadeleri, başka ifadelerle de kullanılabilir. Bu durumda, iç if ifadesi, dış if ifadesinin test ifadesi doğruysa ve iç if ifadesinin test ifadesi de doğruysa yürütülür. Dış if ifadesinin test ifadesi doğruysa ve iç if ifadesinin test ifadesi yanlışsa, iç else ifadesi yürütülür.

if (test expression 1) {

// Executes when the test expression 1 is true 

if (test expression 2) {

// Executes when the test expression 2 is true

} else {

// Executes when the test expression 2 is false

}

}

Birden fazla if ve else deyimi düzeyini iç içe yerleştirmek de mümkündür. Bu, karmaşık bir programda birden çok koşulu test etmek için yararlı olabilir.

if (test expression 1) {

// Executes when the test expression 1 is true 

if (test expression 2) {

// Executes when the test expression 2 is true 

if (test expression 3) {

// Executes when the test expression 3 is true

} else {

// Executes when the test expression 3 is false

}

} else {

// Executes when the test expression 2 is false

}

}

İç içe geçmiş if ifadelerinin, özellikle birden fazla iç içe geçme düzeyi olduğunda kodun okunmasını ve anlaşılmasını zorlaştırabileceğini akılda tutmak önemlidir. Bu gibi durumlarda, switch deyimi veya çoklu if-else deyimleri gibi farklı bir kontrol yapısı kullanmak daha uygun olabilir.

Ayrıca, ‘&&’ veya ‘||’ gibi bir mantıksal işleç kullanabileceğinizi unutmayın. iç içe if ifadeleri kullanmak yerine birden çok koşulu birleştirmek için. Bu, kodu daha okunabilir ve anlaşılması kolay hale getirecektir.

Özetle, Java’daki iç içe geçmiş if ifadeleri, bir programcının bir program içindeki birden çok koşulu test etmesine izin veren bir tür kontrol yapısıdır. Belirli durumlarda yararlı olabilirler, ancak kodun okunabilir ve bakımı yapılabilir olmasına özen gösterilmelidir. Birden çok koşulu birleştirmek için mantıksal işleç kullanmak daha iyidir.

İbrahim Ebrar AKÇAKOYUN