0% found this document useful (0 votes)
23 views37 pages

Java Unit 2 Materials

The document provides an overview of constants, variables, and data types in Java programming. It explains the different types of constants (numeric, character, string), the concept of variables and their declaration, as well as the various data types available in Java, including primitive types and their sizes. Additionally, it covers variable scope, type casting, and default values for variables.

Uploaded by

devi vijay
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)
23 views37 pages

Java Unit 2 Materials

The document provides an overview of constants, variables, and data types in Java programming. It explains the different types of constants (numeric, character, string), the concept of variables and their declaration, as well as the various data types available in Java, including primitive types and their sizes. Additionally, it covers variable scope, type casting, and default values for variables.

Uploaded by

devi vijay
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
Constants, Variables, and Data types Introduction: A Programming Language is designed to process certain kinds of data consisting of numbers, characters and strings and to provide uselttl output known as information. The task of processing data is accomplished by executing a sequence of instructions constituting a program. These instructions are formed using certain symbols and words according to some rigid rules known as syntax nlles, Constants: Constants in java refer to fixed values that do not change during the execution of a program, Java supports several types of constants, JAVA CONSTANTS Numeric constants Character constants Integerconstants Real constants Character String constants Constants Integer Constants ‘An Integer constant refers to a sequence of digits. There are three types of Integers , namely decimal Integer, Octal Integer and Hexadecimal Integer. > Decimal Integer consists of set of digits, 0 through 9, preceded by optional minus sign. Valid examples of decimal Integer constants are: 123° -321 0 454321 Embedded spaces, commas, and non-digit characters are not permitted between digits. For example, 15 750 20.000 $1000 are illegal numbers > An Octal Integer consists of any combination of digits from the set 0 through 7, with a leading 0. Some examples of Octal integer are 037 «0-435. 0551 > A sequence of digits preceded by OX consiclered as Hexadecimal Integer. They may also include Alphabets A through F ora through f, A letter A through F represents the numbers 10 through 15. Following are the examples of valid hex integers. 0X2 OX9F OXbed OX We rarely use octal and hexadecimal numbers in programming. Real Constants Integer numbers arc inadequate to represents quantities that vary continuously, such as distances, heights, temperatures and prices and so on. These quantities are represented by numbers containing fractional parts like 17.548, Such numbers are called real or floating point constants. Example: 0.0083 -0.75 435.36 ‘These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part, which is an integer. It is possible that the number may not have digits before the decimal points or digits after the decimal point. That is 215. 95-71 are all valid real numbers. A real number may also expressed in exponential(or scientilic)notation, For example, the value 215.65 may be written as 2.1565¢2in exponential notation. E2 means multiply by 10® ‘The general form is, Mantissa e exponent ‘The mantissa is either real number expressed in decimal notation or an integer. The exponent is an (eger with an optional plus or minus sign, The leter e separating the mantissa and the exponent be written in either lower case or upper ease. Since the exponent causes the decimal point to “float”, this notation is said to fepresent a real number in floating point form, Examples are: 0.65e4 12e-2 1.5e#5 3.18E3 “128-1 Embedded white (blank) space is not allowed, in any numeric constant. Exponential notation is useful for representing numbers that are cither very large or very small in magnitude, For example, 7500000000 may be written as 7.5E9 or 75E8. A floating point constant may comprise four parts: © Awhole number © Adecimal nunber © A fractional part © Anexponent Single character constants A single character constant contains a single character enclosed within a pair of single quote Example: ‘5? *X* y ” Note that the character constant *S* is not the same as the number 5, The last constan String constants ablank space. string con be alphabets. digit Examples ar “Hello Java" “2021" “WELL DONE” “?.!" “5+5" int isu sequence of character enclosed between double quotes. The characters may special characters and blank spaces. “x” Backslash character constants Java supports some special backslash character constants that are used in output methods. For example, the symbol "\n’ stands for newline character. Each of them represents one character, although they consists of two characters. These characters combination is known as escape sequences. Backslash character constants Constant_| Meaning Nb" Back space at Form feed ‘\n’ New line ar Carriage return Ae Horizontal tab A" Single quote v= Double quote ww backslash VARIABLES A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program Some examples of variable names are: © Average © Height © Total -height © Class Strength Variable names may consist of alphabets, dig following conditions: - he underscore( _)and dollar characters, subject to the 1 They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4, White space is not allowed. 5, Variable names can be of any length. DATA TYPES Every variable in java has a data type. Data types specify the size and type of values that can be stored. Java language is rich in its data types. DATA TYPES IN JAVA Primitive data type itive data type Numeric [ ft * Interface classes Arrays Non-numeric Integer ss | Floating point Characte Boolean Integer types can holt whole numbers such as 123, -96, 5639 . the size of the values that can be stored depends on the java supports four types of integer Size and range of integer types [Type [Size inimum value Maximum value byte [Onebyte | -128 127 short_| Two bytes 68 32.767, imt___|Fourbytos | -2. 147. 483, 648 2,147, 483, 647 Tong _ | Bight bytes 23, 372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807 Floating point types double-precision numb: Floating point types contain fractional part such as 27.59, - point storage. The float type values are single-preci 75. There are two kinds of floating ile the double type represents Size and range of Floating point types | Type _| Size ‘Minimum value ‘Maximum value Float | 4bytes [Link]-038 1.704038 double [8 bytes [Link]-038 1.7¢+308 Mating point data types Floating point types fo Float Double Character Type To store character constant in memory, java provides a character data type called char. The char type assumes the size of two bytes, basically, it can hold only a single character. Boolean Type ‘We want to test a particular condition during the execution of a program. There are only two values that a Boolean type can take: true or false . Boolean type is denoted by the keyword Boolean and uses only one bit of storage. Declaration of Variables ‘Variables are name of the storage location variables can be used to store a value of any data [Link] general form of declaration of variable is, type variablel, variable2 able N 5 Variables are separated by commas. A declaration statement must end with semicolon. Some valid declarations are: int count; float x.y: double pi; byte b; char cl,c2,c3; Giving value to variables A variable must be given a value after it has been declared but before it is used in an expression. This can be achieved in two ways: 1. By using an assignment statement 2. By using a read statement. Assignment statement A simple method of giving value to a variable is through the assignment statement as follows: variableName = value For example: initialvalue = 0; finalvalue = 100; yes='x" siring assignment expression is shown below: xey=zath itis also possible to assign a value to a variable at the time of its declaration. This takes the form: type varinblename = valucy char yes ="x"; double total 75.36 ‘The process of giving initial values to a variable is known as initialization. float x, y.%: /declares three float variables. inem=5,n=10; declares and initializes two int variables. intmn=10; /Ideclares m and n and initializes n Read statement We may also give values to variables interactively through the keyboard using the readLine() method as illustrated in program. Reading data from the keyboard import [Link]. DatatnputStream; class Reading { Public s { DatinputStr Inc intnumber Float floatnumber= 0.0¢; uy { [Link](“Enter an Integer: Intnumber=fnteger,parselnt([Link]): ‘[Link]("Enter a float number floatnumbers Most. [Link]()).floatvalue(): ) Cateh(Exception e) uO System out printin(“intnumber="+intnumber): [Link] printin(“foatnumber="*floatnumber);, ) ) tic void main(String args[]) min = new DatalnputStream([Link]); ‘The inpot and output of the program Enter an integer: 123 Enter‘a float number: 123.45 Intaumber=123 Floatnumber=123.45 Scope of the variable Java variables are actually classified into three kinds 1. Instance variables 2. Class variables 3. Local variables Instance-and class variables are declared inside the class. Instance variables are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global (o the class and belong to the entire set of objects that the class creates. Only one memory location is created for each class variable. Variables declared and used inside the methods are called local variables. They are not available for use outside the method definition. Local variables can also be declared inside the program blocks that are defined between an opening brace} and a closing brace }. These variables are visible to the program only {rom the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The area of the program where the variable is accessible(ie Usable)is called its scope. Nested program blocks intx=0 Block | fl : Block 2 intn =5; ( Block 3 intm=0 } UNITIL We can have program blocks within other blocks (called nesting). Each block can contain its own set of local variable declarations. We cannot however, declare a variable to have the same name as one in an outer block. The variable declared x declared in Block! is available in all the three blocks. However the variable n declared in block2 is available only in block2, because it gocs out of the scope at the end of the black2. Similarly , m is accessible only in block3. Symbolic constants “These constants may appear repeatedly in a number of places in the program. One example of such a constant is 3,142, representing the value of the mathematical constant “pi” . Another example is the total number of students whose mark-sheets are analysed by the “test analysis program"The number of students say 50, may be used for calculating the class total, class average, standard deviation etc. we face two problems in the subsequent use of such programs. They are: 1. Problem in modification of the program 2. Problem in understanding the problem. Mollifiability We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of calculations or the number 50 to 100 to process the test result of another class. In both the cases, we have to scarch throughout the program and explicitly change the value of the constant wherever it has been used. If any value is left unchanged , the program may produce disastrous outputs. Understandability ‘When a numeric values appeared in a program, its use is not always clear, especially when the saine value means different things in different places. Example, the number 50 may mean the number of students at one place and the ‘pass marks* at another place of the same program. We may forget what a certain number meant, when we read the program some days later. Assignment of asymbolic name to such constants frees us from these problems. Example, we may use the name STRENGTH to denote the number of students and PASS-MARK to denote the pass marks required in « subject. Constant values are assigned to these names at the beginning of the program, Subsequent use of the names STRENGTH and PASS-MARK in the program has the effect of causing, their defined values to be automatically substituted at the appropriate points. A constants is declared as follows final type symbolic-name = value; stant declaration are: 100; Valid examples of cor final int STRENGTI final int PASS-MARK final float PI = 3.14159; Type Casting There is a need to store a value of one type into a variable of another type. We must cast the value to be stored by proceeding it with the type name in parentheses. The syntax type variablel =(type) ‘The process of converting one data type to another is called casting. Example: int m=50; byte n=(byte)m; ong count =(long)m; From To byte short, char, iat, Jong, Moat, double short int, long, float. double char ft, Jong, Nlowt, double int Jong, float, double Tong Alot, double float double Automatic conversion Itis possible to assign a valuc of one type to a variable of a different type without a cast. Java does the conversion of the assigned value automatically . this is known as automatic type conversion. Example: byte b= 75; int a= by Getting values of variable ‘A computer program is written to manipulate a given set of data and to display or print the results, Java supports two output methods that can be used to send the result to the screen. © printQmethod = print and wait © printin() method —//printalline and move to the next line. The print() sends the information into the butler. This buffer is not flushed until a newline character is sent. As a result, the print() method prints output on one line until a newline character is encountered. Example: [Link](“Hello”); [Link](“ava"); Will display the words Hello Java on one line and waits for displaying further information on the same line. The next line by printing a newline character as shown below: [Link](“n"); Example: [Link](“Hello”); [Link](\ [Link](“Java”); Will display the output in two lines as follows Hello Java The printin() method by contrast, takes the information provided and displays it on a line followed by aline feed, [Link],printin(“Hello”): [Link](“Java”); Will display the output in two lines as follows Hello Java ‘The statement [Link]( ); rill print a blank line, Getting the result ta the screen class Displaying { public static void main(String args{]) { Syste [Link]("Sereen Display”); i<=9; i+) { forint j= { [Link]("* [Link] printin } [Link]("\n"); } System out printhn(“Screen Display Done"); } } Jsen; j++) ‘The output will be Serven Display 1 22 33003 44 4 4 $5 5 5 5 6 6 6 6 6 6 77°77 7° 7° °«7°~°7 88 8 8 8 8B 8 8 99 9 9 9 9 9 9 9 Screen Display Done Standard Default Values Every variable has a default value. If we don't initialize a variable when itis first created, java provides default value to that variable type automatically. Default values for various types Types of variable Default value byte Zero: (byte) 0 short Zero: (short) 0 imt Zero: 0 long Zero : OL, float oor double 0.00 char null character boolean false reference null Operators and Expressions Java supports rich set of operators. we have already used several of them such as and *. an ‘operator is a symbol that tells a computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables, Java operators can be classified into Arithmetic operators Relational Operators Logical Operators Assignment Operators Increment and Decrement operators Conditional Operators Bivwise operators Special operators. ex AWeENS Arithmetic operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. Java provides all the basic arithmetic [Link] following table lists the arithmetic operators: Operator Subtraction (also unary minus) Multiplication Division Modulus Increment Addition assignment Subtraction assignment Multiplication assignment Division Modulus a Decrement Arithmetic operators are used as shown below ath ab a*b wb a%b -a¥b here «and b may be variables or constants and are known as operands Integer Arithmetic When both the operands in a single arithmetic expression such as a+b are integers. The expression is called integer expression. And the operation is called integer arithmetic, Integer arithmetic sun integer [Link] a=14 and b=4 we have the following results: ‘/b=3 (decimal part truncated) a¥b=2(remainder of integer division) Real arithmetic ‘An arithmetic operation involving only real operands is called real arithmetic. A real operant may assume values either in decimal or exponential notation, Floating point arithmetic class FloatPoint ( public statie void main(String args[]) ( float a = 20.58, h=6.4f; [Link](“a=" +a); ‘[Link](“b= +b); [Link](“atb=" #(atb)); [Link] printin(“a-b=" + (a-b)): [Link] printIn(“a*b=" +(a*b)); System [Link](“a/b=" +(a/b)); [Link] printin(“a%b=" +(a%b)); 1 1 The output is given below 220.5 Mixed-mode Arithmetic When one of the operand is real and the other is integer, the expression is called mixed-mode arithmetic expression. If cither operand is of the real type, then the other operand is converted into real and the real withmetic is performed, The result will be a real, 15/10.0 produces the result 1.5 15/10 produces the result 1 Relational operators The relational operators determine the rel The relational operators are shown hei \ionship that one operand has to the other. Operator Result = Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to > < > < “The general form is: ae-1 relational operator ae-2 Implementation of relational operators class RelationalOperators t public static void main(steing args{1) { float a=15.0f, b=20.75f, c=15.0f; ‘[Link](“a=" +a); [Link]("l [Link] printin("e—" + [Link] printin(“ab is" +(0>b) [Link](“a—e is” +(a: [Link](“ac=e is" + (n<=e)); [Link](“a>=b is” Ha [Link](b!=c" +(b!=c)); [Link](“b==a+e is” +(b—=ate)); The output of the program azi5 b=20.75 cls ab is tue asb is false azsc is truc rue is false true besade is false Logical Operators Java has three logical operators. The logical operators && and [J are used when we want to form compound condition by combining two or more relations. Am example is: a>b && x==10 An expression of this kind which combines two or more relational expressions is termed as logical expression or a compound relational expression, A logical expression also yields a value of true or false according to the truth table. Logical operators Operator Meaning, Be i t Truth table Op-T Op2 Op Op- Top 1&é&op-2_|2 Tue The | Tue ue) Thue False | False tue) False True | False tue False False | False false ‘The Assignment Operator Assignment operators are used to assign the value of an expression to a variable. wehave seen the usual assignment operator” =”. Java has a set of shorthand assignment operators which are used in the form Vop = exp Where v is a variable, exp is an expression and op is a java binary operator. The operator op=is known as the shorthand assignment operator. ‘The assignment statement vop=exp: is equivalent to v=v op (exp); with v accessed only once. Example: x+=y+l; This is same as the statement xext (v4); Increment and decrement operator Java has two very useful operators not generally found in many other languages. These are the increment and decrement operators: and = ‘The operator ++ adds | to the operand while — subtracts 1. Both are unary operators and are used in the following form: Hm; or mH; om; oF m +t; is equivalent to m=m+l; (or m+=1) in; is eqiuivalent to m = mel; (or m-=1) We use the increment and decrement operators extensively in for and while loops. While ++m and m++ mean the same thing when they form statement independently, they behave itferently when they are used in expressions on the right-hand side of an assignment statement. Consider the following m=5; yeeem in this case, the value of y and m would be 6. Suppose , if we rewrite the above statement as thon, the valuc of y would be 5 and m would be 6, A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left, On the other hand, a postfix operator first assigns the value o the variable on left and then increment the operand. Increment operator illustrated lass inctementoperator 1 public { int m=10, n=20; [Link]¢*m=" +m); ‘[Link](“n” +n); [Link](“+tm: ‘System. [Link](*n+=" [Link](*m atic void main(String args|]) ‘System. [Link](*m=" +m); } } Output will be conditional operator ‘The character pair 9: is a ternary operator available in java. This operator is used to construct conditional expression of the form ‘exp Zexp2 : exp3 Where expl,exp2 and exp3 are expressions. exp! is evaluated first. IF it is nonzero(true) , then the expression exp? is evaluated and becomes the value of conditional expression. Note that only one of the expressions are evaluated first. in this example, x will be assigned the value of b. this can be achieved using the tement as follows: Bitwies operators This operators arc used for testing the may not be upplied to Sloat or double. or shifting them to the right or left. This operator Operator Result & Bitwise AND | Bitwise OR ‘ Bitwise exclusive OR, > Shift right a> Shift right zero fll << Shift left Special Operators Java supports some special operators of interest such as instanceof operator and member selection operator.) Instanceof operator ‘The instanceof is an object reference and returns true if the object on the lelt-hand side is an instance of the class given on the right-hand side, This operator allows us to determine whether the object belongs to a particular class oF not. Exampl person instanceof student is truc if the object person belongs to the class student; otherwise itis false. Dot operator ‘The dot operator.) is used to acess the instance variable and methods of class objects. Example: person aige//reference to the variable age personl salary(//reference to the method salary() Arithematic expressions ‘An arithematic expression is a combination of variables, constants, and operators arranged as per the syntax of the language. Expressions Algebric expression java expression abel abel (m+n)(xty) (m4n)* ty) a*b/e 3*x*xt2* x41 Evaluation of expressions Expressions are evaluated using an assignment statement of the form sariablesexpression Variable is any valid java name. when the statement is encountered, the expression is evaluated first and the result then replaces the variable on the left-hand side. All the variable used in the expression must be assigned values before evaluation is attempted. Examples of evaluation statements are xzatbec yableta: zeaWierd: Precedence and arithmetic operators An arithmetic expression without any parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in java: High priority 7% Low priority + ‘The basic evaluation procedure includes two left-to-right passes through the expression. During the first pass, the high priority operators(if any) are applied as they are encountered. During the second pass, the low priority operator(if any) are applied as they are encountered. Consider the following evaluation statement: xea-b/34c72-1 when a=9, 2. and c=3, the statement becomes x=9-12/343"2-1 and is evaluated as follows: second pass step3: x= 546-1 step4: x= 11-1 step5: x=10 the order of evaluation ean be changed by introducing parenth first pass: step]: 9-12/6*(2-1) step2: 9-12/6*1 second pass step3: 9-2*1 step4: third pass step: 7 the procedure consists of three left to right passes. However, the number of evaluation steps remain the same as 5, Parenthesis may be nested, and in such cases, evaluation of expression will proceed outward from the innermost set of parenthesis, Make sure that every opening parentheses has a matching closing one. For example 9-(123#3)*2)-1=4 Whereas 9-((12/3}+3*2)-1= -2 into an expression ‘Type conversion in Expressions Automatic Type Conversion Java permits mixing of constants and variables of different types in an expression, but during evaluation it adheres to very strict rules of type conversion. We know that the computer, considers one operator at a involving, two operands are of different type, the “lower” type is automatically converted to the ‘higher’ type before the operation proceeds. The results is of the higher type. If byte short and int variables are used in an expression, the results is always promoted to int, to avoid overflow. Ifa single long is used in the expression, the whole expression is promoted to long. Remember that all integer values are considered to be int unless they have the 1 or L appended to them. Ifan expression contains a float operand, the entire expression is promoted to float. If any operand is double, result is double. Automatic Type conversion char byte short int long float double ‘char int int int int long ‘double | double byte [int int int int Tong double | double short [ine int int int Tong double | double int Line int Int int long. double | double long long long long Jon; Jong, double double Tloat float float float float float double | double double double: double double double double double double ‘The final result of an expression is converted to the type of the variable on the left of the assignment sign before assigning the value to it. However, the following changes are introduced during the final assignment. 1. Float (o int causes truncation of the fractional part. 2. Double to float causes rounding of digits. 3. Long to int causes dropping of the excess higher order bits. Casting a value ‘Tava performs type conversion automatically. However, there are instances when we want to force a type conversion in a way that is different from the automatic conversion, Consider, for example, the calculation of ratio of female to males in a town. ratio =female _number / male_ number Since female _ number and male _ number are declared as integers in the program, the decimal part of the result of the division would be lust ratio would not represent a correct figure. This problem eu be solved by converting locally one of the variables to the floating points as shown below; float) female number / male_ number The operator (float) converts the female _ number to floating points for the purpose of evaluation of the expression, Then using the rule of automatic conversion, the divi point mode, thus retaining the ferctional part of result. Note that (float) convests the female _ number to floating point for the purpose of evaluat expression, Then using the sule of automatic conversion, the di mode, thus retaining the fractional part of result Note that in no way dose the operator (float) alfect the value of the variable female _ number. And also, the type of female _ number semains as int in theother parts program. “The process of such a local conversion is known as casting value, The general form of a cast is; ion is performed in foalting (Type _ number) expression Where type- name is one of the standard data types. The expression may be a constant, variable or an expression. Examples: (int) 7.5 7.5. is converted to integer by truncation. (int) (a+b) the result of a+b is converted to integer. (int) a+b ‘ais canverted to integer and then added to b, Casting can be used to round — off.a given value to an integer . consider the follo x= (int) (y +05); Ify is 27.6, y + 0.5 is 28.1 and casting, the results becomes 28, the value that is assigned to x. OF course, the expression being is not changed. ‘When combining two different types of variubles in an expression, never assume the rules of automatic conversion. It is always a good practice to explicitly force the conversion. It is more safer. For example, when y and p are double and m is int, the following (wo statements are equivalent, p+ my p+ (double) 1g statement; Operator precedence and associativity ‘This precedence is used to determine hoe an expression involving more than one operator is evaluated. There are distinct level of precedence and an operator may belong to one of the [Link] operators at the higher level of precedence are evaluated first. The operators of the same precedence are evaluated cither from left to right or from right to lelt, depending on the level. This is Known as the asst 'y property of an operator. Mathematical Functions Mathematical functions such as cos, sqrt, log, ete. are frequently used in analysis of real-life problems. Java supports these basie math functions through math class defined in the [Link], package. These functions should be used as Math.funetion_name( Example: Double y=[Link](x); Math functions: sin(x) Retums the sine of angle x in radians cos(x) Returns the cosine of angle x in radians tan(x) Returns the tangent of angle x in radians asin(y) Returns the angle whose sine is y acosty) Returns the angle whose cosine is y atan(y) Returns the angle whose tangent is y Decision Making and Branching: decision making statements in Java: Decision making structures have one or more conditions to be evaluated or tested by the program, along with astatement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Branching: When a Program breaks the sequential flow and jumps to another part of the code ,it is called [Link] are Two types of Branching . [Link] Branching When a program breaks the sequential flow and jumps to another part of the code,it is called conditional Branching. [Link] Branching If Branching takes place without any decision,it is known as unconditional Branching. There are the 5 ways of exercising decision making in Java: Lif 2. if-else 3. nested-if 4, else-if-Ladder 5. switch-case 1. If Statement in Java Java if statement is the simplest decision making statement. It encompasses a boolean condition followed by a scope of code which is executed only when the condition evaluates to true. However if there are no curly braces to limit the scope of sentences to be executed if the condition evaluates to true, then only the first line is executed. Syntax: if(condition) { /Icode to be executed } Flow diagram for if statement False Code to be executed if condition is true _ code outside if block 2. if else statement in Java This pair of keywords is used to divide a program to be executed into two parts, one being the code to be executed if the condition evaluates to true and the other one to be executed if the value is false. However if no curly braces are given the first statement after the if or else keyword is executed. if(condition) /eode to be executed if the condition is true } else { /code to be executed if the condition is false } Flow diagram of if-else statement True ‘statements outside if ‘ else block 3. Nested if Statements in Java © The nested if is similar to the nested loops we learnt about in the previous chapters. If the condition of the outer if statement evaluates to true then the inner if statement is evaluated. e Nested if’s are important if we have to declare extended conditions to a previous condition Syntax: if(condition) { Heode to be executed if(condition) { Mcode to be executed ) } Flow diagram of Java nested if statement: Flow diagram a nested if statement ~Innerelse block "Statement outside nested if block 4, else-if Ladder Statements in Java These statements are similar to the if else statements , The only difference lies in the fact that each of the else statements can be paired with a different if condition statement. This renders the ladder as a multiple choice option for the user. As soon as one of the if conditions evaluates to true the equivalent code is executed and the rest of the ladder is ignored. Syntax: if ( “code to be executed } else if(condition) ( /icade to be executed } else if(condition) ( Hcode to be executed } else ( Heode to be executed } Flow Diagram of Java else if Ladder statements: Flow Diagram of if else if statements False True If block Statement outside __ifelse if block Java switch statement is a different form of the if else if ladder statements. False 5. Switch Statement in Java + It branches the flow of the program to multiple points as and when required or specified by the conditions. + It bases the flow of the program based on the output of the expression. As soon as the expression is evaluated, the result is matched with each and every case listed in the scope. If the output matches with any of the cases mentioned, then the particular block is executed. + Abreak statement is written after every end of the case block so that the remaining statements are not executed. + The default case is written which is executed if none of the cases are the result of the expression. This is generally the block where error statements are written, Syntax: switch(expression) case : ficode to be executed break; case : ‘code to be executed break; default: “code to be defaultly executed } Flow Diagram of Java switch statement: Flow Diagram of the switch statement Switch Expression o True | _End of switch case The Conditional Operator(?: Operator) Java Conditional Operator or ternary operator minimizes and mimics the if else statement. It consists of a condition followed by a question mark(?). It contains two expressions separated by a colon(:). If the condition evaluates to true, then the first expression is executed, else the second expression is executed. Syntax : (Condition)?(expression 1):(expression 2); For example, the segment Tf(x<0) Flag=0; else Flag=1; Can be written as flag=(x<0)?0:1; Decision making and Looping In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then rather than typing the same code 100 times, you can use a loop. In Java, there are three types of loops. + for loop + while loop + do...while loop for Loop Java for loop is used to run a block of code for a certain number of times. The syntax of for loop i: for (initialExpression; testExpression; updateExpression) // body of the loop Here, 1. The initialExpression initializes and/or declares variables and executes only once. 2. The condition is evaluated. If the condition is true, the body of the for loop is executed. 3. The updateExpression updates the value of initialExpression. 4, The condition is evaluated again. The process continues until the condition is false. {nitialization| Expression a= Condition y for'Loop Body Update Expression Loop Terminates Example 1: Display a Text Five Times // Program to print a text 5 times class Main [{ public static void main(String[] args) { intn=5; // for loop for (inti = 1; i <=n; ++i) { [Link]("Java is fun"); } } } Output Java is fun Java is fun Java is fun Java is fun Java is fun While Loop Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is: while (testExpression) { // bady of loop } Here, 1. A while loop evaluates the textExpression inside the parenthesis (). 2. If the textExpression evaluates to true, the code inside the while loop is executed, 3. The textExpression is evaluated again. 4. This process continues until the textExpression is false. 5. When the textExpression evaluates to false, the loop stops. Flowchart of while loop true Roath Loop Terminates Vv Example 1: Display Numbers from 1 to 5 // Program to display numbers from 1 to 5 class Main ( public static void main(String[] args) { // declare variables inti=1,n=5; / while loop from 1 to 5 whileG <= n) { X w we [Link](i); i++; } } } Output UbuUne Java do...while loop The do...while loop is similar to while loop. However, the body of do...while loop is executed once before the test expression is checked. For example, do{ // body of loop } while(textExpression) Here, . The body of the loop is executed at first. Then the textExpression is evaluated. If the textExpression evaluates to true, the body of the loop inside the do statement is executed again. . The textExpression is evaluated once again. If the textExpression evaluates to true, the body of the loop inside the do statement is executed again. . This process continues until the textExpression evaluates to false. Then the loop stops. Flowchart of do...while loop | Commies tt17 Test Condition Loop Terminates Example 3: Display Numbers from 1 to 5 // Java Program to display numbers from 1 to 5 // Program to find the sum of natural numbers from 1 to 100. class Main { public static void main(String[] args) ( inti=1,n=5; // do...while loop from 1 to 5 do { [Link](i); it; } while(i <= n); } } Output UabwUnNe a umps in Loop © The jumping stataments are the control statements which transfer the program ‘execution contra! to a specific statements. + jump: Java supports three jump statement: break, continue and retum. These three slatements transfer control to other part of the program, Break: In Java, break is majorly used for: Terminate a sequence ina switch statement. Java Break Statement We can use break statement in the following cases. Inside the switch case to come aut of the switch black. Within the loops to break the loop execution based on some condition. Inside labelled blocks to break that block execution based on some condition, The break cannat be used outside the loops and switch statement Java Continue Jumping Statement * This statement is used only within looping statements. When the continue statement is encountered, then it skip the current iteration and the next iteration starts. ‘* The remaining statements in the loop are skipped. The execution starts from the top of loop again. » We can use continue statement to skip current iteration and continue the next iteration inside loops. Labeled Loops We can give a label to a block of statements.A label is any valid java variable [Link] give a label to a loop, place it before the loop with a colon at the end. For ex. Outersfor(int m=1;me<11;m+4) { Forint n=1;n<14;n++) { [Link](""+m*n ); It (n==m) Continue outer; } }

You might also like