Leveraging Basic Concepts
Module 2
Overview
Control Statements: Iterators or Loops
Arrays
Strings
Methods
Exception Handling
Iterators: Loops in Java
FOR Loop WHILE Loop DO WHILE Loop
Iterators: Loops in Java
Problem Statement
FOR LOOP: How it works?
FOR LOOP: FOR LOOP SYNTAX
for (int i = 0; i < 3; i++) { for (counter; condition; inc/decrement) {
System.out.println(“Hello”); // Put your code here
} }
Initialize à Condition Check à Code Execute à Increment
Output:
Loop 1 i = 0 à 0 < 3 à true à Print “Hello” à i++ à i = 1 Hello
Loop 2 à 1 < 3 à true à Print “Hello” à i++ à i = 2 Hello
Loop 3 à 2 < 3 à true à Print “Hello” à i++ à i = 3 Hello
End of Loop à 3 < 3 à false à Loop Terminates
Loops are the Control Statements that are used to
iterate a part of the program several times.
Syntax and Example
FOR Loop Syntax FOR Loop Example
for (counter; condition; inc/decrement) { for (int i = 0; i < 3; i++) {
// Your Code System.out.println(“Hello”);
} }
WHILE Loop Syntax WHILE Loop Example
while (condition) { while (i < 3) {
// Your Code System.out.println(“Hello”);
// Increment/Decrement Counter i++;
} }
DO WHILE Loop Syntax DO WHILE Loop Example
do { do {
// Your Code System.out.println(“Hello”);
// Increment/Decrement Counter i++;
} while (condition) } while (i < 3)
Which Is Better? What To Use?
If the number of iteration is fixed
➝ For Loop: Condition à Code
If the number of iteration is not fixed
➝ While Loop: Condition à Code
If the number of iteration is not fixed and you need to
execute the code at least once
➝ Do-while Loop: Code à Condition
Iterators
For Loop
While Loop
Do While Loop
Difference between these loops
In what scenario we use loops?
Array
Collection of Same Data Type
• 1D Array or Array
• 2D Array
Array
40 7 12
4.9f 12.3f
int[] arrayOne = { 40, 7, 12 };
float[] arr = { 4.9f, 12.3f };
‘8’ ‘$’ ‘&’ ‘h’
char[] arrayTwo = { ‘8’, ‘$’, ‘&’, ‘h’ };
2D Array
Collection of Same Data Type in 2 Dimensional Array
OR, Collection of 1D Array
2D Array
2D Array Example
int[][] myArray = { 0 1 2 3
0 { 3, 5, 1, 9 },
1 { 10, 15, 3, 0 },
2 { 1, 11, 31, 90 },
3 { 2, 51, 1, 9 }
};
System.out.print( myArray[3][1] ) // prints 51
System.out.print( myArray[3][3] ) // prints 9
Array
SIZE: 3
Properties
INDEX 0 1 2 ➝ It is a data structure
➝ Fixed Size
➝ Collection of same data type
40 7 12 ➝ Elements are present in sequence
➝ Index starts from 0
int[] arrayOne = { 40, 7, 12 };
Disadvantages
int[] arrayOne = new int[3]; ➝ It has fixed size
arrayOne[0] = 40;
arrayOne[1] = 7; ➝ You cannot add new elements
arrayOne[2] = 12;
String
“I am a String”
Few Important Concepts
Class Reference Object Or
Variable Instance of a Class
Heap
Scanner scanner = new Scanner(System.in); // S Memory
String name = “Internshala”; // S1
S2
String company = new String(“Internshala”);// S2
S
Stack Memory
S1
company scanner
name
How Strings Are Created?
Using Literals
String str = “Rahul”; // S1 Creates a new instance
String str1 = “Robert”; // S2 Create a new instance Heap
String str2 = “Robert”; // S2 Does Not create a new instance
S5 [ Vishal ]
String
Using new Keyword Constant
S6 [ Vishal ]
String str3 = new String(“Vishal”); // S5 Creates a new instance Pool
S1 [ Rahul ]
String str4 = new String(“Vishal”); // S6 Creates a new instance
S2 [ Robert ]
Stack Memory
str
str3
str4
str1 str2
String
String is an object
It is sequence of characters
Each character of the String is indexed
➝ The index starts from 0
They are created in two ways
➝ Using literals directly
➝ Using new keyword
Strings are Immutable [ Check helper text for details ]
➝ Once created cannot be modified later
Methods or Functions
What Are They? How They Look Like?
Methods
Why Do We Need Methods?
Banking Application
Calculate Simple Interest
Method Overloading
Same Name but Different in Parameters
Methods
Methods are the collection of statements that are grouped together to
perform a specific operation
Method
Syntax
modifier Return type Method Name Formal Parameters
OR Formal Arguments
public static void main(String[] args) {
// Method Body: Put your code here
int sum = findSum(2, 3);
Actual Parameters
System.put.print (sum);
Return Statement OR Actual Arguments
return;
}
private static int findSum(int a, int b) {
int sum = a + b;
return sum;
}
Method
How to call a method?
How to pass values to the methods?
How to return a value from the methods?
Advantages
➝ Reduces code redundancy
➝ Code reuse
➝ Makes code clean: Easy to read
Method Overloading: Same name but different parameters
• add( )
• add( int, int )
• add( int, int, float )
Method
Few important predefined methods that we used so far
➝ String.concat( String value )
➝ String.charAt( int index )
➝ System.out.print( value )
➝ Scanner.nextInt( )
Exception Handling
Problem Statement
Exception Handling: Three Possible Case
When you face a When you have When you don’t know
Exception Multiple Exceptions the Exception name
try { try { try {
… code ... … code ... … code ...
} catch( Name1 e ) { } catch( Name1 | Name2 e ) { } catch ( Exception e ) {
… code ... … code ... … code ...
} } }
Try-catch block Multi-catch block
List of Few Common Exceptions
Please See Helper Text
Exception Handling
Exception handling
➝ Handles runtime errors
➝ Normal flow of program continues
➝ Prevents application from crashing
Use catch block to handle a exception
Use multi-catch block to handle multiple exception
finally block is always executed
➝ Use only important code
Miscellaneous Concepts
Miscellaneous Concepts
Naming Convention
• Methods
Naming Convention
Variables Naming Convention
By convention we follow “Camel Case” style
➝ First letter is lower case
➝ Start of each word after the first is lower case
➝ All other letters are lower case
Examples name salary firstName isAlive myPanCardNumber grade4 level2Training
Methods Naming Convention
Same as that of Variables but
➝ All names should be a verb
Examples print( ) add( ) calculate( ) calculateSimpleInterest( ) applyBrakes( )
String.length( ) main( ) Scanner.nextInt( )
Module Summary
Iterators or Loops: For, While and DoWhile
Arrays: 1D Array, 2D Array, For Each loop, Nested For Loop
Strings
Methods
Exception Handling
Assignment and Quiz
End of Module 2