You are on page 1of 13

Chapter 1

Overview of Java Programming

1.1. Data Types and Variables

In programming, a data type is a classification that specifies which type of value a variable can
hold, what operations can be performed on that variable, and how the data is stored. It defines a
set of values and the allowable operations on those values. Data types are fundamental to
programming languages and play a crucial role in ensuring that data is stored and processed
appropriately.

Primitive Data Types: Primitive data types are the basic building blocks of data manipulation in
programming languages. They are predefined by the language and represent simple values.

 In Java, the primitive data types include:


1. Byte:
 8-bit signed integer
 The `byte` data type in Java is an 8-bit signed integer, meaning it can
represent integer values in the range from -128 to 127 (inclusive).
 Use Case: Used when memory conservation is crucial and the value range
fits within the byte limits.
2. Short:
 16-bit signed integer
 The `short` data type is a 16-bit signed integer, allowing it to represent
values in the range from -32,768 to 32,767.
 Use Case: Suitable for scenarios where a larger range of values is required
compared to `byte`.

3. Int: 32-bit signed integer


 The `int` data type is a 32-bit signed integer, accommodating a wider
range of values from approximately -2 billion to 2 billion.

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 1


 Use Case: Most commonly used integer type due to its balance between
range and memory usage.

4. Long: 64-bit signed integer


 The `long` data type is a 64-bit signed integer, providing an even larger range
from approximately -9 quintillion to 9 quintillion.
 Use Case: Used when a broader range of integer values is necessary,
especially for large calculations or timestamp representations.
5. Float: 32-bit floating-point number
 The `float` data type represents a 32-bit floating-point number, allowing
for decimal values. It is suitable for values with moderate precision.
 Use Case: Appropriate for applications where memory efficiency is
important, and the precision of decimal values is acceptable.
6. Double: 64-bit floating-point number
 The `double` data type is a 64-bit floating-point number, providing higher
precision than `float`. It is the default choice for decimal values.
 Use Case: Widely used when high precision is required, such as in
scientific calculations or financial applications.
7. Char: 16-bit Unicode character
 The `char` data type represents a single 16-bit Unicode character, allowing
the storage of letters, digits, symbols, and special characters.
 Use Case: Specifically used for storing individual characters, like letters or
symbols.
8. Boolean: Represents true or false values
 The `boolean` data type has only two possible values: `true` or `false`. It is
used for logical operations and decision-making.
 Use Case: Fundamental for representing binary logic in conditions and
decision statements.
 These primitive data types provide the basic building blocks for storing different kinds of
data in Java, each tailored to specific needs in terms of range, precision, and memory
efficiency.
Prepared By: MSc. Misgana Belete Wachemo university Java Programming 2
 These primitive data types are directly supported by the language and are not objects.
They are used to store simple values efficiently in memory.

Reference Data Types: Reference data types, also known as non-primitive data types, do not
store the actual data but a reference (memory address) to the location where the data is stored.
They are more complex than primitive data types and are often used to represent objects and
structures. In Java, reference data types include:

 Class Types: Objects created from classes.


 Classes in Java serve as blueprints or templates for creating objects. Objects
are instances of classes, and they encapsulate both data (attributes) and
behavior (methods).

// Example of a class
class Car {
String model;
int year;
// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
// Method
public void startEngine() {
System.out.println("The " + year + " " + model + " is starting the
engine.");
}
}
// Creating an object (instance) of the class

Car myCar = new Car("Toyota Camry", 2022);

myCar.startEngine();

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 3


 Interface Types: Objects created from interfaces.
 Interfaces define a set of abstract methods that implementing classes must
provide. Objects can be created from classes that implement these interfaces.

// Example of an interface
interface Printable {
void print();
}
// Class implementing the interface
class Printer implements Printable {
@Override
public void print() {
System.out.println("Printing a document.");
}
}
// Creating an object of the class implementing the interface
Printable myPrinter = new Printer();
myPrinter.print();
 Array Types: Objects that represent arrays.
 Arrays are objects in Java that represent a collection of elements of the same
data type. They provide a way to store and manipulate multiple values under a
single name.
// Example of an array
int[] numbers = {1, 2, 3, 4, 5};

// Accessing elements of the array


int firstElement = numbers[0];
System.out.println("First element: " + firstElement);
 Enumeration Types: Objects created from enumeration types

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 4


