View
483
Download
0
Category
Preview:
Citation preview
Day 1Introduction to Java
Data Types And VariablesOperators And Expressions
Control Flow Statement
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 2
Introduction to Java
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 3
Introduction
• The first version of Java was introduced in 1991.• Java was initially called as Oak.• In 1995, Oak was renamed to Java.• Java programming language is platform-independent and object-
oriented.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 4
Installation
• Java software can be downloaded from the following site:• http://www.oracle.com/technetwork/java/javase/downloads/index.html
• Run the executable file and install Java.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 5
Environment Setup
• The following two environment variables need to be set:• PATH• CLASSPATH
• The PATH environment variable specifies a set of directories whereexecutable programs are located.
• The PATH environment variable is set to the bin folder of JDKinstallation.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 6
Environment Setup (Contd.)
• The CLASSPATH environment variable specifies the class path on agiven system.
• A class path is a list of locations that are searched for classes whenthe Java Virtual Machine attempts to locate a referenced class.
• The CLASSPATH must include the current directory in order to runJava programs from the command line with the java command.
• The Classpath environment variable is set to the class files folder ofJava program.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 7
Environment Setup (Contd.)
• The environment variables are set using the System Properties dialogbox.
• To open the System Properties dialog box following steps should beperformed:
• Control PanelAll Control Panel Items System Advanced systemsettings
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 8
Environment Setup (Contd.)
• The System Properties dialog box will be display as shown in thefollowing figure.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 9
JVM, JRE, JDK
• JVM stands for Java Virtual Machine.• The JVM provides a platform-independent way of executing Java
code.• In Java, the Java complier translates the Java source code into an
intermediate code know as byte code.• The JVM interprets the byte code into the machine code depending
upon the underlying operating system and hardware combination.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 10
JVM, JRE, JDK
• The execution flow of a Java program.
Java ProgramJava Program Java CompilerJava Compiler BytecodeBytecode Java InterpreterJava Interpreter Real MachineReal Machine
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 11
JVM, JRE, JDK (Contd.)
• JRE stands for Java Runtime Environment.• JRE contains JVM, class libraries, and other supporting files.• If you want to run any java program, you need to have JRE installed in
the system.• The JVM runs the Java program using the class libraries and other
supporting files provided in JRE.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 12
JVM, JRE, JDK (Contd.)
• JDK stands for Java Development Kit.• JDK contains tools to develop and run Java program.• The various components of JDK are:
• Java Compiler• Java Interpreter• Java Disassembler• Java Header File Generator• Java Documentation• Java Debugger• Java Applet Viewer• JRE
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 13
JVM, JRE, JDK (Contd.)
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 14
Java Programming Basics
• Java programming language allows to create following application• Stand-alone Java application• Java Applet application
• A stand-alone Java application are CUI or GUI based application thatrun on a stand-alone computer.
• A Java Applet application are small internet application that run on abrowser.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 15
Java Programming Basics (Contd.)
• A structure of Java program may contain one or more sections asshown in the following list:
• Documentation• Package• Import• Interface• Class• Main Method
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 16
A First Java Program
• An example for defining a simple Java program:public class Demo {
public static void main(String args[]){System.out.println("My First Java Program");
}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 17
Compiling and executing Java Applications
• Compiling Java program• The javac command is used to compile a Java program.
• javac Demo.java
• Executing Java program• The java command is used to execute a Java program.
• java Demo
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 18
Java Source Files
• The following are the rules associated with declaring classes, importstatements, and package statements in a source file:
• There can be only one public class per source file.• If there is a public class in a file, then, the filename must match the class
name.• If the class is part of a package, the package statement must be the first line in
the code.• The import statements must lie between the package statement and the class
definition statement.• The package and import statements apply to all classes within the source
code file.• A source file can have more that one nonpublic class.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 19
The JDK Directory Structure
includeinclude
JDKJDK
binbin liblib jrejre src.zipsrc.zip dbdb
binbin liblib
clientclient serverserver extext securitysecurity appletsapplets serverserver
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 20
Data Types And Variables
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 21
Identifiers
• Identifiers are the names used to identify various Java items, such asa variable, class, method, interface, and package.
• Identifiers allows a programmer to refer to these item from otherplaces in the code.
• While name an identifier following rules must be followed:• Must start with a letter or currency character, $, or underscore, _.• After the first character, identifier can contain combination of letters,
currency character, underscore, or numbers.• The Java keywords can not be used as identifiers.• Identifiers are case-sensitive.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 22
Identifiers (contd.)
• The standard Java naming conventions are:• Packages names should be in lowercase.• Classes and interfaces names should be in camel case.• Methods and variable names should be in mixed case.• Constants names should be in uppercase.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 23
Identifiers (contd.)
• Example:
package testinterface PrintableIntf{…}class PaperDemo{int paperSize;double final MIN_THICKNESS=0.1;void displayData(){…}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 24
Primitive Datatypes
• The primitive datatypes in Java are:
• Note: To work with string data Java provides, String class and the default value is null.
Data type Description Default value
char 16 bits Unicode character data \u0000'
boolean boolean values true or false false
byte 8 bits signed integer 0
short 16 bits signed integer 0
int 32 bits signed integer 0
long 64 bits signed integer 0L
float 32 bits signed floating point number 0.0f
double 64 bits signed floating point number 0.0d
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 25
Primitive Datatypes (Contd.)
• The range of numeric primitive data types:
• The boolean data type does not has any range.• The char data type range is 0 to 216. That is it can hold data from
0 to 65535.
Data type BitsAllocated Min Range Max Range
byte 8 -27 27-1
short 16 -215 215-1
int 32 -231 231-1
long 64 -263 263-1
float 32 n/a n/adouble 64 n/a n/a
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 26
Primitive Variables Declaration andInitialization• Java provides containers called variables to store data within a
program.• To declare a primitive variables a combination of a datatype and
identifier is used.• The syntax to declare primitive variable:
<datatype> <identifier>;
• An example to declare primitive variable :int val;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 27
Primitive Variables Declaration andInitialization (Contd.)• After declaring a primitive variable, a value can be assigned.• The process of assigning values to a variable is called initialization.• The syntax to initialize a primitive variable:
<variable name>=<value>;
• An example to initialize a primitive variable :int val;val=10;
• The declaration and initialization of primitive variable can be done ina single line as shown in the following code:int val=10;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 28
Literals
• A literal is constant value.• Literals are commonly used to initialize a variable.• Different types of literals are:
• Integer• Floating• Boolean• Character• String
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 29
Literals (Contd.)
• The integer literal are used to represent integer numbers.• An integer literal is of type long if it ends with the letter L or l else it is
of type int.• The integer literals can be represented using the following number
system:• Decimal• Binary• Octal• Hexadecimal
• Decimal number system consists of digits from 0 to 9.• Example: int a=30;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 30
Literals (Contd.)
• Binary number system consists of the digits 0 and 1.• Example: int a=0b11110;
• Octal number system consists of digits from 0 to 7. Therefore, torepresent octal integer, a zero is placed before the number.
• A octal number can include 21 digits excluding the zero• Example: int a=036;• Here, a is holding the value, 30.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 31
Literals (Contd.)
• Hexadecimal number system consists of digits from 0 to 9 and the lettersfrom A to F.
• Example: int a=0x1E;• Here, a is holding the value, 30.
• The floating literals are used to represent fractional number.• A floating-point literal is of type float if it ends with the letter F or f; else its
type is double.• Example: float fValue=45.8f;
double dValue=45.8;double dValE=1.234e2;float fValE=1.234e2f;
• Here, dValE and fValE are using scientific notation.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 32
Literals (Contd.)
• In numeric literals, integer and floating any number of underscorecharacters (_) can appear anywhere between digit.
• This feature enables to separate groups of digits in numeric literals toimprove the readability.
• Example:int iVal=1_999;
float fVal=1_999.11_1f;
• Boolean literals are used to represent boolean values.• The boolean values are true and false
• Example: boolean boolVal=true;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 33
Literals (Contd.)
• Character literals are used to represent characters.• The character literals are enclosed in single quotes.• Character literals can also be represented using the Unicode
notification.• Example: char cVal='a';
char cValU='\u004E';• Here, the cValU is holding the letter, N.
• String literals are used to represent string data.• String literals are enclosed in double quotes.
• Example: String sVal="Hello";
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 34
Literals (Contd.)
• An example to work with literals:public class LiteralsDemo {
public static void main(String[] argv) {int decimal=30;int binary=0b11110;int octal=036;int hexadecimal=0x1E;float fValue=45.8f;double dValue=45.8;
double dValE=1.234e2;
float fValE=1.234e2f;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 35
Literals (Contd.)
int iVal=1_999;
float fVal=1_999.11_1f;
boolean boolVal=true;
char cVal='a';
char cValU='\u004E';
String sVal="Hello";
System.out.println(decimal+", "+binary+", "+octal+", "+
fValue+", "+dValue+", "+dValE+", "+fValE+", "+iVal+","+fVal+", "+
boolVal+", "+cVal+", "+cValU+", "+sVal);
}
}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 36
Literals (Contd.)
• The preceding code output will be:30, 30, 30, 45.8, 45.8, 123.4, 123.4, 1999, 1999.111,true, a, N, Hello
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 37
Arrays
• An array is a collection of data storage location that can holds onlysame type of data.
• The data stored in an array is called element.• Each element in an array is stored at a specific index.• An array can be of any type and can have one or more dimensions.• The dimension of an array is determined by the number of indexes
needed to identify an element.• The commonly used array dimensions are:
• One-dimensional array• Two-dimensional array
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 38
Arrays (Contd.)
• One dimensional array is represented with single index.• The syntax to declare one-dimensional array:
<array_type> <array_name>[];
• The syntax to create one-dimensional array:<array_name>=new <array_type>[size];
• An example to create one-dimensional array:int rollNo[];rollNo=new int[5];Orint rollNo[]=new int[5];
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 39
Arrays (Contd.)
• The following figure shows the elements position in a one-dimensional array:
1st element 5th element
rollNo
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 40
Arrays (Contd.)
• The syntax to initialize one-dimensional array:<array_name>[index_no]=value;or<array_type> <array_name>[]={array_element1,..,array_element n}
• An example to initialize one-dimensional array:rollNo[0]=111;……………rollNo[4]=115;
Orint rollNo[]={111,112,113,114,115};
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 41
Arrays (Contd.)
• The following figure shows the data stored in a one-dimensionalarray:
111 112 113 114 115
Elements
0th
index1st
index2nd
index3rd
index4th
index
rollNo
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 42
Arrays (Contd.)
• An example to work with one-dimensional array:public class Demo {
public static void main(String args[]){int rollNo[]={111,112,113,114,115};System.out.println(rollNo[3]);
}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 43
Arrays (Contd.)
• Two dimensional array is represented with two indexes.• The syntax to declare two-dimensional array:
<array_type> <array_name>[][];
• The syntax to create two-dimensional array:<array_name>=new <array_type>[row_size][col_size];
• An example to create two-dimensional array:int pointCord[][];pointCord =new int[3][2];Orint pointCord[][]=new int[3][2];
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 44
Arrays (Contd.)
• The following figure shows the elements position in two-dimensionalarray:
1st row2nd row3rd row
1st column 2nd column
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 45
Arrays (Contd.)
• The syntax to initialize two-dimensional array:<array_name>[row_index][col_index]=value;
or<array_type> <array_name>[][]={{row0col0_element,…,row0coln_element} ,.., {rowncol0_element,..,rowncoln_element} }
• An example to initialize two-dimensional array:pointCord[0][0]=5;……………pointCord[2][1]=4;
Or
int pointCord [][]={{5,3},{4,3},{2,8}};
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 46
Arrays (Contd.)
• The following figure shows the data stored in two-dimensional array.
5 34 32 8
[rowindex0][colindex0][rowindex1][colindex0][rowindex2][colindex0]
[rowindex0][colindex1][rowindex1][colindex1][rowindex2][colindex1]
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 47
Arrays (Contd.)
• An example to work with two-dimensional array:public class Demo {
public static void main(String args[]){int pointCord[][]={{5,3},{4,3},{2,8}};System.out.println(pointCord[2][1]);
}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 48
Operators And Expressions
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 49
Expression
• An expression is a syntactic construction that has a value.• Expressions are formed by combining operands and operators, which
returns a value.• An example of expression:
a+b• Here a and b are operands and + is the operator.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 50
Operators
• Operators are special symbols that perform specific operations onone, two, or three operands, and then return a result.
• The different types of operators are:• Arithmetic Operators• Assignment Operator• Relational Operators• Logical Operators• Increment and Decrement Operators• The Conditional Operator
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 51
Assignment Operator
• An assignment operator,=, is used to assign a value.• The assignment operator is evaluated from right to left.• An example to use assignment operator:
a = b = c = 0;The preceding statement would assign 0 to c, then c to b then b to a.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 52
Arithmetic Operators• The arithmetic operators are used to perform arithmetic operations,
such as addition, subtraction, multiplication, and division.• The following tables shows the arithmetic operators, its description,
and its usage:Operator Description Example
Assume integer variable a holds 10 and variableb holds 20
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left handoperand
a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand a / b will give 2
% Modulus - Divides left hand operand by right hand operand andreturns remainder
b % a will give 0
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 53
Arithmetic Compound Assignment Operators
• Java allows you to combine the arithmetic and assignment operatoras shown in the following table:
Operator Description+= Addition assignment-= Subtraction assignment*= Multiplication assignment/= Division assignment%= Modulus assignment
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 54
Arithmetic Compound Assignment Operators(Contd.)• An example to work with arithmetic operators:
a=10b=20b=a+b
• The preceding code snippet can be otherwise written as:a=10b+=a;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 55
Relational Operators• Relational operators determine the relationship that one operand has
to other.• The following tables shows the relational operators its description,
and its usage:
Operator Description ExampleAssume integer variable a holds 10 and variable bholds 20
== Checks if the values of two operands are equal or not, if yes then conditionbecomes true.
(a == b)is not true
!= Checks if the values of two operands are equal or not, if values are not equalthen condition becomes true.
(a != b)is true
> Checks if the value of left operand is greater than the value of right operand,if yes then condition becomes true.
(a > b)is not true
< Checks if the value of left operand is less than the value of right operand, ifyes then condition becomes true.
(a < b)is true
>= Checks if the value of left operand is greater than or equal to the value ofright operand, if yes then condition becomes true.
(a >= b)is not true
<= Checks if the value of left operand is less than or equal to the value of rightoperand, if yes then condition becomes true.
(a <= b)is true
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 56
Increment and Decrement Operators
• The increment operator, ++, increases its operands value by one.• The decrement operator, --, decreases its operands value by one.• The increment and decrement operator of two types:
• Prefix• Postfix
• In prefix increment or decrement operator, the operator ++ or –precedes the operand. Example: ++a or --a
• In postfix increment or decrement operator, the operator ++ or –follows the operand. Example: a++ or b++
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 57
Increment and Decrement Operators (Contd.)
• An example to work with prefix increment operator:public class Demo {
public static void main(String args[]){int a=1;int b=++a;System.out.println("a="+a);System.out.println("b="+b);
}}
• The preceding code will generate the output:a=2b=2
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 58
Increment and Decrement Operators (Contd.)
• An example to work with postfix increment operator:public class Demo {
public static void main(String args[]){int a=1;int b=a++;System.out.println("a="+a);System.out.println("b="+b);
}}
• The preceding code will generate the output:a=2b=1
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 59
Logical Operators
• The logical operators operates on boolean operand.• The following tables shows the logical operators its description, and
its usage:Operator Description Example
Assume Boolean variables a holdstrue and variable b holds false
&& Called Logical AND operator. If both the operandshold true value, then the condition becomes true.
(a && b) is false.
|| Called Logical OR Operator. If any of the two operandshold true value, then the condition becomes true.
(a || b) is true.
! Called Logical NOT Operator. Use to reverses thelogical state of its operand. If a condition is true thenLogical NOT operator will make false.
!(a && b) is true.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 60
Conditional Operator
• The conditional operator,?:, is used to create a simple conditionalexpression.
• An example to work with conditional operator:public class Demo {
public static void main(String args[]){int a=10;int b=20;int max=a>b?a:b;System.out.println("max="+max);
}}
• The preceding code will display the output:max=20
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 61
Operator Precedence
• The precedence of operators is shown in the following table:Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 62
Operator Precedence (Contd.)
• The closer to the top of the table an operator appears, the higher itsprecedence.
• Operators with higher precedence are evaluated before operatorswith relatively lower precedence.
• Operators on the same line have equal precedence.• When operators of equal precedence appear in the same expression,
a rule must govern which is evaluated first.• All binary operators except for the assignment operators are
evaluated from left to right; assignment operators are evaluated rightto left.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 63
Type Casting
• Type casting is the process of converting an entity of one data typeinto another data type.
• The different type casting supported by Java are:• Implicit type casting• Explicit type casting
• In implicit type casting, one type of data is assigned to another typeof variable.
• An example of implicit type casting:int a=10;long b=a;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 64
Type Casting (Contd.)
• Implicit type casting will take place in two condition:• The two types must be compatible.• The destination type must be larger than the source type.
• In explicit type casting, a larger data type value is converted andstored in smaller data type variable.
• An example of explicit type casting:long a=10;int b=(int)a;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 65
Type Casting (Contd.)
• Consider the following code snippet:float fVal=100.56f;int iVal=(int)fVal;
• In the preceding code snippet, iVal, will have the value,100. This isbecause an integer variable can not store a decimal value. Therefore,the digit after the decimal part is lost.
• Consider the following code snippet:int iVal= 150;byte bVal=(byte)iVal;
• In the preceding code snippet, bVal, will have the value, -106.© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com 66
Type Casting (Contd.)
• This is byte variable can hold numbers between the range -128 to127.
• The 16 bit binary representation of 150 is:0000000010010110
• When the 8 bits are lost from 16 bit, the value is:10010110
In a eight bit representation, the left most is the sign bit. Here, the leftmost bit is 1, which mean negative value. Therefore, the bVal holds thevalue -106
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 67
Control Flow Statements
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 68
Statements
• Statements contain the instructions to execute by the complier.• Control statements enable us to specify the order in which the
various instructions in a program are to be executed by the computer.• Control statements determine the flow of control in a program.• Different types of control statements in Java are:
• Conditional Construct Control Statement• Repetition or Loop Construct Control Statement
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 69
Conditional Construct Control Statement
• The conditional construct control statements allow a program toexecute a certain piece of code based on a decision.
• The different types of conditional construct control statements are:• if construct• if-else construct• switch construct
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 70
if Construct
• The different types of conditional cotro• The if construct tells the program to execute a certain section of code
only if a particular test evaluates to true.• The syntax to work with if construct :
if (condition)statement1;
• In the preceding syntax,• Each statement may be a single statement or a compound statement
enclosed in curly braces (a block).• The condition is any expression that returns a boolean value.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 71
if Construct (Contd.)
• The if construct example:char option='y';
if(option == 'y'){System.out.println("If block executed");
}System.out.println("After if block");
• The output of the preceding code snippet will be:If block executedAfter if block
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 72
if Construct (Contd.)
• An if statement can be the target of another if or else statement andis known as nested if.
• The nested if construct example:int a=12;if(a>=10){if(a<=20)System.out.println("value of a is in range: 10 to 20");}
• The output of the preceding code snippet will be:value of a is in range: 10 to 20
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 73
if-else Construct
• The if-else construct is Java’s conditional branch statement that canbe used to route program execution through two different paths.
• The syntax to work with if-else construct :if (condition) statement1;else statement2;
• In the preceding syntax,• Each statement may be a single statement or a compound statement
enclosed in curly braces (a block).• The condition is any expression that returns a boolean value.• The else clause is optional.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 74
if-else Construct (Contd.)
• The if…else construct example:int a=1;int b=5;if(a>b)
System.out.println(a+" is greater than "+b);else
System.out.println(b+" is greater than "+a);
• The output of the preceding code snippet will be:5 is greater than 1
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 75
if-else Construct (Contd.)
• A common programming construct that is based upon a sequence ofnested ifs is the if-else-if ladder.
• The syntax to work with if-else-if ladder construct:if (condition)statement;else if (condition)statement;else if (condition)statement;…elsestatement;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 76
if-else Construct (Contd.)
• The if-else-if ladder construct example:int month = 4; // AprilString season;if(month == 12 || month == 1 || month == 2)season = "Winter";else if(month == 3 || month == 4 || month == 5)season = "Spring";else if(month == 6 || month == 7 || month == 8)season = "Summer";else if(month == 9 || month == 10 || month == 11)season = "Autumn";elseseason = "Bogus Month";System.out.println("April is in the " + season + ".");
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 77
if-else Construct (Contd.)
• The output of the preceding code snippet will be:
April is in the Spring.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 78
Switch Construct
• The switch statement is Java’s multi way branch statement.• It provides an easy way to dispatch execution to different parts of
code based on the value of expression.• It often provides a better alternative than a large series of if-else-if
statements.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 79
Switch Construct (Contd.)
• The syntax to work with switch construct:switch (expression) {case value1:// statement sequencebreak;case value2:// statement sequencebreak;…case valueN:// statement sequencebreak;default:// default statement sequence}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 80
Switch Construct (Contd.)
• The expression must be of type byte, short, int, or char.• Each of the values specified in the case statements must be of a type
compatible with the expression.• Each case value must be a unique literal .• Duplicate case values are not allowed.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 81
Switch Construct (Contd.)
• The switch construct example:class SampleSwitch {public static void main(String args[]) {for(int i=0; i<6; i++)switch(i) {case 0:System.out.println("i is zero.");break;case 1:System.out.println("i is one.");break;
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 82
Switch Construct (Contd.)
case 2:System.out.println("i is two.");break;case 3:System.out.println("i is three.");break;default:System.out.println("i is greater than 3.");}}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 83
Switch Construct (Contd.)
• The output of the preceding code will be:
i is zero.i is one.i is two.i is three.i is greater than 3.i is greater than 3.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 84
Switch Construct (Contd.)
• Consider the following code:public class SwitchDemo {
public static void main(String args[]){char cVal='a';switch(cVal){case 'a':case 'e':case 'i':case 'o':
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 85
Switch Construct (Contd.)
case 'u':System.out.println("Vowles");break;
default:System.out.println("Consonant");break;
}}
}
• The preceding code output will be:Vowles
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 86
Switch Construct (Contd.)
• In the preceding code, if the break statement after the statement,System.out.println("Vowles");, is removed the output will be:Vowles
Consonant
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 87
Loop Construct Control Statement
• The loop construct control statements allow to repeat a block of codemultiple times, while the given condition is true.
• The different types of loop construct control statements are:• while loop construct• do-while loop construct• for loop construct
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 88
while Loop Construct
• The while loop is Java’s most fundamental loop statement.• It repeats a statement or block while its controlling expression is true.• The syntax to work with while loop:
while(condition) {// body of loop}
• The condition can be any Boolean expression.• The body of the loop will be executed as long as the conditional
expression is true.• When condition becomes false, control passes to the next line of code
immediately following the loop.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 89
while Loop Construct (Contd.)
• The while loop construct example:int i = 4;while(i > 0) {System.out.println("value " + i);i--;
• The output of the preceding code snippet will be:value 4value 2value 2value 1
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 90
while Loop Construct (Contd.)
• An example of nested while loop:public class WhileLoopDemo {public static void main(String args[]){
{int i = 1, j = 1;while (i <= 2){
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 91
while Loop Construct (Contd.)
while (j <= 10) {
System.out.println(i + " * " + j + " = " + (i * j));
j++;
}
i++;
System.out.println("");
System.out.println("");
}
}
}
} © People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 92
while Loop Construct (Contd.)
• The preceding code output will be:1 * 1 = 11 * 2 = 21 * 3 = 31 * 4 = 41 * 5 = 51 * 6 = 61 * 7 = 71 * 8 = 81 * 9 = 91 * 10 = 10
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 93
do-while Loop Construct
• When the condition in a while loop is found false for the first time,the body of the loop is not executed at all.
• At times, you need to execute the body of the loop at least once. Javasupplies a loop that does just that: the do-while loop.
• The do-while loop always executes its body at least once, because itsconditional expression is at the bottom of the loop.
• The syntax to work with do-while construct:do {// body of loop} while (condition);
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 94
do-while Loop Construct (Contd.)
• The do-while construct example:
int n = 0;do {System.out.println("value " + n);n--;} while(n > 0);
• The output of the preceding code snippet will be:value 0
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 95
do-while Loop Construct (Contd.)
• An example of nested while loop:public class DoWhileDemo {
public static void main(String args[]) {int i = 1, j;do {
j=1;do {
System.out.print(i + " ");j++;
} while (j <= i);
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 96
do-while Loop Construct (Contd.)
System.out.println("");i++;
} while (i <= 5);
}}
• The preceding code output will be:12 23 3 34 4 4 45 5 5 5 5
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 97
for Loop Construct
• Similar to while and do-while, for loop is used to execute a set of statements.• The syntax to work with for loop:
for(initialization; condition; iteration) {// body}
• When the loop first starts, the initialization portion of the loop is executed.• Then, condition is evaluated.• If this expression is true, then the body of the loop is executed. If it is false, the
loop terminates.• Then, the iteration portion of the loop is executed.• This process repeats until the controlling expression is false.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 98
for Loop Construct (Contd.)
• The for loop construct example:
for(int n=1; n<5; n++)System.out.println("tick " + n);
• The output of the preceding code snippet will be:tick 1
tick 2tick 3tick 4
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 99
for Loop Construct (Contd.)
• An example of nested for loop construct example:int i, j;for(i=0; i<5; i++) {for(j=i; j<5; j++)System.out.print("*");System.out.println();}
• The output of the preceding code snippet will be:***************
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 100
for Loop Construct (Contd.)
• To create an endless for loop following code snippet is used:for(; ;)
• An example to demonstrate a for loop with multiple variables:public class ForLoopDemo {
public static void main(String args[]){for(int x=1,y=10;(x<10)&& (y>1);x++,y--){
System.out.println("x="+x+" y="+y);}
}}
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 101
for Loop Construct (Contd.)
• The preceding code output will be:x=1 y=10x=2 y=9x=3 y=8x=4 y=7x=5 y=6x=6 y=5x=7 y=4x=8 y=3x=9 y=2
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 102
Enhanced For Loop Construct
• The enhanced for loop construct is designed to cycle through a collectionof objects, such as an array, in strictly sequential fashion, from start tofinish.
• The enhanced for loop construct of for is also referred to as for-eachconstruct
• The syntax to work with enhanced for loop:for(type itr-var : collection)statement-block
• Type specifies the type and itr-var specifies the name of an iterationvariable that will receive the elements from a collection, one at a time,from beginning to end.
• The collection being cycled through is specified by collection.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 103
Enhanced For Loop (Contd.)
• The enhanced for loop construct example:int nums[] = { 1, 2, 3, 4, 5 };int sum = 0;for(int x: nums){System.out.println("Value is: " + x);sum += x;}System.out.println("Summation: " + sum);
• The output of the preceding code snippet will be:Value is: 1Value is: 2Value is: 3Value is: 4Value is: 5Summation: 15
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 104
The Continue Statement
• At times, you need to force an early iteration of a loop.• You might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. The continuestatement performs such an action.
• By default in while and do-while loops, a continue statement causes controlto be transferred directly to the conditional expression that controls theloop.
• By default in a for loop, control goes first to the iteration portion of the forstatement and then to the conditional expression.
• The default transfer of the control can be modified by using a labeledcontinue statement.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 105
The Continue Statement (Contd.)
• The continue statement example:for(int i=0; i<10; i++) {System.out.print(i + " ");if (i%2 == 0) continue;System.out.println("");}
• The output of the preceding code snippet will be:0 12 34 56 78 9
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 106
The Continue Statement (Contd.)
• Java• An example to work with labeled continue statement:
public class LabeledContinueDemo {public static void main(String args[]) {
Outer:for (int i = 0; i < 2; i++) {
inner:for (int j = 0; j < 2; j++) {
System.out.println("InnerFor Loop");
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 107
The Continue Statement (Contd.)
continue Outer;}
System.out.println("Outer For Loop");}
System.out.println("Loop Ended");}
}
• The preceding code output will be:Inner For LoopInner For LoopLoop Ended
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 108
The Break Statement
• We often come across situations where we want to jump out of aloop instantly, without waiting to get back to the conditional test.
• The keyword break allows us to do this.• When break is encountered inside any loop, control automatically
passes to the first statement after the loop.• The labeled break statement can be used to exit out of the labeled
loop.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 109
The Break Statement (Contd.)
• An example to work with labeled break statement:public class LabeledBreakDemo {
public static void main(String args[]) {Outer:
for (int i = 0; i < 2; i++) {inner:
for (int j = 0; j < 2; j++) {if(i==j)
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 110
The Break Statement (Contd.)
System.out.println("InnerFor Loop");
break Outer;}
System.out.println("Outer For Loop");}
System.out.println("Loop Ended");}
}
• The preceding code output will be:Inner For Loop
Loop Ended
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 111
Summary
• You have learnt that:• Java programming language is platform-independent and object-oriented.• The PATH environment variable specifies a set of directories where executable
programs are located.• The CLASSPATH environment variable specifies the class path on a given
system.• The JVM provides a platform-independent way of executing Java code.• JRE contains JVM, class libraries, and other supporting files.• JDK contains tools to develop and run Java program.• Java programming language allows to create following application
• Stand-alone Java application• Java Applet application
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 112
Summary (Contd.)
• The a set of rules are associated with declaring classes, import statements,and package statements in a source file.
• Identifiers are the names used to identify various Java items, such as avariable, class, method, interface, and package.
• Java provides containers called variables to store data within a program.• A literal is constant value.• An array is a collection of data storage location that can holds only same type
of data.• An expression is a syntactic construction that has a value.• Operators are special symbols that perform specific operations on one, two,
or three operands, and then return a result.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 113
Summary (Contd.)
• Operators with higher precedence are evaluated before operators withrelatively lower precedence.
• Type casting is the process of converting an entity of one data type intoanother data type.
• Statements contain the instructions to execute by the complier.• The conditional construct control statements allow a program to execute a
certain piece of code based on a decision.• The loop construct control statements allow to repeat a block of code
multiple times, while the given condition is true.• The enhanced for loop construct is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to finish.• The continue and break statements are used to stop either the current
iteration or the entire loop.
© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 114
Recommended