0% found this document useful (0 votes)
98 views14 pages

Java Control Statements Explained

The document discusses different types of control statements and error handling techniques in Java. It defines selection statements like if, if-else, and switch statements. It also covers repetition statements like while, do-while, and for loops. Finally, it discusses branching statements like break and continue, and defines exceptions and errors in Java and different exception handling techniques using try-catch blocks.

Uploaded by

pradeflx
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views14 pages

Java Control Statements Explained

The document discusses different types of control statements and error handling techniques in Java. It defines selection statements like if, if-else, and switch statements. It also covers repetition statements like while, do-while, and for loops. Finally, it discusses branching statements like break and continue, and defines exceptions and errors in Java and different exception handling techniques using try-catch blocks.

Uploaded by

pradeflx
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

MI0032 Java and Web Designing 2 Credits

Q.1 Explain different types of control statements.

Ans: Control Statements


The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements: 1- Selection Statements 2- Repetition Statements 3- Branching Statements Selection statements:

1. If Statement:
This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed . Syntax: if(conditional_expression){ <statements>; ...; ...; } Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10; if(n%2 = = 0){ System.out.println("This is even number"); }

2.

3. If-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. Syntax: if(conditional_expression){ <statements>; ...; ...; } else{ <statements>; ....; ....; } Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11; if(n%2 = = 0){ System.out.println("This is even number"); } else{ System.out.println("This is not even number"); }

4.

5. Switch Statement:
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the

case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed. Syntax: switch(control_expression){ case expression 1: <statement>; case expression 2: <statement>; ... ... case expression n: <statement>; default: <statement>; }//end switch Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday") ; break; case 4: System.out.println("Thrusday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default:

System.out.println("Invalid entry"); break; }

Repetition Statements:

1. while loop statements:


This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop. Syntax: while(expression){ <statement>; ...; ...; } Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1; //print 1 to 10 while (i <= 10){ System.out.println("Num " + i); i++; }

2.

3. do-while loop statements:


This is another looping statement that tests the given condition past so you can say that the dowhile looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once. Syntax: do{ <statement>; ...; ...; }while (expression); Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.
int i = 1; do{

System.out.println("Num: " + i); i++; }while(i <= 10);

4.

5. for loop statements:


This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true . Syntax: for (initialization; condition; increment or decrement){ <statement>; ...; ...;

} initialization: The loop is started with the value specified. condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated. increment or decrement: After each iteration, value increments or decrements. Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){ System.out.println("Num: " + num); }

Branching Statements:

1. Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements. Syntax: break; // breaks the innermost loop or switch statement. break label; // breaks the outermost loop in a series of nested loops. Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just following the loop.

2. Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration . Syntax: continue; Example:

3. Return statements:
It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method. Syntax: return; return values; return; //This returns nothing. So this can be used when method is declared with void return type. return expression; //It returns the value evaluated from the expression. Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.

Q.2 a. What is the difference between errors and exceptions? Ans: Exceptions are things you can create/throw yourself or that might be thrown because of an obvious run-time error such as trying to access a null object or reading an array out of bounds. They can also be caught and repaired by a developer. Errors should never be created, thrown, caught, or repaired. They are usually beyond the scope of your application code such as 'out of memory'. Even if you caught an out of memory error, you wouldn't likely be in a better place than the system garbage collector to fix this (and you'd have to fix it while allocating no new memory) so its better to let the system crash and repair the root cause.

Q.2 b. Explain different types of error handling techniques with a suitable example. Ans: All right, let's begin explaining what exceptions are. Just as in other programming languages, this applies to Java as well: exceptions are those errors that occur during runtime. These aren't real errors, because they are exceptions. One might call them exceptional events that can and should be handled to continue program execution. So there's "something" one has to do about them.

One of the most remarkable examples of exceptional cases and conditions is when, during program execution, the time comes for a division by zero. This cannot be done and, therefore, Java throws an exception, specifically the ArithmeticException. From the Java programmer's point of view, exceptions are objects. Throwing

exceptions is akin to throwing objects. But here's the drill: not every object can be thrown.

