Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

chapter 1 - Overview of Java Programming

The document provides an overview of Java programming, covering its definition, data types, variables, arrays, and control statements. It explains the structure of Java programs, types of variables, and the concept of arrays, including single and multidimensional arrays. Additionally, it discusses decision-making and control flow statements in Java, illustrating these concepts with examples.

Uploaded by

fikadu.meu.edu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chapter 1 - Overview of Java Programming

The document provides an overview of Java programming, covering its definition, data types, variables, arrays, and control statements. It explains the structure of Java programs, types of variables, and the concept of arrays, including single and multidimensional arrays. Additionally, it discusses decision-making and control flow statements in Java, illustrating these concepts with examples.

Uploaded by

fikadu.meu.edu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

1

CHAPTER 1
OVERVIEW OF JAVA PROGRAMMING

Tomas U.(MSc in IT)


Madda Walabu University

Java Programming ITec3056


Outline
2

 What is Java Programming?


 Data types and variables in Java
 Arrays and Types of Arrays in Java
 Decision and Repetition statement in Java
 Exception Handling in Java
 Exception Handling Methods
What is Java Programming?
3

 Java is a programming language and a platform.


 Java is a high level, robust, object-oriented and secure
programming language.
 Java was developed by Sun Microsystems (which is now the
subsidiary of Oracle) in the year 1995.
 James Gosling is known as the father of Java.
 Before Java, its name was Oak.
 Since Oak was already a registered company, so James
Gosling and his team changed the name from Oak to Java.
 Platform: Any hardware or software environment in which a
program runs, is known as a platform.
 Since Java has a runtime environment (JRE) and API, it is called
a platform.
Data Types and Variables
4

 A variable is a container which holds the value while the Java


program is executed.
 A variable is assigned with a data type.
 Variable is a name of memory location.
 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
5

2
Variable
6

 A variable is the name of a reserved area allocated in memory.


 In other words, it is a name of the memory location.
 It is a combination of "vary + able" which means its value can
be changed.
Java Program Structure
7
Keyword
Access Modifier

Access Modifier
Types of Variables
8

 There are three types of variables in Java:


1) Local Variable
 A variable declared inside the body of
the method is called local variable.
 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.


Types of Variables
9
2) Instance Variable
 A variable declared inside the class but outside the body of the
method, is called an instance variable.
 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/class 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.
Example to understand the types of variables in java
10

1. public class A
2. {
3. static int m=100; //static variable
4. void method()
5. {
6. int n=90; //local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50; //instance variable
11. }
12. } //end of class
Java Variable Example: Add Two Numbers
11

1. public class Addition{


2. public static void main(String[] args){
3. int a=10;
4. int b=20;
5. int c=a+b;
6. System.out.println(c);
7. }
8. } Output:
30
Java Arrays
12

 An array is a collection of similar type of elements which has


contiguous memory location.
 Java array is an object which contains elements of a similar
data type.
 The elements of an array are stored in a contiguous memory
location.
 It is a data structure where we store similar elements.
 We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and
so on.
 Unlike C/C++, we can get the length of the array using the
length member. In C/C++, we need to use the sizeof operator.
Java Arrays
13

 In Java, array is an object of a dynamically generated class.


 We can store primitive values or objects in an array in Java.
 Like C/C++, we can also create single dimensional or
multidimensional arrays in Java.
Advantage
14

 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.

Disadvantage
 Size Limit: We can store only the fixed size of elements in the
array.
 It doesn't grow its size at runtime.
 To solve this problem, collection framework is used in Java
which grows automatically.
Types of Arrays
15

 There are two types of array.


• Single Dimensional Array

• Multidimensional Array

Single Dimensional Array


• Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];
Array Example
16

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
1. class Testarray{
2. public static void main(String args[]){
3. int a[]=new int[5]; //declaration and instantiation
4. a[0]=10; //initialization
Output:
5. a[1]=20; 10
6. a[2]=70; 20
7. a[3]=40; 70
8. a[4]=50; 40
50
9. //traversing array
10. for(int i=0;i<a.length;i++)//length is the property of array
11. System.out.println(a[i]);
12. }}
Declaration, Instantiation and Initialization of Arrays
17

 We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
 Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
1. class Testarray1{
2. public static void main(String args[]){
3. int a[]={33,3,4,5}; //declaration, instantiation and initialization printing array
4. for(int i=0;i<a.length;i++) //length is the property of array
5. System.out.println(a[i]); Output:
6. } 33
3
7. }
4
5
For-each Loop for Java Array
18

 We can also print the Java array using for-each loop.


 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 of the for-each loop is given below:

