0% found this document useful (0 votes)
2 views16 pages

Thread & Assertion

The document discusses assertions in Java, highlighting their use for debugging and internal consistency checks, while cautioning against their use in production code. It also covers multithreading, explaining how to create threads by extending the Thread class or implementing the Runnable interface, along with the advantages of multithreading. Additionally, it outlines flow control statements, including conditional and iterative statements, which guide program execution based on conditions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Thread & Assertion

The document discusses assertions in Java, highlighting their use for debugging and internal consistency checks, while cautioning against their use in production code. It also covers multithreading, explaining how to create threads by extending the Thread class or implementing the Runnable interface, along with the advantages of multithreading. Additionally, it outlines flow control statements, including conditional and iterative statements, which guide program execution based on conditions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
LAssertions Assertions in Java are a way to tgp ass to verify that a certain co; hai nition holds intended for use in debugging ane aM. Assertions are mainly Assertions are used with the 4 Production code, evaluates t0 £a1se, an Asser be displayed ifthe assertion Syntax: TLONError is thro fils, ee + condition: A boolean expression that shouta be nu ithe assumpti + errorMessage (optional): A message that will be displayed ite cee Using Assertions 1. Assertions should not be used fe Public methods. They are intended for internal consistency checks and debugging, Use exceptions for validating method arguments in production code, 2. Assertions can be disabled in during development and testing Assertions are a usefull tool for catching lo ensure that your code behaves as expected, By default, assertions are disabled in Java. You need to enable the enableassertions) flag, Production environments, They should be use to catch bugs gical errors early in the development process and can help "m at runtime using the ea (or - Command to Enable Assertions: C:/USER/X/DESKTOP# java -ea ClassName ublic class AssertionExample { Dbl ends etd eae ering) gel i int x= 5; int y = 107 ddoete ney 2 should be Less than y7 system-out printin("% is leas than 9") ’ habits class Ae denen eet | AA : public static void main(Strin ine age = 167 ‘or voting check if age is valid f // Assertion co check Sf 29° Oe oe least, 10" assert age >= 18 7 nage is valid for votin [Link]-printin ("Age i yster 103 | Pa8e [Link] Class ‘5,Thread Class to execute multiple tasky erating system : Tread 1s “easy fare Oxsensed — ~ 2 ProCena » 41m. oD procenpr Givestime t Ja round robin ¢ zs . Borns a ‘i Fire 3) gunning Get time por excutton - —- condiver 2) =a’ —=— a Running C suse a heaq or sain rewme C) jai] —) mus = sept] (Gab) Renan _ | —, POrtp . sowe even, [oP intergace feet) oir, Witenes Suse saw os eM jane Vein ctor eae et emt? i PEVINC FRI ORCI ee Saemne ciate 7 ead HT a aiirtocl # = nes Mestad C20) ee le stort Os : ase Petar PEON BL impreR Py Perey aan Cotan # iwaiemer'« Pumas ke tmpemers HE Nang) mem of Liat a tread Ing AERA Oncbyey wovemrated frtm tes Fhneebre ” eeyy pa . bs we fongee ch metic) (Ol we trrcodt Claw A impemert Cumabe 1 told. van td - fer? ) é 3 Cak 8 iwtemert Cemarte a rer ee rt tes Chapter Chree (Ch j Flow control statements WA Navigating the Path of Program Logic D —— Flow control statements are fundamental constructs in programming that dictate the order in which enable a program to make decisions, repeat actions, and alter its execution path these; iterative looping statements—such as “for’, ‘while’, and 100 code executes. They Jased on conditions and inputs. Among: _JgrwhIE”Toops—allow repetitive execution of code blocks, facilitating tasks that require rep ditional —like“if,, ‘else’, “switch’, and “case” statements—enable or iteration. On the other hand, Con © the program 10 ch ferent execution paths-based on various conditions another type is branching if ike a Conditional statement (switch , case, break, continue statements) statements it functions Together, these flow control mec! flexibility needed to create dynamic and responsive programs. Jhanisms—often referred to as control flow statements—provide the ecause they help your program make decisions Conditional statements are essential in programming b tions. They help in controlling the flow of and execute different actions based on certain condi ‘execution, enabling a program to handle various scenarios dynamically sil Page OC — Conditional Statements: "else (condition) 7 true : false Switch zt Melee iteise-if Nested-it_) fe 0) [eeonatmen) | fimconatieny — ) (Meeranon » Oral , ~~ ; ane >| ‘m0 meonavon a) am ikrue FF 52| Page ) //(age >= 18)~ so "You are an adult." is printed. : int age = 207 boolean hasID = trues if (age >= 18) && (age <= 65) && hasID) { You are eligible."); Evaluates to true, [Link] .printin(™ ) Ji (lage >= 18) 66 (age <= 65) && hasID)- Evaluates to Eruey 30 ‘you are eligible." is printed Single Statement without Brackets: Jy a single statement following it, the curly braces {) are If the if statement contains on! optional. However, omitting them can lead to confusion or errors if you add more statements later. if (age >= 18) system. out. Pp: system. out print1n( intln("You are an adult.")i "Welcome! In this example, only the first [Link]("You are an een et Og ee oe The — second [Link]("Welcone!"); will always execute regardless of the be the desired behaviour. condition, which might not rect statements are executed based on the Using Brackets: 1e block of code. To avoid con! condition, use curly braces { In Java, the concept of con including if, while, do-while, ‘the condition must evaluate execution path of the code. fusion and ensure that the coi } to clearly define th ditions is fundamental to other control flow statements, for, and nested if statements. The core principle is that to a boolean value (true or false) to determine the 2. If- Else Statement: tatement that allows a program to fied condition is true and another block of code ifthe condition ‘within a program, enabling different paths of execution The iftelse statement in Java is a fundamental control flow st ‘execute one block of code if a speci is false. Itprovides a way to make decisions based on the evaluation of a condition. syntax: if (condition) { 7) code to be executed if the condition 4s F5ve ) else { /7 code to be executed if the condition 1S false ) Example: if (score >= 60) { system. out .printin("Pass") i 53 Page else ( [Link] .printin ) ("pail") 3. Nested a eal statement that is placed inside another if statemeny, Anested ifs is allows you to check multiple conditions in @ hierarchics manner. Essentially, a nested ig hierarchi . Esse statement lets you create more complex. decision-making logic by evaluating additiona) statement i Nn, conditions based on the outcome of a previous conditio Syntax: if (condition) { | // Code to be executed if condition] is true £ (condition2) { oo : " Code to be executed if both condition] and conditio: are true ) else ( // Code to be executed if condition! is condition? is false ) } else { // Code to be executed if conditionl is false > Example: int grade = 85; // Example grade boolean isInvolvedInExtracurricular = true; // Bxample extracurricular involvement if (grade > 80) ( if (isInvolvedingxtracurricular) { [Link]("Eligible. } else { [Link]("Not Eligible."); , ) else | [Link]("grade is not high enough ) Conditional statements help your program make decisions by checking condit tic Jace gaerimecondon cinco. By wie. ae eet and nese stem ¢. By using if, ifelse, ths and handle var pected under You can guide the program through different pat ‘You can ensure that your program behaves as ex 4. If- Else -If Ladder s4| Page Symax: Af (condition) 17 code else © be executed $f condition: ( if (condition?) a. 11 Code to ‘ to be executed if cong ondition2 2 is true £ none of them are true “Excellent,” "Good," "Average," achieve this: if (grade >= 99) System. out .printin( else { if (grade >= 70) [Link]("Good”) ; else if (grade >= 50) System. out .printin ("Average"); Valuated and classified into categories and "Poor" Her Poor” Here's how you can use an ite if ladder leit to "Excellent" else system. out .print1n ("Poor") ; ) If there is no if block (i.e no { } then the immediate statement is condidered the only statement of If /else block) ae Iterative Statements block of code Iterative statements, or loops, it ire control flow statements used to exect ive tasks and repeatedly based on_a ion. They are essential for performing 1 ‘automating repetitive processes within a program. These statements help manage tasks that require the same operation to be executed multiple times, reducing the need for redundant code. Iterative statements are needed when you have'a task that involves repeating operations until a specific condition is met. 1. While Loop a ‘The white loop repeatedly executes a block of code as long asa specified condition i tre Syntax while (condition) { 47 Code to be executed while the condition is true ) Here’s an example that prints numbers from I to 5 using a white loop int number = 17 while (number <= 5) { ; System. [Link] (number) number*+7 , In this example: sie s5|Page dlock of bade «s exeCUEY 2. Do-While Lao? arth vse op DEES MS atleast once before the condition i tested. erate Over AMS a capa is phe fOr-eaon which as used #0 i: [Another spec peop te £0 Tne char ara collections. We will discuss the £ox-e2< Syntax a ‘a code to be executed at least once and ther repeatedly while the condition is true while (condition); . Here's an example that prints rurbers from 110 Swsing a do-vhite oP: int number = 1) do { [Link].print1n (number) } number++7 } while (number <= S)e ‘The code inside the do block is executed first. The condition is checked after the code execution, and the loop continues as long as number is Fess than or equal t0 5. 3. For Loop — The for loop is used to execute a block of code a specific number of times, It is ideal for scenarios where the number of iterations is known beforehand, Syntax for (initialization; condition; update) { // Code to be executed for each iteration ) Here's an example that prints numbers from 1 to 5 using a for loop: for (int number = 1; number <= 5; numbert+) { system. out .printin (number) ; , Inthis example: Initialization: int number = 1 sets up the starting value of number and will be executed just once in the beginning of loop execution Condition: nunber <= § determines how long the loop will run, Update: nunber++ increments the nunber after each iteration, Both whiie and do-whi le loops are used to execute a block of code repeatedly based on & condition, but they have key differences in how and when they evaluate the condition, io-vhiie Loop ‘ondition |Condition is checked before The}Condi ion is checked after the code [Check [code block executes. block executes. Se) Pease 7 Code to be ex, [Suitable “When th lterations is not kno while (number <5) je |] [Link] numbert+; It condition nunber < Pll ifthe condition is hile (condition) | find you want to skip execution ifthe [condition is false initially, jint number = 6; [The code block inside the white loop| Outcome |fdoes not execute NOt execute at false initially cuted) 'e number of own in advance| 7 number); because the| 5 ls false Initially, oo [Sultable when you need to ensure that Ihe code block is executed atleast once, Fezardless of the initial condition, [eens int number = 6; ldo ( [Link] println(aumber), umber } white (number <5); [The code block inside the do=wni1e loop} Jexecutes once, printing 6, before checkin the condition number < 5, The loop terminates after the first execution since he condition is fase. Branching/Jumping with the Switch Statement in Java ‘The switch statement in Java is a control flow statement that allows the execution of one block of code among many possible options based on the value of an expression. It is an alternative to multiple if-e1se statements, particularly when there are several conditions to evaluate based on the same expression. Conditions an \d Restrictions «Expression Type: The expression in @ switch statement must evaluate toa value that can be compared to the case labels. This includes primitive data types (such as t er, Character), corresponding wrapper classes (like Integer, C! Case Labels: Each case label must be a constant expression, and it must be unique within the svicch match tl ‘+ Break Statemer he expression value. If block. Duplicate case labels will result in a compile-time e Default Case: The default case is optional but recomment i ‘ot included, no action is taken if there's no match. int: A break statement is used to exit the switch executed. Without a break, execution will continue: Syntax switch (expression case valuels // Code to break; case value2: 7/ Code to v4 be executed be executed int, char, and enun) and their but not floating-point types or objects. ror. ded. It executes if none of the case labels block after a matching case is to thenext case. if expression equals valuel f expression equals value? s7|Page break: // Additional cases does not default: dq if expression ecute // Code to be ex cases ) Example Consider a scenario where you want to Monday, 2 for Tuesday, ete.) int day = 3; // Example value print the name of a day based on a number () f, switch (day) { case 1: ae system. out .print1n ("Monday") break; case 2: on system. [Link] ("Tuesday") + break; case 3: an [Link].print1n ("Wednesday"); break; case [Link] .printin ("Thursday"); break; case 5: [Link] ("Friday"); break; case 6: System. out .printIn ("Saturday") ; break; case 7: System. out .print1n ("Sunday") ; break; default: [Link] ("Invalid day"); break; y In this example: Expression: day is compared against each case value. Matching Case: If day is 3, it matches case 3, and "Wednesday" is printed. Default Case: If day does not match. any of the case Values, "Invalid day" is printed. The switch statement simplifies handling multi ple conditions based on a single expression and can make the code more readable and manageable cx “ompared to using multiple if-e1se statements. Why break is Necessary in switch Statements ????? Without break, execution will continue to the next case label, regardless of whether it matches oF not. This behavior, known as "fall-through,"" can lead to unintended outcomes Properly managed. 7 Using beak ensures that once a matching case block is statement and does not continue executing subsequent executed, the program exits the sui tc case blocks. 5a Page a without break: Ifthe bre. Fea statements were. aos ‘Srtted. once the case MacA eresuten the angen would continue executing the case 4 bios block ends. Sse 4 block and beyond! unt! weseuntes ena manent or the sxitcn block is S ensure that ON the matched case Bik at case Bah anesthe the swat ‘The break statement is also used to terminate \ 7 Ns s to the statement immediately following the Se sama x ese o€ switeh statement amt taster gomtrol for (int i= 0; i < 10 if (i == 5) ¢ 7 break: // Exit loop wh ; nA equate $ ,_ S¥[Link]: The loop will terminate when i equals S, and the program will continue with the oote following the loop. Use of continue Statement The continue statement is used to skip the current iteration ofa top ad proce with he weXt joes not terminate the loop but rather skips the remvaininyg cowle in the current OOH wo iteration. iteration. for (int i = 0; i < 10; ite) ( if (i 8 2-== 0) ( continue; // Skip even numbers ) [Link](i): // Prints only odd numbers } When i is an even number, the continue statement is executed, skipping the [Link] -printin (i) statement and proces with the next iteration, ‘asa result, only odd numbers are printed. rts enhance control flow management it loops and conditional we stateme programming. Both break and contin\ ater flexibility and precision in statements, providing gre solPage

You might also like