In order to fully understand throwable exceptions, some parts of the entire class hierarchy should be presented. There is one main class called Throwable. This class has two sub-classes: Exception and Error. An exception object must be descended from a class that is Throwable, meaning it must be an object instance of either an Exception sub-class or Error sub-class. These can both be found in the java.lang package.

Exception handling is the technique of catching the exceptions that might be thrown some time in the future during runtime. Java offers robust exception handling solutions with the try-catch-finally construct. On other hand, you can work with already-declared exceptions, such as the ArithmeticException, NullPointerException, and others. Other classes extend the Exception class-e.g., the IOException subclass from java.io.

Furthermore, we should also note that exceptions are of two kinds: unchecked and checked. Unchecked exceptions are technically RuntimeExceptions (or its subclasses). These don't need to be declared in your throws clauses, and catching them is optional, but many don't bother-they occur without the knowledge of programmers, who may not even know that those are "catchable." Most of the time, these are logic programming errors such as NullPointerException or ArrayIndexOutOfBounds.

Meanwhile, checked exceptions technically force the programmer to handle and manage them, meaning catch and cover them individually. These are derived from the Exceptions class and its subclasses, excluding the RuntimeExceptions as we discussed in the paragraph above (those are unchecked!). Checked exceptions require exception handling because they might cause program termination.

Now that we've learned the basic theory, let's fire up our IDE, and start coding!
On the previous page we mentioned that exception handling either deals with the exception in the code snippet where it occurs with the try/catch block, or throws the exception back to the runtime engine, which on its end will search for the exception handling routine that is the closest to the place where the exception occurred. It searches within the call stack that contains the sequence of method calls.

Generally, exceptions can happen due to either having an abnormal event that leads to an exceptional case, or another method has thrown the exception and now it's time to deal with it, or in the case of an asynchronous exception (which happens only when multiple threads are used and they aren't synchronized appropriately). Now we are going to cover the basics of exception handling: how to "catch" and deal with them. Java allows us to create our own Exception objects and classes-but there is a critical requirement. They must be extending the Exception class, and that's how inheritance happens. It is part of the coding standard that exceptions must be named quite "thoroughly," meaning their name should speak for themselves. throw new Exception(" This is an exception! ");

Now let's see how to catch and deal with an exception. Check out the following.

try { // this is the block of code where the exception happens // sometimes called as source/root of exception // or even called as tricky block or tricky method }

catch (Exception_Type1 e){ // dealing with this kind of exception } catch (Exception_Type2 e){ // dealing with this kind of exception } // ... unlimited number of catches are possible finally { // this block of code is always executed }

The first part of the try-catch-finally construct is the try block. This is the segment where the exception may occur. Generally it's advised to write the minimum amount of code lines here since they are executed only until the exception happens. When it does, the execution jumps to the catch blocks, where the exception types are compared. If they match, then the exception that occurred is dealt with. The finally block is always executed, regardless of whether or not an exception happens during the try block, or whether an exception could be handled within the catch blocks. Since it always gets executed, it is recommended that you do some cleanup here. Therefore, as expected, implementing the finally block is optional. The structure of try-catch blocks is similar to that of switch-case constructs. It should also be said that, in the case of checked exceptions, which must be dealt with, it is possible to either "handle" them right where they occur inside that same method, or throw them further. The latter can be done with the throws keyword. And in this case, the type of exception must be specified in the method signature. See the example: void myMethod () throws SomeKindOfException{ // method goes here }

Q.3 What is InterThread communication in Java? Explain with an example.

Ans: Consider the classic queuing problem, where one thread is producing some data and
another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable. To avoid polling, Java includes an elegant interprocess communication mechanism via the following methods:

wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ): This method wakes up the first thread that called wait( ) on the same object. notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c The highest priority thread will run first.

These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context. These methods are declared within Object. Various forms of wait( ) exist that allow you to specify a period of time to wait.

Example:

The following sample program consists of four classes: Q, the queue that you're trying to synchronize; Producer, the threaded object that is producing queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer. The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions, as shown here:

class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } }

class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it. Here is some output from this program, which shows the clean synchronous behavior:

Put: Got: Put: Got: Put: Got: Put: Got: Put: Got:

1 1 2 2 3 3 4 4 5 5

You might also like