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

CH 1 Overview of Java Programming

Uploaded by

gadisakarorsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

CH 1 Overview of Java Programming

Uploaded by

gadisakarorsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 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.

◆ All variables have two important attributes:


◼ A type, which is, established when the variable is defined (e.g., integer, float, character)
except in some programming language like python.
◼ A value, which can be changed by assigning a new value to the variable.

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;

◼ int myAge, myWeight; // two int variables


◼ long area, width, length; // three longs

◆ 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. {

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
1-6
Basic Data Types in Java
• Data types specify the different sizes and values
that can be stored in the variable. Two types of
data types in Java are:
• Primitive data types: The primitive data types
include boolean, char, byte, short, int, long, float and
double.
• Non-primitive data types: The non-primitive data
types include Classes, Interfaces, and Arrays.
• In Java language, primitive data types are the building
blocks of data manipulation

1-7
Basic Data Types and their Ranges in Java
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

1-8
Example: A Demonstration of the Use of Variables Java

public class Demo {


public static void main(String[] args) {
int Width = 5, Length;
Length = 10;
int Area = Width * Length;
System.out.println("Width:"+ Width + "\n");
System.out.println("Length: " + Length + "\n");
System.out.println( "Area: " + Area + "\n");
}
}

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

An array of size N is indexed from zero to N-1

This array holds 10 values that are indexed from 0 to 9

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;

⚫ mean = (scores[0] + scores[1])/2;

⚫ System.out.println ("Top = " + scores[5]);

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)

◆ The element type can be a primitive type or an object reference

◆ Therefore, we can create an array of integers, or an array of characters, or an


array of String objects, etc.

◆ In Java, the array itself is an object

◆ 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

◆ Syntax to Declare an Array in Java


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

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 {

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

3. int a[]=new int[5];//declaration and instantiation

4. a[0]=10;//initialization

5. a[1]=20; a[2]=70; a[3]=40; a[4]=50;

6. //traversing array

7. for(int i=0;i<a.length;i++)//length is the property of array

8. System.out.println(a[i]);

9. }}

1 - 15
Declaration, Instantiation and Initialization of Java Array
Example:-

1. //Java Program to illustrate the use of declaration, instantiation


2. //and initialization of Java array in a single line

3. class Testarray1{

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

5. int a[]={33,3,4,5};//declaration, instantiation and initialization

6. //printing array

7. for(int i=0;i<a.length;i++)//length is the property of 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

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{

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

4. int arr[]={33,3,4,5};

5. //printing array using for-each loop

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

Data is stored in row and column based index (also known


as matrix form).
⚫ Syntax to Declare Multidimensional
▪ dataType[][] arrayRefVar; (or)

▪ dataType [][]arrayRefVar; (or)

▪ 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{

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. 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{

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

4. //declaration and initialization of array

5. int arr[]={4,4,5};

6. //getting the class name of Java array

7. Class c=arr.getClass();

8. String name=c.getName();

9. //printing the class name of Java array

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:

◆Decision-making statements decide which statement to execute


and when.
◆Decision-making statements evaluate the Boolean expression and

control the program flow depending upon the result of the


condition provided.
◆There are two types of decision-making statements in Java, i.e.,

◆ 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. }

◆ Syntax if-else statement:-


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

3. }

4. else{

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

6. }

1 - 26
Syntax of Decision-Making statement (2)

Syntax of if-else-if statement:-


⚫ 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) {

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

5. }

6. else{

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

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){

5. case 0: System.out.println("number is 0");

6. break;

7. case 1: System.out.println("number is 1");

8. break;

9. default: System.out.println(num);

10.} } }

1 - 31
Loop Statements

◆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. 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) {

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. } }

1 - 33
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.
◼ The syntax to use the for-each loop is:-
1.for(data_type var : array_name/collection_name) {

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) {

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");

6. for(String name:names) {

7. System.out.println(name);

8. }

9. }

10.}

1 - 35
syntax for while and do—while loop

◆ The syntax of the while loop:-


1. while(condition){
2. //looping statements

3. }

◆ Syntax of the do-while loop


1. do
2. {

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

can only be written inside the loop or switch 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.
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.

⚫ It is an object which is thrown at runtime.

◆ 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

capability, a method must handle the exception or terminate the program.


1 - 39
Hierarchy of Java Exception classes
• The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error.
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes


1 - 40
System Errors
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

System errors are thrown by JVM Many more classes


and represented in the Error LinkageError
class. The Error class describes
internal system errors. Such Error VirtualMachineError
errors rarely occur. If one does,
there is little you can do beyond Many more classes
notifying the user and trying to
terminate the program gracefully.
1 - 41
Exceptions

Exception describes errors


ClassNotFoundException
caused by your program
and external ArithmeticException
circumstances. These IOException

errors can be caught and Exception NullPointerException


handled by your program. RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

1 - 42
Runtime Exceptions
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

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

◆ There are mainly two types of exceptions are:


◼checked and unchecked.
◼An error is considered as the unchecked exception.

◼According to Oracle, there are three types of exceptions namely:


a) Checked Exception
b) Unchecked Exception
c) Error

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

Many more classes


LinkageError

Error VirtualMachineError Unchecked


exception.
Many more classes

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{

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.}

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

◆ 3) NumberFormatException:- If the formatting of any variable or number is mismatched,


it may result into NumberFormatException.
◼ String s="abc";
◼ int i=Integer.parseInt(s);//NumberFormatException

◆ 4) ArrayIndexOutOfBoundsException
⚫ When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.

◼ int a[]=new int[5];


◼ a[10]=50; //ArrayIndexOutOfBoundsException
1 - 49

You might also like