for(data_type variable: array){


//body of the loop
}
Example for-each loop
19
ArrayIndexOutOfBoundsException
20
 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
2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]); Output
8. }
9. }
10. }
Multidimensional Array in Java
21

 In such case, data is stored in row and column based index


(also known as matrix form).
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)

2. dataType [][]arrayRefVar; (or)

3. dataType arrayRefVar[][]; (or)

4. dataType []arrayRefVar[];
Example to initialize Multidimensional Array in Java
22

1. a[0][0]=1; Example to instantiate Multidimensional Array in Java


2. a[0][1]=2; int[][] a=new int[3][4];//3 row and 4 column
3. a[0][2]=3;
4. a[0][3]=4;
5. a[1][0]=5;
6. a[1][1]=6;
7. a[1][2]=7;
8. a[1][3]=8;
9. a[2][0]=9;
10. a[2][1]=10;
11. a[2][2]=11;
12. a[2][3]=12;
Example of Multidimensional Java Array
23

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{

3. public static void main(String args[]){

4. //declaring and initializing 2D array

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. } Output:
11. System.out.println(); 1 2 3
12. } 2 4 5
13. } 4 4 5
14. }
Java Control Statements | Control Flow in Java
24

 Java compiler executes the code from top to bottom.


 The statements in the code are executed according to the
order in which they appear.
 However, Java provides statements that can be used to control
the flow of Java code.
 Such statements are called control flow statements.
 It is one of the fundamental features of Java, which provides a
smooth flow of program.
Java Control Statements | Control Flow in Java
25

Java provides three types of control flow statements.


1. Decision Making statements

1. if statements
2. switch statement
2. Loop statements

1. do while loop
2. while loop
3. for loop
4. for-each loop
3. Jump statements
1. break statement
2. continue statement
Decision-Making statements:
26

1) If Statement:
 In Java, the "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.
 In Java, there are four types of if-statements.

1. Simple if statement

2. if-else statement

3. if-else-if ladder

4. Nested-if statement
Decision Making statements | If Statement:
27

1) Simple if statement:
 It is the most basic statement among all control flow statements
in Java.
 It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.

Syntax:
1. if(condition) {

2. statement 1; //executes when condition is true

3. }
Example Student.java
28

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
Output:
9. }
x + y is greater than 20
Decision Making statements | If Statement:
29

2) if-else statement
 The if-else statement is an extension to the if-statement, which
uses another block of code, i.e., else block.
 The else block is executed if the condition of the if-block is
evaluated as false.
Syntax:
1. if(condition) {

2. statement 1; //executes when condition is true

3. }

4. else{

5. statement 2; //executes when condition is false

6. }
Example Student.java
30
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. }
8. else {
9. System.out.println("x + y is greater than 20");
10. }
11. } Output:
x + y is greater than 20
12. }
Decision Making statements | If Statement:
31

3) if-else-if ladder:
 The if-else-if statement contains the if-statement followed by multiple
else-if statements.
 We can also define an else statement at the end of the chain.

Syntax:
if(condition 1) {
1. statement 1; //executes when condition 1 is true

2. }

3. else if(condition 2) {

4. statement 2; //executes when condition 2 is true

5. }

