CH 1 Overview of Java Programming
CH 1 Overview of Java Programming
1-1
Java Variables
◆A variable is a symbolic name for a memory location in which data can be stored
and subsequently recalled.
◆Variables are used for holding data values so that they can be utilized in various
computations in a program. It is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
◆ There are three types of variables in java: local, instance and static.
◆ There are two types of data types in Java: primitive and non-primitive.
1-2
Variable Declaration
◆ Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
◆ Declaring a variable means defining (creating) a variable.
◆ Example:
◼ int myAge;
◼ float length;
◆ But in python, we don't need to specify the type of variable because python is a infer language
and smart enough to get variable type. When we assign any value to the variable, that variable
is declared automatically.
1-3
Assigning Values to Your Variable
◆You assign a value to a variable by using the assignment operator (=).
◆Thus, you would assign 5 to Width by writing
int Width;
Width = 5;
◆You can combine these steps and initialize Width when you define it
by writing.
int Width = 5;
// create two int variables and initialize them
int width = 5, length = 7;
1-4
Types of Variables
◆ There are three types of variables in Java:-
1) Local Variable
⚫ A variable declared inside the body of the method. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.
⚫ A local variable cannot be defined with "static" keyword.
2) Instance Variable
⚫ A variable declared inside the class but outside the body of the method,
⚫ It is not declared as static.
⚫ It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
⚫ A variable that is declared as static is called a static variable. It cannot be local.
⚫ You can create a single copy of the static variable and share it among all the instances of the class.
⚫ Memory allocation for static variables happens only once when the class is loaded in the memory.
1-5
Example to understand the types of variables in java
1. public class A
2. {
1-7
Basic Data Types and their Ranges in Java
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
1-8
Example: A Demonstration of the Use of Variables Java
1-9
◆ An array is an ordered list of values 1.2. Arrays
The entire array
has a single name Each value has a numeric index
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
1 - 10
Arrays
◆ A particular value in an array is referenced using the array name followed by the index in brackets
◆ For example, the expression scores[2, refers to the value 94 (the 3rd value in the array)
◆ That expression represents a place to store a single integer and can be used wherever an integer variable can be
used
◆ For example, an array element can be assigned a value, printed, or used in a calculation:
⚫ scores[2] = 89;
⚫ scores[first] = scores[first] + 2;
1 - 11
Arrays
◆ The values held in an array are called array elements
◆ An array stores multiple values of the same type (the element type)
◆ Therefore the name of the array is a object reference variable, and the array
1 - 12
itself must be instantiated
Arrays
◆ Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position.
◆ Disadvantages
• Size Limit: It doesn't grow its size at runtime. To solve this problem, collection framework is
used in Java which grows automatically.
◆ Types of Array in java:- there are two types of array.
• Single Dimensional Array
• Multidimensional Array
1 - 13
Single Dimensional Array in Java
1 - 14
Example of Java Array
◆ Simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
1. class Testarray {
4. a[0]=10;//initialization
6. //traversing array
8. System.out.println(a[i]);
9. }}
1 - 15
Declaration, Instantiation and Initialization of Java Array
Example:-
◆
3. class Testarray1{
6. //printing array
8. System.out.println(a[i]);
9. }}
1 - 16
For-each Loop for Java Array
◆The Java for-each loop prints the array elements one by one.
It holds an array element in a variable, then executes the
body of the loop.
◆The syntax:
for(data_type variable:array){
//body of the loop
}
1 - 17
Example
4. int arr[]={33,3,4,5};
6. for(int i:arr)
7. System.out.println(i);
8. }}
1 - 18
ArrayIndexOutOfBoundsException
◆ The Java Virtual Machine (JVM) throws an
ArrayIndexOutOfBoundsException if length of the array in negative, equal
to the array size or greater than the array size while traversing the array.
1. //Java Program to demonstrate the case of ArrayIndexOutOfBoundsException in a Java Array.
2. public class TestArrayException{
3. public static void main(String args[]){
4. int arr[]={50,60,70,80};
5. for(int i=0;i<=arr.length;i++){
6. System.out.println(arr[i]);
7. }
8. }}
1 - 19
Multidimensional Array in Java
as matrix form).
⚫ Syntax to Declare Multidimensional
▪ dataType[][] arrayRefVar; (or)
▪ dataType []arrayRefVar[];
1 - 20
Example of Multidimensional Java Array
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" "); }
10. System.out.println();
11.}
12.}}
1 - 21
What is the class name of Java array?
◆ In Java, an array is an object. For array object, a proxy class is created whose name can be
obtained by getClass().getName() method on the object.
1. //Java Program to get the class name of array in Java
2. class Testarray4{
5. int arr[]={4,4,5};
7. Class c=arr.getClass();
8. String name=c.getName();
10.System.out.println(name);
11. }}
1 - 22
1.3. Decision and Repetition statement
◆ Java compiler executes the code from top to bottom. The statements in
the code are executed according to the order in which they appear.
◆ Java provides three types of control flow statements.
1. Decision Making statements 3. Jump statements
1. if statements
1. break statement
2. switch statement
2. continue statement
2. Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
1 - 23
Decision-Making statements:
◆ If statement and
◆ switch statement.
1 - 24
1) If Statement:
◆"if" statement is used to evaluate a condition.
◆The control of the program is diverted depending upon the specific
condition.
◆The condition of the If statement gives a Boolean value, either true or
false.
◆Some if statements are:-
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1 - 25
Syntax of Decision-Making statement (1)
◆ Syntax of if statement :-
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
3. }
4. else{
6. }
1 - 26
Syntax of Decision-Making statement (2)
⚫ The if-else-if statement contains the if-statement followed by multiple else-if statements.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
1 - 27
Syntax of Decision-Making statement (3)
◆ Syntax of Nested if-statement:-
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
5. }
6. else{
8. }
9. }
1 - 28
Syntax of Decision-Making statement (4)
◆ Switch Statement:
◼ In Java, Switch statements are similar to if-else-if statements.
◆ Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression. It
is optional.
• Break statement terminates the switch block when the condition is satisfied. It is optional, if
not used, next case is executed.
• While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
1 - 29
Syntax of Decision-Making statement (4)
◆ The syntax to use the switch statement :-
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. . . .
6. case valueN:
7. statementN;
8. break;
9. default:
10. default statement;
11. }
1 - 30
The following example to understand the flow of the switch
statement.
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
6. break;
8. break;
9. default: System.out.println(num);
10.} } }
1 - 31
Loop Statements
particular condition.
⚫ In Java, we have three types of loops that execute similarly. However,
there are differences in their syntax and condition checking time.
1.forloop
2.while loop
3.do-while loop
1 - 32
Java for loop
◆ Syntax for loop
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
◆ Example:-
1. public class Calculattion {
2. public static void main(String[] args) {
4. int sum = 0;
6. sum = sum + j;
7. }
9. } }
1 - 33
Java for-each loop
2.//statements
3.}
1 - 34
Example to understand the functioning of the for-each loop in
Java.
1. public class Calculation {
2. public static void main(String[] args) {
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10.}
1 - 35
syntax for while and do—while loop
3. }
3. //statements
4. } while (condition);
1 - 36
Jump Statements
Jump statements are used to transfer the control of the program to the
◆
specific statements.
⚫ The break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
⚫ However, it breaks only the inner loop in the case of the nested loop.
⚫ The break statement cannot be used independently in the Java program, i.e., it
whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
1 - 37
Example of Jump Statements
1. public class ContinueExample {
2. public static void main(String[] args) {
1.public class BreakExample {
2. public static void main(String[] args) { // T
3. // TODO Auto-generated method stub
ODO Auto-generated method stub
4. for(int i = 0; i<= 2; i++) {
3.for(int i = 0; i<= 10; i++) {
5. for (int j = i; j<=5; j++) { 4.System.out.println(i);
6. if(j == 4) { 5.if(i==6) {
7. continue;
6.break;
7.}
8. }
8.}
9. System.out.println(j);
9.}
10.} } } } 10.}
1 - 38
1.4. Exception Handling
◆ When a program runs into a runtime error, the program terminates abnormally.
⚫ How can you handle the runtime error so that the program can continue to run or terminate
gracefully?
◆ Exception
⚫ Exception is an abnormal condition.
⚫ In Java, an exception is an event that disrupts the normal flow of the program.
◆ Exception Handling
⚫ Is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
⚫ Exception handling is enables a method to throw an exception to its caller. Without this
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
1 - 42
Runtime Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
RuntimeException is caused
Error VirtualMachineError
by programming errors, such
Many more classes as bad casting, accessing an
out-of-bounds array, and
numeric errors.
1 - 43
Types of Java Exceptions
1 - 44
Difference between Checked and Unchecked Exceptions
◆ 1) Checked Exception
◼ The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions.
◆ For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
◆ 2) Unchecked Exception
◼ The classes that inherit the RuntimeException are known as unchecked exceptions.
◆ For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
◼ Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
◆ 3) Error
◼ Error is irrecoverable.
◆ Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
⚫ RuntimeException, Error and their subclasses are known as unchecked exceptions. All other
exceptions are known as checked exceptions, meaning that the compiler forces the programmer to
check and deal with the exceptions.
1 - 45
Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
1 - 46
Java Exception Keywords
◆ Java provides five keywords that are used to handle the exception. The following
table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.
1 - 47
Java Exception Handling Example
◆ //JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
9. }
10.}
1 - 48
Common Scenarios of Java Exceptions
◆ 1) ArithmeticException:- If we divide any number by zero, there occurs an
ArithmeticException.
◼ int a=50/0;//ArithmeticException
◆ 2) NullPointerException:- If we have a null value in any variable, performing any
operation on the variable throws a NullPointerException.
◼ String s=null;
◼ System.out.println(s.length());//NullPointerException
◆ 4) ArrayIndexOutOfBoundsException
⚫ When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.