 Enumerations (enums) define a fixed set of named constant values. Objects
can be created from these enumerated types, and each constant represents a
specific value.

// Example of an enumeration

enum Days {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY,


FRIDAY, SATURDAY, SUNDAY

// Creating an object of the enumeration type

Days today = Days.WEDNESDAY;

System.out.println("Today is: " + today);

 In each example, the creation of an object involves using the new keyword to instantiate
a class, implement an interface, create an array, or use an enumerated constant. Objects
are instances of these types and can be manipulated based on the defined structure and
behavior.
 Reference data types allow for more complex data structures and enable the creation of
user-defined types through classes and interfaces. They provide a way to represent and
manipulate data in a more flexible and extensible manner compared to primitive data
types.

Variables: Variables are containers for storing data values. In Java, variables must be declared
with a specific data type before they can be used.

// Example of variable declaration


int age;
// Example of variable initialization
age = 25;
// Combining declaration and initialization
double price = 49.99;

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 5


Declaration

 It is the process of introducing a variable to the compiler, indicating the type


of data it will hold.
 Introducing a variable to the compiler, specifying its data type.
 Syntax (Java): data_type variable_name;
 Example: int age;

Initialization

 It is the assignment of an initial value to a variable at the time of declaration or


later in the program
 Assigning an initial value to the variable.
 Syntax (Java): data_type variable_name = initial_value;
 Example: int age = 25;

Variable Naming Conventions:

Descriptive Names:

 Choose meaningful and descriptive names for variables.


 Use names that clearly describe the purpose or content of the variable.

// Good example

int studentAge;

Camel Case:

 Start variable names with a lowercase letter.


 Capitalize the first letter of each subsequent concatenated word.
 Good example: double averageScore;

Avoid Keywords:

 Do not use reserved keywords for variable names.


 Use full words instead of abbreviations to maintain clarity. Example: String
customerName;
 Use meaningful names, avoiding generic terms like data, value, etc.

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 6


Example: int x, y;

Scope refers to the region of the program where a variable is accessible.

Types of scope:

1. Local Scope: Variable is accessible only within a specific block or method.


2. Instance Scope: Variable is accessible to the entire class.
3. Class Scope (static): Variable is associated with the class rather than instances.

Lifetime is the duration during which a variable exists in the memory.

There are three type of Life time:

1. Local Variables: Exist as long as the block or method is executing.


2. Instance Variables: Exist as long as the object exists.
3. Class Variables (static): Exist as long as the class is loaded in memory.

Type Casting

Type casting is the conversion of a variable from one data type to another.

 Implicit Casting (Widening): Automatically done by the compiler when there is no loss
of data (e.g., int to double).
 Explicit Casting (Narrowing): Requires manual intervention and may result in data loss
(e.g., double to int).

Syntax (Java):

Implicit: double numDouble = 10;

Explicit: int numInt = (int) 10.5;

These concepts are fundamental to understanding how variables are declared, initialized, named,
scoped, and casted in Java programming. Proper usage and understanding of these concepts
contribute to writing clear, efficient, and error-free code.

1.2. Arrays

Definition and Purpose: An array is a data structure that allows you to store a collection of
elements of the same data type under a single name. The purpose of arrays is to efficiently
manage and manipulate a set of related data items.

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 7


Declaration:

 Define the array's type and name.


 Example: int [] numbers;

Initialization:

 Assign values to the array elements.


 Example: int [] numbers = {1, 2, 3, 4, 5};

Accessing Array Elements:

 Elements are accessed using their index (starting from 0).


 Example: int firstElement = numbers [0];

Multi-dimensional Arrays:

 Arrays can have multiple dimensions (2D, 3D, etc.).


 Example: int [][] matrix = {{1, 2}, {3, 4}};

Common Array Operations