6. else {

7. statement 2; //executes when all the conditions are false

8. }
Example Student.java
32
1. public class Student {
2. public static void main(String[] args) {
3. String city = “Robe";
4. if(city == “Goba") {
5. System.out.println(“City is Goba");
6. }else if (city == “Addis Ababa") {
7. System.out.println(“City is Addis Ababa ");
8. }else if(city == "Adama") {
9. System.out.println(“City is Adama");
10. }else {
11. System.out.println(city);
12. } Output:
13. } Robe
14. }
Decision Making statements | If Statement:
33

4. Nested if-statement
 In nested if-statements, the if statement can contain a if or if-
else statement inside another if or else-if statement.
Syntax:
1. if(condition 1) {

2. statement 1; //executes when condition 1 is true


3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. } }
Example Student.java
34

1. public class Student {


2. public static void main(String[] args) {
3. String address = “Addis Ababa, Ethiopia";
4. if(address.endsWith(“Ethiopia")) {
5. if(address.contains(“Robe")) {
6. System.out.println("Your city is Robe");
7. } else if(address.contains(“Goba")) {
8. System.out.println("Your city is Goba");
9. } else {
10. System.out.println(address.split(",")[0]);
11. }
12. }else {
13. System.out.println("You are not living in Ethiopia");
14. }
15. } Output:
16. } Addis Ababa
Decision Making statements | Switch statement
35

Switch Statement:
 In Java, Switch statements are similar to if-else-if statements.

 The switch statement contains multiple blocks of code called


cases and a single case is executed based on the variable
which is being switched.
 The switch statement is easier to use instead of if-else-if
statements.
 It also enhances the readability of the program.
Decision Making statements | Switch statement
36

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.
Decision Making statements | Switch statement
37
Syntax:
switch (expression){
1. case value1:
2. statement1;
3. break;
4. .
5. .
6. .
7. case valueN:
8. statementN;
9. break;
10. default:
11. default statement;
12. }
Example Student.java
38

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println(“Number is 0");
7. break;
8. case 1:
9. System.out.println(“Number is 1");
10. break;
11. default:
12. System.out.println(num); Output:
13. } } } 2
Loop Statements
39

 In programming, sometimes we need to execute the block of


code repeatedly while some condition evaluates to true.
 However, loop statements are used to execute the set of
instructions in a repeated order.
 The execution of the set of instructions depends upon a
particular condition.
 In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop
Loop Statements
40

Java for loop


 In Java, for loop is similar to C and C++.

 It enables us to initialize the loop variable, check the condition,


and increment/decrement in a single line of code.
 We use the for loop only when we exactly know the number of
times, we want to execute the block of code.
Syntax:
1. for(initialization; condition; increment/decrement) {
2. //block of statements
3. }
Example Calculation.java
41

1. public class Calculation {


2. public static void main(String[] args) {

3. // TODO Auto-generated method stub

4. int sum = 0;

5. for(int j = 1; j<=10; j++) {

6. sum = sum + j;
7. }

8. System.out.println("The sum of first 10 natural numbers is " + sum);

9. }

10. } Output:
The sum of first 10 natural numbers is 55
Loop Statements
42

Java for-each loop


 Java provides an enhanced for loop to traverse the data
structures like array or collection.
 In the for-each loop, we don't need to update the loop
variable.
Syntax:
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Example Calculation.java
43

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
Output:
6. for(String name:names) { Printing the content of the array names:

7. System.out.println(name);Java
C
8. }
C++
9. } Python
10. } JavaScript
Loop Statements
44

Java while loop


 The while loop is also used to iterate over the number of
statements multiple times.
 However, if we don't know the number of iterations in advance,
it is recommended to use a while loop.
 Unlike for loop, the initialization and increment/decrement
doesn't take place inside the loop statement in while loop.
 It is also known as the entry-controlled loop since the condition
is checked at the start of the loop.
 If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
Loop Statements
45

Syntax:
while(condition){
1. //looping statements
2. }
Example Calculation .java
46

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");

Output:
6. while(i<=10) {
Printing the list of first 10 even numbers
7. System.out.println(i); 0
8. i = i + 2;
2
4
9. } 6
10. }
8
10
11. }
Loop Statements
47

Java do-while loop


 The do-while loop checks the condition at the end of the loop
after executing the loop statements.
 When the number of iteration is not known and we have to
execute the loop at least once, we can use do-while loop.
 It is also known as the exit-controlled loop since the condition is
not checked in advance.
Syntax:
do
1. {
2. //statements
3. } while (condition);
Example Calculation .java
48

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do { Output:
7. System.out.println(i); Printing the list of first 10 even numbers
8. i = i + 2; 0
2
9. }while(i<=10); 4
10. } 6
11. }
8
10
Jump statements
49

Java break statement


 As the name suggests, 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 can only be written inside the loop or switch
statement.
Example BreakExample.java
50
1. public class BreakExample {
2. public static void main(String[] args) {

3. // TODO Auto-generated method stub

4. for(int i = 0; i<= 10; i++) {

5. System.out.println(i);

6. if(i==6) {
Output:
7. break; 0
8. }
1
2
9. }
3
10. } 4
11. }
5
6
Jump statements
51

Java continue statement


 Unlike break statement, the continue statement doesn't break
the loop, whereas, it skips the specific part of the loop and
jumps to the next iteration of the loop immediately.
Jump statements
Java continue statement Example
52

// Java Program to illustrate the use of continue statement


