Widget HTML Atas

Structure in Java

Java, like any programming language, supports both conditional statements and loops to determine control flow.

Block Scope
Before we get into the actual control structures, you need to know more about blocks. A block or compound statement is any number of simple java statements that are surroundedby a pair of braces. Blocks define the scope of your variables. Blocks can be nested inside another block. Here is  a block that is nested inside the block of the main method


general syntax in java :

public static void main (String[] args)
{
int n;
...
{
int k;
...
} //k is only defined up to here
}

more example

public static void main (String[] args)
{
int n;
...
{
int k;
int n; //error-cant redefine n in inner block
...
}
}

Conditional Statements
The conditional statement in Java has the form
if (condition) statement
The condition mus be surrounded by parentheses. In java, as in most programming languages, you will often want to execute multiple statements when a single condition is true. In this case, you use a block statement that takes the form

{
statement1
statement2
...
}

for example :

if(value >= 60)
{
 congratulations you passed;
}
else
{
try again;
}


While - Loop
The while loop executes a statement (which may be a block statement) while a condition is true. The general form is  while (condition) statement
example :

while (balance < goal)
{
 balance += payment;
double interest = balance*interestRate / 100;
balance += interest;
years++;
}
System.out.println(years + "years");

A while loop tests at the top. Therefore, the code in the block may never be execute.
If you want to make sure a block is executed at least once, you will need to move the test to the bottom. You do that with the

Do / while loop.
its syntax looks like this :
do statement while (condition)

example :

do
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
//print current balance
...
//ask if ready to retire and get input
...
}
while (input.equals("n"));

For - Loop
general syntax

for (index=intExpresion; continueExpresion;incrementExpresion)
{
statement 1;
...
statement n;
}

Switch - Case 

switch (comparison)
{
case 'comparison1'
statement1; break;
...
case 'comparison n'
statement n; break;
default;
statement default;
}

No comments for "Structure in Java"

Search Results Computer Programing, technological, Data Appears, RiskTool, games, memory, MIPS Computer Programing, technological, Data Appears, RiskTool, games, memory, MIPS