 Iterating through Arrays:


 Use loops (for, while) to iterate through array elements.

Example (for loop):

for (int i = 0; i < numbers.length; i++) {

// Access and process each element

System.out.println(numbers[i]);

 Array Length and Bounds:


 Length property provides the number of elements in the array.
 Example: int arrayLength = numbers.length;
 Be cautious of array bounds to prevent IndexOutOfBoundsException.
 Sorting and Searching Arrays:
 Use sorting algorithms (e.g., Arrays.sort()) to arrange elements.
 Example: Arrays.sort(numbers);

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 8


 Searching can be done through loops or specialized methods.

Example (binary search): int index = Arrays.binarySearch(numbers, 3);

1.3. Decision and Repetition statement

Decision statements, also known as conditional statements, allow a program to make decisions
and choose different paths of execution based on certain conditions.

Types of Decision Statements:

 if Statement: Executes a block of code if a condition is true.

Example:
if (condition) {
// Code to execute if the condition is true
}
 else-if Statement: Provides an alternative condition if the preceding 'if' condition is
false.

Example:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
}
 else Statement: Executes if none of the preceding conditions are true.

Example:

if (condition1) {
// Code to execute if condition1 is true
} else {
// Code to execute if none of the conditions are true
}
 Switch Statement: Evaluates an expression against multiple possible case values.

Example:

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 9


switch (variable) {
case value1:
// Code to execute for value1
break;
case value2:
// Code to execute for value2
break;
// ...
default:
// Code to execute if none of the cases match
}
 Conditional (Ternary) Operator: Provides a concise way to express an 'if-else'
statement.

Syntax: variable = (condition) ? expression_if_true : expression_if_false;`

Example: result = (num1 > num2) ? "Greater”: "Smaller";

Repetition Statements (Loops)

Repetition statements, or loops, enable the execution of a block of code repeatedly as long as a
specified condition is true.

Types of Repetition Statements:

 for Loop: Executes a block of code repeatedly for a specified number of times.

Example:

for (int i = 0; i < 5; i++) {


// Code to execute in each iteration
}
 while Loop: Repeats a block of code as long as a given condition is true.

Example:

while (condition) {
// Code to execute as long as the condition is true
}
Prepared By: MSc. Misgana Belete Wachemo university Java Programming 10
 do-while Loop: Similar to 'while' loop, but guarantees at least one execution.

Example:

do {
// Code to execute at least once
} while (condition);
 break and continue Statements:
 Break: Exits the loop prematurely.

Example: break;

 Continue: Skips the rest of the loop's code and proceeds to the next iteration.

Example: continue;

1.4. Exception Handling

1.4.1. Exception Handling Overview

 Exception handling is a mechanism in Java to gracefully manage runtime errors, known


as exceptions. It allows the program to detect and respond to unexpected situations,
preventing abrupt termination.

Types of Exception handling

1. Checked Exceptions

 Checked at compile-time
 Must be handled or declared.
2. Unchecked Exceptions (Runtime Exceptions):
 Not checked at compile-time
 It can be handled.
3. Exception Hierarchy
 All exceptions are subclasses of the `Throwable` class.
 Two main categories: `Error` (critical errors) and
`Exception` (recoverable).

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 11


1.4.2. Syntax of Exception handling

 try-catch Blocks:
 Try: Encloses the code where an exception might occur.
 Catch: Catches and handles the exception.
 Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
 finally Block:
 Executes code regardless of whether an exception occurs or not.
 Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that always executes
}
 Multiple catch Blocks:
 Handles different types of exceptions in separate catch blocks.
 Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType1 e) {
// Code for ExceptionType1
} catch (ExceptionType2 e) {
// Code for ExceptionType2
}

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 12


 Throw and Throws Keywords:
 Throw: Explicitly throws an exception.
Syntax: throw new ExceptionType("Custom message");
 Throws: Declares that a method might throw a particular type of exception.

Syntax:

void methodName() throws ExceptionType {


// Method code
}

Prepared By: MSc. Misgana Belete Wachemo university Java Programming 13

You might also like