import java.util.*; // Importing Classes/Files
public class GFG {
// Main driver method Output
public static void main(String args[])
{ // For loop for iteration
for (int i = 0; i <= 15; i++) {
// Check condition for continue
if (i == 10 || i == 12) {
// Using continue statement to skip the execution of loop when i==10 or i==12
continue;
}
// Printing elements to show continue statement
System.out.print(i + " ");
}
}
}
Exception Handling in Java
53

 The Exception Handling in Java is one of the


powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.
Runtime errors:
• ClassNotFoundException,

• IOException,

• SQLException,

• RemoteException, etc.

What is Exception in Java?


 Dictionary Meaning: Exception is an abnormal condition.
 In Java, an exception is an event that disrupts the normal flow
of the program.
 It is an object which is thrown at runtime.
Advantage of Exception Handling
54

 The core advantage of exception handling is to maintain the normal flow


of the application.
 An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:
1. statement 1; o Suppose there are 10 statements in a Java
2. statement 2; program and an exception occurs at statement
5; the rest of the code will not be executed,
3. statement 3; i.e., statements 6 to 10 will not be executed.
4. statement 4; o However, when we perform exception
handling, the rest of the statements will be
5. statement 5;//exception occurs executed.
6. statement 6; o That is why we use exception handling in Java.
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Hierarchy of Java Exception classes
55

 The java.lang.Throwable class is the root class of Java Exception hierarchy


inherited by two subclasses: Exception and Error.
 The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
56

 There are mainly two types of exceptions: checked and


unchecked.
 An error is considered as the unchecked exception.
 However, according to Oracle, there are three types of
exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
57
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,
LinkageError etc.
Java Exception Keywords
58

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.
Java Exception Handling Example
JavaExceptionExample.java
59

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println(“Rest of the code...");
9. }
10. }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Rest of the code...
Example TryCatchExample2.java
60

1. public class TryCatchExample2 {


2. public static void main(String[] args) {
3. try
4. {
5. int data=50/0; //may throw exception
6. }
7. // handling the exception
8. catch(Exception e)
9. { // displaying the custom message
10. System.out.println("Can't divided by zero");
11. }
12. } Output:
} Can't divided by zero
Java Multi-catch block
61

 A try block can be followed by one or more catch blocks.


 Each catch block must contain a different exception handler.
 So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
• At a time only one exception occurs and at a time only one catch
block is executed.
• All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
Flowchart of Multi-catch Block
62
Example MultipleCatchBlock1.java
63

1. public class MultipleCatchBlock1 {


2. public static void main(String[] args) {
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e)
8. {
9. System.out.println("Arithmetic Exception occurs");
10. }
Example MultipleCatchBlock1.java
64

12. catch(ArrayIndexOutOfBoundsException e)
13. {
11. System.out.println("ArrayIndexOutOfBounds Exceptio
n occurs");
12. }
13. catch(Exception e)
14. {
15. System.out.println("Parent Exception occurs");
16. }
17. System.out.println(“Rest of the code");
18. }
19. } Output:
Arithmetic Exception occurs
Rest of the code
Java finally block
65

 Java finally block is a block used to execute important code


such as closing the connection, etc.
 Java finally block is always executed whether an exception is
handled or not.
 Therefore, it contains all the necessary statements that need to
be printed regardless of the exception occurs or not.
 The finally block follows the try-catch block.
Java finally block
66

 Flowchart of finally block


Why use Java finally block?
67

• finally block in Java can be used to put "cleanup" code such as


closing a file, closing connection, etc.
• The important statements to be printed can be placed in the
finally block.
Usage of Java finally
 Case 1: When an exception does not occur

 Case 2: When an exception occur but not handled by the catch block
 Case 3: When an exception occurs and is handled by the catch block
Example TestFinallyBlock.java
68

Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
Example TestFinallyBlock.java
69

12. //executed regardless of exception occurred or not


13. finally {

14. System.out.println("finally block is always executed");

15. }

16. System.out.println("rest of the code...");

17. }

18. }
Output
Java throw Exception
70

 The Java throw keyword is used to throw an exception


explicitly.
 We specify the exception object which is to be thrown.
 The Exception has some message with it that provides the error
description.
 These exceptions may be related to user inputs, server, etc.
 We can throw either checked or unchecked exceptions in Java
by throw keyword.
 It is mainly used to throw a custom exception.
Java throw Exception
71

 We can also define our own set of conditions and throw an


exception explicitly using throw keyword.
 For example, we can throw ArithmeticException if we divide a
number by another number.
 Here, we just need to set the condition and throw exception
using throw keyword.
Syntax:
throw new exception_class("error message");
 Example of throw IOException

throw new IOException("sorry device error");

You might also like