7 : java basics introduction - computer education in schoolverymicro.org › wp-content › uploads...

12
12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org ) 1 7 : JAVA BASICS Introduction Java is object oriented programming language developed by Sun Microsystems in 1991. A company best known for its high-end UNIX workstations. Modelled after C++ Java language is designed to be small, simple and portable across platforms and operating Systems, (Means run on any OS like Windows, Linux, Mac etc or easily, fast, efficient and support wide range of hardware devices) both at the source and at the binary level. So it is called platform independent (Moves easily one PC to another PC(Computer). Most of Java syntaxes are very similar to C language. Capabilities of creating flexible, modular, reusable code. It includes a set of class libraries that provide basic data types, system input, output capabilities and other utilities functions. These basic classes are part of the JAVA DEVELOPMENT KIT (JDK). JDK has classes to support networking, common Interpreter protocols and user interface toolkit functions. At binary level, platform independent is possible due to bytecode interpreter. Programs written in Java are compiled into machine language that doesn’t really exist in computer. This so-called “Virtual” computer is known as the Java Virtual Machine (JVM). This is called Java bytecode (Java binary file). The only disadvantage of using bytecode is its slow execution speed. Some tools convert Java bytecode into native code. Native code is faster to execute, but then it does not remain machine independent. A java program is composed of classes. It should have at least one class and it must have main method in it. Example of Java Program (How to write Code) /** * Program that will compute the cost of phone call and update balance */ public class CallCost { public static void main(String[ ] args) { /*declare variables */ double blance; // balance amount in rupees double rate; double duration; double cost; /* computations. */ balance=170; rate=1.02; duration=37; cost=duration * rate; balance=balance cost; /* display results */ System.out.print(“Call Duration: “); System.out.print(duration); System.out.println(“ Seconds”); System.out.println(“Balnce: “ + balance + “ Rupees”); } } Output :: Call Duration 37 Seconds Balance 168.58 Rupees

Upload: others

Post on 25-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 1

7 : JAVA BASICS Introduction Java is object oriented programming language developed by Sun Microsystems in 1991. A company best known for

its high-end UNIX workstations. Modelled after C++

Java language is designed to be small, simple and portable across platforms and operating Systems, (Means run on any OS like Windows, Linux, Mac etc or easily, fast, efficient and support wide range of hardware devices) both at the source and at the binary level. So it is called platform independent(Moves easily one PC to another PC(Computer).

Most of Java syntaxes are very similar to C language.

Capabilities of creating flexible, modular, reusable code. It includes a set of class libraries that provide basic data types, system input, output capabilities and other utilities functions.

These basic classes are part of the JAVA DEVELOPMENT KIT (JDK). JDK has classes to support networking, common Interpreter protocols and user interface toolkit functions. At binary level, platform independent is possible due to bytecode interpreter.

Programs written in Java are compiled into machine language that doesn’t really exist in computer. This so-called “Virtual” computer is known as the Java Virtual Machine (JVM). This is called Java bytecode (Java binary file).

The only disadvantage of using bytecode is its slow execution speed. Some tools convert Java bytecode into native code. Native code is faster to execute, but then it does not remain machine independent.

A java program is composed of classes. It should have at least one class and it must have main method in it.

Example of Java Program (How to write Code)

/** * Program that will compute the cost of phone call and update balance */ public class CallCost { public static void main(String[ ] args) { /*declare variables */

double blance; // balance amount in rupees double rate; double duration; double cost;

/* computations. */ balance=170; rate=1.02; duration=37; cost=duration * rate; balance=balance – cost;

/* display results */ System.out.print(“Call Duration: “); System.out.print(duration); System.out.println(“ Seconds”); System.out.println(“Balnce: “ + balance + “ Rupees”); } }

Output ::

Call Duration 37 Seconds

Balance 168.58 Rupees

Page 2: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 2

Comments Comments in a program are for human readers only. Comments are entirely ignored by the computer. Comments are important to make the program easy to understand for everybody. Comments are not compiled or interpreted. Comment cannot be nested means we cannot have a comment inside a comment.

A. Single line comment it begins with // (double slash) and extends till the end of a line. B. Multi line comment it begins /* and end with */. This is use to have more than one line as comments. C. Documentation commentIt begins with /** and end with */. They are used for creating API documentation

from the code. API=Application Program Interface. These are special comments that are used for javadoc system.

The body of the program is contained in a routine called main(). In java, main() is the first routine that is run when the program is executed. Computation part contains expressions. Here, several subroutine(also called function or method in java) call statements are used to display information to the user of the program.

Method used to display results System.out.print and System.out.println. Both take a value to be displayed.

Method System.out.print adds a linefeed.(Means we can display other message after it in a one line)

System.out.println does not add a linefeed.

When we run program, the Java interpreter calls the main() method and the statements. The main() routine can call other subroutines that are defined in the same class or even in other classes, but main() routine determines how and in what order the other subroutines are used.

The word “public” in the first line of main() means that this routine can be called from outside the program.

Using SciTE editor For new file : File New, For save a file : File Save, For compile source program: Tools Compile For execute : Tools Go

Structure of a Java Program The rules that determine what is allowed are called the syntax of the language. Syntax rules specify the basic vocabulary of the language. Program can be constructed using things like variables, expressions, statements, branches, loops and methods. The definition of the method(function) consists of function header and the sequence of statements enclosed between curly braces { and }. Variable and method declaration after and before main() method is optional. Each program must have one class that contains public method main(). Java is free-format language. Computer doesn’t care about the program layout. We can write the entire program together on single line. Layout is important to human readers.

Java Primitive Data Types Data type is nothing but the type of the data. Each variable in Java must have certain type associated with it which tells us what kind of data a variable can store. Data type determines the require memory size, type of value, range of value and type of operations. Data type classified into two main groups Primitive and Reference Data Types. Data types are predefined by the Java Language. Predefined data types are Reserved Keyword so we cannot use them as variable name inside program or Application. Primitive value do not share state with other primitive values. They are built into the system. These are machine-independent (means their sizes and characteristics to be consistent across all java programs on all machines.) Total number of primitive data types in Java are 8. All Primitive Data types have respective Wrapper Classes i.e Integer is wrapper class for primitive type int.

Page 3: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 3

Integer Data Types (byte, short, int, long)(signed) Integer Data type is used to store integer value. It is able to store both unsigned and signed integer value. Integer numbers with b bits precision store signed values in the range of (-2b-1-1, 2b-1). Real numbers in Java are compliant with IEEE754(International standard for defining floating-point numbers and arithmetics). signed value -32768 to 32767 Unsigned Value – 0 to 65535 short Data types has 16 bits size. 232 = 65536 Character Data Types( Char)(unsigned) The data type used to store character is char. Java uses Unicode to represent characters. There are no negative character. example: char ch=’M’; Increment Character Value : char ch1, ch2; char ch1=’P’; ch1 = 88; //code for X System.out.println(“ch1 contains” +ch1); ch1 = ‘Y’; ch1++; System.out.println(“ch1 is now” +ch1); Float Data Types (float, double) Floating Data type is used to store float value. Example: float num=10.5f; (it occupy 4 bytes in memory) double num=10.5; (it occupy 8 bytes in memory) Not require to write d. It is default value. Boolean Data Types (boolean) Boolean data type is used for logical values. It have two possible values true or false. It is required by the conditional expressions used in control statement such as if and for. Example: boolean b=true; if (b) { System.out.println(“I am true”); } Default Value Programm public class DefaultValue {

static boolean bool; static byte by; static char ch; static

double d; static float f; static int i;

static long l; static short sh; static String str;

public static void main(String[] args) {

System.out.println("Bool :" + bool);

System.out.println("Byte :" + by);

System.out.println("Character:" + ch);

System.out.println("Double :" + d);

System.out.println("Float :" + f);

System.out.println("Integer :" + i);

System.out.println("Long :" + l);

System.out.println("Short :" + sh);

System.out.println("String :" + str);

}

}

OUTPUT

Bool :false

Byte :0

Character:

Double :0.0

Float :0.0

Integer :0

Long :0

Short :0

String :null

Variables in Java Programming Variable means Character or value. A name used to refer to the data stored in memory is called a variable. We can say that variable is something which can store a value. Data can only referred to by giving the numerical address. A variable can take different data values at different times during the execution of the program, but it always refers to the same memory location. Variable name may be given by programmer. When the list contains more than one item(variables), items should be separated by commas. Example : double amount, interest, total;

Some Rules of Variable Naming Convention: 1. Case-sensitive. (Name and name both variable are different) 2. can be any legal identifier. It can be any length.

√ (Right) birth_date, result, CallCost, top5students, amount$, $price, _amount X (Wrong) 4me, %discount, birth date, @main

3. letter, Digits and Two special Characters ( Must begin with an alphabet, _ and $) 4. Length of variable name can be any number. 5. Start With Alphabet (However we can use underscore, but do not use it) 6. Spaces is not permitted. 7. Special Character are not allowed.

Page 4: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 4

8. Digit at start is not allowed. 9. Sequence : letters, digits, $ or Underscore ( _ ) 10. Variable name must not be a Keyword or reserved word. (like class, public, static, if, else, while....)

Examples : total_num, TotaNum, total, TOTAL, no1, no2 There are three types of variables: 1. Instance variables 2. class variables 3. local variables.

1. Instance variables are declared in a class, but outside a method, constructor or any block. 2. Class variables are declared with static keyword in a class, but outside a method, constructor or block. It is also

known as static variables. 3. Local variables are declared in methods, constructors or blocks. We are learning now local variables. (Destroyed

when method gets executed completely.)

Java Literals (Constant value) Theoretically Literals means – Any number, Text or Other information that represents a VALUE.

Literal Type Statement Explain Decimal int num = 20; Decimal 20 is assigned to the variable num. Octal int num = 020; “020” is octal number. So first octal no is converted into integer and then

it is assigned to variable “num” Hexadecimal int num = 0x20 or 0xFF7A; 0x20 is hexadecimal number. Binary int num = 0b1010; 0b1010 is binary number. Long long num = 563L; 562L is long number, assigned to the variable “num”. Unicode literals consists of \u followed by four hexadecimal digits. Example : “\u00E9 Here 20, 020, 0x20, 0b1010, 563L etc are literals. Java integer literal and Underscore example : int num = 19_90; int num = 1990; When the literal is compiled, the underscores are discarded. It makes easier to read large integer literals. It will assign 1990 to variable “num” Examples : 45_89 4589, 045_23 Octal 04523, 0x56_23 Equivalent Hex : 0x5623 Don’t Use underscore as first and last character. It is use only in between two integers. Java Floating Point Literal (Real Number literals) Decimal Values with a fractional component is called floating point. Example 17.591 They can be expressed in either standard or scientific notation. Standard Notation : 5.6984598, 42.0, 112345.56 Scientific Notation: Floating point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number. Which can be positive or nagative. Examples: 6.02E21 6.02x1021 , 314159E-05 314159x10-05 Floating Point literals in Java default to double precision. Example: float x = 54.5f; (F or f can use) Not compulsory to represent with D or F double y = 29.5d; (D or d can use) Boolean literals There are two literals only : true and false. Type without quotes. Zero treated as false and non-zero treated as true. True and false are not associated with any numeric value. Character literals It is expressed by a single character with single quotes: ‘a’ , ‘A’, ‘#’ etc. It is stored as 16-bit Unicode character. Certain special literals that use a backslash(\) as an “escape character”. Table lists the special codes that can represent nonprintable characters, as well as characters from the Unicode character set

String literals A string is sequence of characters. Strings are enclosed with double quotes (“ “). Within a string special characters can be represented using the backslash(\). Example: Many, Congratulations! String str=”Many,\”Congratulations!\””; String str=”Hello”; String str=”Hel” + “lo”;

String start=”Hello”; String end=start.concat(“World!”); System.out.println(end); Output : Hello World!

This string brought to you by Java\u2122, the Unicode code sequence \u2122 produces a trademark (TM).

Escape Code

Meaning Escape Code

Meaning

\n New line \f Formfeed(New page)

\t Tab \\ Back slash Character

\b Backspace \’ Single quote Character

\r Carriage Return

\\” Double quote Char

\ddd Three octal

digit (d=0 to 7) \xdd

Two hexadecimal digits (d=0to9 and a to f)

\udddd Unicode number dddd (d= hexadecimal digit)

Page 5: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 5

Expression ( + , - , *, /, <, >, %, etc) Simple expression can be a literal, a variable, a function call. More complex expression can be built up by using operators to combine simple expressions. When several operators appear in an expression, there is a question of precedence. Example : x = 7 + 3 * 2 , x is assigned 13, not 20 because * has higher precedence than +.

Category Operator Associativity Category Operator Associativity

Postfix ( ), [ ], . Left to right Equality ==, != Left to right

Unary ++, -- , !, ~ Right to Left Bitwise &, ^, | Left to right

Multiplicative *, /, % Left to right Logical &&, || Left to right

Additive +, - Left to right Conditional ?, : Right to Left

Relational <, >, >=, <= Left to right Assignment =, +=, -=,*=,/=,%= Right to Left

Operators (Operators are special symbols used to build an expression) 1. Arithmetic operators 2. Unary Operators 3. Comparison (Relational) 4. Logical operators 5. Conditional operators 6. Assignment Operators.

1. Arithmetic Operators (+(Addition), - (Substraction), *(Multiplication), /(Division), %(Modulus-Gives remainder)

Arithmetic operators are used in mathematical expressions. It can be applied on any type of numeric data type.

Assume integer variable a = 10 and Variable b=22 a+b=32, a-b=-12, a*b=220, b/a=2 or 2.2, b%a=2, a++=11, a--=9 (Here a, b are operands and +,-,/,*,% are operators)

When both operands are of same data type result in same as the type of operands Example : int a=9; int b=2; then a/b = 4 not 4.5 (if float a=9; float b=2 then a/b=4.5)

When both operands are of different data types. (Example: float a=9; int b=2 then a/b=4.5)

Lower range data type is implicitly converted to higher data type to have the same types of operands. This type of conversation is also known as promotion (9f/2 = 4.5).

With modulus operator %, if first operand is negative the result is negative.

Modulus % is also use with float. (Example: 25.8%7 then quotient(int) is 3 and remainder(float) is 4.8)

Operator + can also used to concatenate a string. (Example: Hello + World = HelloWorld)

PRACTICAL

public class Test{ public static void main(String args[]){ int a =10; int b =20; int c =25; int d =25; System.out.println("a + b = "+(a + b)); System.out.println("a - b = "+(a - b)); System.out.println("a * b = "+(a * b)); System.out.println("b / a = "+(b / a)); System.out.println("b % a = "+(b % a)); System.out.println("c % a = "+(c % a)); System.out.println("a++ = "+(a++)); System.out.println("b-- = "+(a--)); System.out.println("d++ = "+(d++)); System.out.println("++d = "+(++d)); } }

OUTPUT a + b =30

a - b =-10

a * b =200

b / a =2

b % a =0

c % a =5

a++=10 b--=11

d++=25 ++d =27

2. Unary Operators : ++(increment), -- (decrement) it is also called increment and decrement operators

++ adds 1 to a variable and – subtract 1 from the variable.

POSTFIX :When ++ or -- is used after variable name, it is known as post-increment or post decrement.(x++ or x--) Example: if x = 5, when we print x++ , the old of x will be print(means 5). Thereafter the value of variable is incremented and then x value becomes 6)

PREFIX: When ++ or -- is used before variable name, it is known as pre-increment or pre-decrement. (++x or –x) Example: if x =5, when we print ++x the new value of x will be print (means 6).

When used in a standalone statement, does not make any difference.( statement x++, and ++x; are standalone)

3. Comparison Operators : ==, !=, <, >, <=, >= it is also known as relational operators

These operators can be used to compare value of numeric types or char type. (Unicode values are use for char type).

The result of expression is boolean true or false. So such expressions are also called boolean-valued expression. Example : Assume that a=12 and b= 20

Exp Description Result Exp Description Result

a==b Is a “equal to” b? false a>b Is a “greater than” b? false

a!=b Is a “not equal to” b? true a<=b Is a “less than or equal to” b? true

a<b Is a “less than” b? true a>=b Is a “greater than or equal to” b? false operator == and != also be used to compare boolean values. Usually relational operators are used in if statement and loops.

PRACTICAL

public class Test{ public static void main(String args[]){ int a =10; int b =20; System.out.println("a == b = "+(a == b)); System.out.println("a != b = "+(a != b)); System.out.println("a > b = "+(a > b)); System.out.println("a < b = "+(a < b)); System.out.println("b >= a = "+(b >= a)); System.out.println("b <= a = "+(b <= a)); }

OUTPUT a == b =false a != b =true a > b =false a < b =true b >= a =true b <= a =false

Page 6: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 6

}

4. Logical Operators : &&(AND), ||(OR), ^(XOR), ! (NOT) it is also called boolean operators

These operators can be used to compare value of numeric types or char type. (Unicode values are use for char type).

These operators are used to compare boolean values of variables. Assume that x=true; and y=false

Operator Description Example Result

&& (AND)

If x and y both are true(not same) than result will be true. true && true = true

(x &&y) false

|| (OR) if both (x,y) are true than result false. Means both are not be same. If same result false. If any of two operands are non-zero the true true || true = true

(x||y) true

^ (XOR) It is exclusive OR. It returns true only if its operands are different(one true and one false) true ^ true = false

(x^y) true

! (NOT) NOT is denoted by ! and it is unary operator. If operand is true, result is false and vice versa(Reverse). !(true && true) = false

!(x&&y) true

Short circuiting : When using the conditional AND and OR operators (&& and ||), Java does not evaluate the second operand. Here evaluation has been short circuited. EXAMPLE : If first operand is false or true, there is no need to evaluate second operand. (1 != 1) && (2 = =2) : Here 2==2 never get evaluated. Only 1!=1 is evaluated (Does not evaluated second operands). (1 == 1) && (2 ! =2) : Here 2!=2 never get evaluated. Only 1==1 is evaluated (Does not evaluated right side operands).

PRACTICAL

public class Test{ public static void main(String args[]){ boolean a =true; boolean b =false; System.out.println("a && b = "+(a&&b)); System.out.println("a || b = "+(a||b)); System.out.println("!(a && b) = "+!(a && b)); } }:

OUTPUT a && b =false

a || b =true

!(a && b)=true

5. Conditional Operator : ?: it is also known as ternary operator.

This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable.

Syntax <boolean-expr> ? <expr1> : <expr2>

PRACTICAL

public class Test{

public static void main(String args[]){

int a , b; a =10; b =(a ==1)?20:30; System.out.println("Value of b is : "+ b ); b =(a ==10)?20:30; System.out.println("Value of b is : "+ b ); } }:

OUTPUT

Value of b is:30

Value of b is:20

Here a==1 So a is odd so it will assign 30 in variable b. Here a==10 So a is even so it will assign 20 in variable b.

6. Assignment Operators : =, +=, -=, *=, /=, %= etc.. it is also known as ternary operator.

An expression containing assignment(=) operator is generally referred to as assignment statement. Syntax: variable = expression; (Where expression represents anything that refers to or computes a data value. When execution, it first evaluates the right side of = sign and then put resulting data value into the variable. Example: balance = balance – cost ( it first evaluate right side of = balance – cost, then result store in left side = (balance) If the data type of expression is larger than the variable on left hand side, it may result in an error due to precision problem. Example : there may not be automatic conversion from int to short or double to float. Shorthand Assignment operators : It is a shorthand version of assignment. It saves typing time. Syntax : variable <operator>= expression ( a +=b means a=a+b)

PRACTICAL

public class Test{ public static void main(String args[]){ int a =10; int b =20; int c =0; c = a + b; System.out.println("c = a + b = "+ c ); c += a ;

OUTPUT

c=a+b = 30

c+=a = 40

c-=a = 30

c*=a = 300

Page 7: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 7

System.out.println("c += a = "+ c ); c -= a ; System.out.println("c -= a = "+ c ); c *= a ; System.out.println("c *= a = "+ c ); c /= a ; System.out.println("c /= a = "+ c ); c%= a ; System.out.println("c /= a = "+ c ); } }

c/=a = 30

c%=a = 0

Type cast In some cases, we may want to force a conversion that wouldn’t be done automatically. A type cast is indicated by putting a type name in parentheses before the value we want to convert. Example: int a; short b; a=17; b=(short)a; (Here variable a is explicitly converted using type cast to a value of type short. Precedence Order : When two operators are having different priority, the an operator with the higher precedence is operated first. Example: a + b * c (Here * is having higher precedence than +, b*c evaluated first and then result is added to a) Associativity: When two operators with the same precedence appear in the expression, the expression is evaluated according to its associativity. Associativity determines the direction. (Left to right or right to left)

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift >>>>><< Left to right

Relational >>= <<= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= etc Right to left

Comma , Left to right

Example: 72/2/3 (/ have left right associativity) So (72/2) and then /3 Control Structures

if statement, switch statement, while loop, do...while loop and for loop Generally, statements are executed one by one. Sometime, program logic needs to change the flow of sequence. The statements that enable to control the flow of execution are called as control structures. Two type of control structure : 1. loops : Loops are used to repeat a sequence until some condition occurs. 2. branches : Branches are used to choose among two or more possibility action. So it is also called selective structure. Each of these structures(Statement) is considered to be a single statement, may be a block statement. So now we will learn about block first, then structure.

Block A block statement is a group of statements enclosed between a pair of curly braces { } Purpose of block :

To group a sequence of statements into a unit that is to be treated as a single statement.

To group logically related statements.

To create variables with local scope for statements within a block When we declare variables inside a block is completely inaccessible and invisible from outside that block. When variable executed, memory is allocated to hold the value of the variable. When block ends, that memory is released and is made available for reuse. We can declare variables within any block. Block begun with opening curly brace { and ended by a closing curly brace }. 1 block equal to 1 new scope in Java thus each time you start a new bock, you are creating a new scope. Any attempt to access it outside block will cause compiler time error. Nested block can have access to its outermost bock. If you declared variables inside main block thus all the variables declared inside main block are accessible.

Page 8: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 8

if (boolean-expression) { statement(s) True False } else } statement(s) }

PRACTICAL

// Demonstrate block scope.

class Scope {

public static void main(String args[])

{

int n1; // Visible in main

n1 = 10;

if(n1 == 10)

{ // start new scope

int n2 = 20; // visible only to this block

// num1 and num2 both visible here.

System.out.println("n1 and n2 : "+ n1 +""+ n2);

}

// n2 = 100; // Error! n2 not known here

// n1 is still visible here.

System.out.println("n1 is " + n1);

}

}

OUTPUT

n1 and n2 : 10 20

n1 is 10

Statements in JAVA If Statement The if statement is a conditional branch statement. It is an example of a “branching” or “decision” or “selective” control structure. It tells your program to execute a certain section of code only if a particular test evaluates to true. If boolean expression evaluates to true, the statements in the block are executed. if false, the statement in the if block are not executed. If boolean Expression evaluates to false, there is an else block, the else block are executed.

PRACTICAL (if-else statement) class IfDemo {

public static void main(String[] args) {

int marks = 76;

String grade;

if (marks >= 40) {

grade = "Pass";

}

else

{

grade = "Fail";

}

System.out.println("Grade = " + grade);

}

}

Output

Grade = Pass

If we have multiple conditions then we can use if-else ladder. Syntax:

if (booleanExpression1)

{

statement(s)

}

else if (booleanExpression2)

{

statement(s)

}

else if (booleanExpression3)

{

statement(s)

}

.........

else {

statement(n)

}

boolean-expr

statement1 statement2

Page 9: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 9

PRACTICAL (if-else if- else statement) class IfElseDemo {

public static void main(String[] args) {

int marks = 76;

char grade;

if (marks >= 90) {

grade = 'A';

} else if (marks >= 80) {

grade = 'B';

} else if (marks >= 70) {

grade = 'C';

} else if (marks >= 60) {

grade = 'D';

} else {

grade = 'F';

}

System.out.println("Grade = " + grade);

}

}

Output

Grade = C

Keyword else and a block after else are optional. So, if statement can be written without else part. When an if statement is used in another if statement, it is called nested-if statement.

Switch Case Statement It is alternative to else-if ladder. A switch statement is used when there

are many alternative actions to be taken.

The result of the test expression must be of the type taking discrete (independent) values.

Switch allows you to choose a block of statements to run

from a selection of code.

The expression used in the switch statement must return an int, a String or an enumerated value. Means it should be of the type byte, char, short or int.

When executing switch statement, the value of the test expression is compared with each of the case value in turn from case1 onwards. If match found, the respective statement executed. If no match found, the default statement is executed. The default is optional. There is not necessary of block. Break statement used after each case is not mandatory.

PRACTICAL Switch-Case Using Integer Label: int i=3;

switch (i) {

case 1 :

System.out.println("One player is playing this game.");

break;

case 2 :

System.out.println("Two players are playing this game.");

break;

case 3 :

System.out.println("Three players are playing this game.");

break;

default:

System.out.println("You did not enter a valid value.");

}

Output

Three players are

playing this game

PRACTICAL Switch-Case Using String String name = "Pritesh";

switch (name) {

case "Pritesh" :

System.out.println("One player is playing this game.");

break;

case "Suraj" :

System.out.println("Two players are playing this game.");

Output

One player is

playing this

game.

Page 10: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 10

break;

case "Raj" :

System.out.println("Three players are playing this game.");

break;

default:

System.out.println("You did not enter a valid value.");

}

Repetitive control structures. (There are three type of looping constructs) For loop syntax: While loop syntax do.... while loop syntax

For loop Statement For loop is one of the looping statements.

For loop is used to execute set of statement repeatedly until the condition is true.

For loop checks the condition and executes the set of the statement. It is loop control statement in Java.

These loops are entry-controlled or pre-test loop constructs. It is possible that statements in a loop are not executed at all.

When number of iterations (repetition) are pre-determined, usually for loop is used.

For loop Contains = Initialization, Condition, iterator (Increment/Decrement) :(All three expressions are optional) Thus we can write for (;;) But require some control statements to break the loop. If break statement is not executed, it will result in infinite loop.

Syntax: for (initialization; condition; increment) {

Statement1

Statement2

.

.

StatementN

}

PRACTICAL

class ForDemo {

public static void main(String[] args){

for(int i=1; i<11; i++){

System.out.println("Count is : " + i);

}

}

}

Output Count is: 1

Count is: 2

Count is: 3

Count is: 4

Count is: 5

Count is: 6

Count is: 7

Count is: 8

Count is: 9

Count is: 10

While loop Statement “While” is iteration (travel) statements like for and do-while. It is also called as “Loop Control Statement”. “While Statement” repeatedly executes the same set of instructions until a termination condition is met. While loop is “Entry Controlled loop” because condition is check at the entrance. In for loop initialization, condition and increment all three statement are combined into one statement..... but in “While loop” all these statement are written as separate statements. Syntax : while(condition) { //body of loop } The condition is any boolean expression. The body of the loop will be executed as long as the conditional expression is true. The curly braces are unnecessary if only a single statement is being repeated. Example1

Page 11: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 11

PRACTICAL (While loop boolean condition) For loop While loop While loop (no Curly braces)

class ForDemo {

public static void

main(String[] args){

for(int i=1; i<11;

i++){

System.out.println("Count is

: " + i);

}

}

}

class WhileDemo {

public static void

main(String[] args){

int cnt = 1;

while (cnt < 11) {

System.out.println("Number

Count : " + cnt);

count++;

}

}

}

class WhileDemo {

public static void

main(String[] args){

int cnt = 1;

while (cnt < 11)

System.out.println("Number

Count : " + cnt++);

}

}

do....While loop Statement “do-While” is iteration (travel) statements like for and while loop. It is also called “loop Control Statement”. Do-while Statement is Exit Controlled Loop or post test loop because condition is check at the last moment. Here, statements of loop are executed at least once. Conditional Expression written inside while must return boolean value.

PRACTICAL

Syntax :: do { Statement1; Statement2; Statement3; . . StatementN; } while (expression);

class DoWhile {

public static void main(String args[]) {

int n = 5;

do

{

System.out.println("Sample : " + n);

n--;

}while(n > 0);

}

OUTPUT Sample : 5

Sample : 4

Sample : 3

Sample : 2

Sample : 1

Sample : 0

Note: Semicolon at the end of while is mandatory otherwise you will get compile error.

Use of break and continue statement (Syntax : break; )

The break statement is used to transfer the control outside switch or loop structure.

When break is used in switch structure, it skips all the following statements and control is transferred at the first statement.

In a loop (for, while, do-while), break statement is used to exit the loop. When break executed all the following statements are skipped and no further iteration takes place.

Remember that break jumps outside the nearest loop containing this statement.

Use of continue statement is used to skip the following statements in a loop and continue with the next iteration. We can also say that continue statement is used to skip the part of loop.

Both, break and continue are used the same way as in C language.

Nested loop Loops can be same or different types can be nested in Java Program.

PRACTICAL Example of Nested loops

public class GeneratePrimeNumbersExample {

public static void main(String[] args) {

int limit = 100;

System.out.println("Prime numbers between 1 and " + limit);

for(int i=1; i < 100; i++){

boolean isPrime = true;

//check to see if the number is prime

for(int j=2; j < i ; j++){

Prime numbers between

1 and 100

1 2 3 5 7 11 13 17 19 23

29 31 37 41 43 47 53 59 61

67 71 73 79 83 89 97

Page 12: 7 : JAVA BASICS Introduction - Computer Education in Schoolverymicro.org › wp-content › uploads › 2016 › 12 › 12EM-L-7-Mat.pdf · any OS like Windows, Linux, Mac etc or

12EM Science/Commerce Lesson-7 Java Basics (www.verymicro.org) 12

if(i % j == 0){

isPrime = false;

break;

}

}

// print the number

if(isPrime)

System.out.print(i + " ");

}

}

}

The Java class libraries include a class called Math. The Math class defines a whole set of math operations. Function sqrt() is one of the static method member of the class Math and is invoked as Math.sqrt().

Labelled loops and labelled break When we use nested loops, break statement breaks the nearest enclosing loop and transfers the control outside the loop. Similarly continue also restart the enclosing loop. To control which loop to break and which loop to reiterate, we can use labelled loop. To use labeled loop, add the label followed by colon(:) before the loop. Then add the name of the label after the keyword break or continue to transfer control elsewhere other than enclosing loop.

PRACTICAL labelled loop

Class labelBlock { public static void main (String[]s) { int x=0; out: for (int i=4; i<10; i++) { x=10; while(x<100) { System.out.println(“Inside while loop i is “ + i + “, x is” + x); if (i * x == 350) break out; x =x+20; } //end of while System.out.println(“\nOutside while loop: i is” + i + “ , is” + x + “\n”); } //end of for loop System.out.println(“\nOutside for loop: x is “ + x); } // end of main } // end of class

OUTPUT inside while loop: i is 4, x is 10 inside while loop: i is 4, x is 30 inside while loop: i is 4, x is 50 inside while loop: i is 4, x is 70 inside while loop: i is 4, x is 90

Outside while loop: i is 4, x is 110

inside while loop: i is 5, x is 10 inside while loop: i is 5, x is 30 inside while loop: i is 5, x is 50 inside while loop: i is 5, x is 70 Outside while loop: i is 70

When above code is executed, the value of i*x is 350 when i=5 and x=70. As the if condition in while loop is evaluated to true, it executes ‘break out;’ statement. This will terminate the outer for loop labelled as ‘out’. If only break statement would have used.