Chapter 1 Introduction
Chapter 1 Introduction
University of Gondar
College of Informatics
1
Aleka T.
2017 E.C
Overview of Java Programming
By AlekaT.
2017 E.C
2
2017 E.C
Chapter 1: Overview of Java Programming
3 2017 E.C
Chapter 1: Introduction
Datatypes and Variables
Arrays
Decision and Repetition statement
Exception Handling
Exception handling overview
Syntax
4 2017 E.C
Datatypes and Variables
Variables are containers for storing data values.
String - stores text, such as "Hello". String values are surrounded by
double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -
123
float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
boolean - stores values with two states: true or false
5 2017 E.C
Data Types
a variable in Java must be a specified data type:
6 2017 E.C
Data types
7 2017 E.C
Primitive Data Types
A primitive data type specifies the size and type of variable
values, and it has no additional methods.
There are eight primitive data types in Java:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing
6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing
15 decimal digits
8
1
2017 E.C boolean 1 bit Stores true or false values
0
char 2 bytes Stores a single character/letter or ASCII values
…
Numbers:
Integer types stores whole numbers, positive or negative
without decimals. Valid types are byte, short, int and long.
Floating point types represents numbers with a fractional part,
containing one or more decimals. float and double.
1
2017 E.C
1
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to
objects.
Primitive types are predefined in Java. Non-primitive types are created
by the programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
A primitive type has always a value, while non-primitive types can be
null.
A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
The size of a primitive type depends on the data type, while non-
primitive types have all the same size.
1
2017 E.C
2
Declaring (Creating) Variables
Java is a statically-typed programming language. It means,
all variables must be declared before its use.
To create a variable, you must specify the type and assign it a
value:
Syntax:
| type variable = value;
Example
String name = "John"; int
myNum = 15;
System.out.println(name);
1 2017 E.C
1
…
Local variables
declared inside the body of the method is called local variable.
Instance variables
declared inside the class but outside the body of the method
its value is instance-specific and is not shared among instances.
Static /class/ variables
create a single copy of the static variable and share it among all the
instances of the class.
1
2017 E.C
2
public class Inst_Static_Var {
int id;
String first_Name; public static void main(String[] args) {
double grade;
static String address; Inst_Static_Var stud1 = new Inst_Static_Var
(10, "Alex",3.8, "Gondar");
public Inst_Static_Var(int id, String fname, Inst_Static_Var stud2 = new Inst_Static_Var
double gr, String add) (12, "Girma",3.5, "Bahirdar");
{ Inst_Static_Var stud3 = new Inst_Static_Var
this.id = id; (14, "Yeshi",4.0, "Addis Ababa");
this.first_Name = fname; Inst_Static_Var stud4 = new Inst_Static_Var
this.grade = gr; (16, "Sellomon",3.0, "Hawassa");
this.address=add;
} stud1.showInfo();
public void showInfo(){ stud2.showInfo();
System.out.println("Id :"+id + "\nFirst Name :"+ stud3.showInfo();
first_Name + "\n Grade :"+grade + "\n stud4.showInfo();
Address :"+address); }
} }
1
2017 E.C
3
…
final Variables
you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the
variable as "final" or "constant", which means unchangeable
and read-only):
final int myNum = 15;
Declare Many Variables
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
1 2017 E.C
4
Java Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
The general rules for constructing names for variables (unique
identifiers) are:
can contain letters, digits, underscores, and dollar signs
must begin with a letter
should start with a lowercase letter and it cannot contain
whitespace
can also begin with $ and _
are case sensitive ("myNum" and "mynum" are different
variables)
Reserved words (like Java keywords, such as int or boolean)
cannot be used as names
1 2017 E.C
5
Type Casting
Type casting is when you assign a value of one primitive data
type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to
a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte
1
int myInt = (int) myDouble;
2017 E.C
12/24/2023
6
3
Chapter 1: Introduction
Datatypes and Variables
Arrays
Decision and Repetition statement
Exception Handling
Exception handling overview
Syntax
1
2017 E.C
4
Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
To declare an array, define the variable type with square
brackets:
String[ ] cars;
int a[]=new int[5];//declaration and instantiation
String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Access the Elements: You access an array element by referring
to the index number.
1 System.out.println(cars[0]);
2017 E.C
5
Multidimensional Arrays
A multidimensional array is an array of arrays.
To create a two-dimensional array, add each array within its
own set of curly braces:
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
To access the elements of the myNumbers array, specify two
indexes: one for the array, and one for the element inside that
array.
This example accesses the third element (2) in the second
1
array (1) of myNumbers: // myNumbers[1][2]
2017 E.C
6
Jagged Arrays
jagged array is an array of arrays where each row of
the array can have a different number of columns.
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
2
2017 E.C
0
Chapter 1: Introduction
Datatypes and Variables
Arrays
Decision and Repetition statement
Exception Handling
Exception handling overview
Syntax
1
2017 E.C
7
Decision and Repetition statement
Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for
different decisions.
1
2017 E.C
8
…
conditional statements:
Use if to specify a block of code to be executed, if a specified
condition is true
Use else to specify a block of code to be executed, if the same
condition is false
Use else if to specify a new condition to test, if the first condition
is false
Use switch to specify many alternative blocks of code to be
executed
1
2017 E.C
9
…
Use the if statement to specify a block of Java code to be executed if a
condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Use the else statement to specify a block of code to be executed if the
condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
2
2017 E.C
4
0
…
Use the else if statement to specify a new condition if the first
condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
2
2017 E.C
1
…
Ternary Operator
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands.
It can be used to replace multiple lines of code with a single
line.
It is often used to replace simple if else statements:
variable = (condition) ? expressionTrue : expressionFalse;
2
2017 E.C
2
Switch Statements
Use the switch statement to select one of many code blocks to be
executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
2
2017 E.C
3
…
int day = 4; case 4:
switch (day) { System.out.println("Thursday");
case 1: break;
System.out.println("Monday"); case 5:
break;
System.out.println("Friday");
break;
case 2:
case 6:
System.out.println("Tuesday");
System.out.println("Saturday");
break;
break;
case 3:
case 7:
System.out.println("Wednesday");
System.out.println("Sunday");
break; break;
}
2
2017 E.C
4
While Loop
Loops can execute a block of code as long as a specified condition
is reached.
Loops are handy because they save time, reduce errors, and they
make code more readable.
while (condition) {
// code block to be executed
}
Ex
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
2
2017 E.C
5
Do/While Loop
The do/while loop is a variant of the while loop.
This loop will execute the code block once, before checking if the condition
is true, then it will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
Ex
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
2
2017 E.C
6
For Loop
When you know exactly how many times you want to loop
through a block of code, use the for loop instead of a while loop:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
EXample
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
2
2017 E.C
7
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop
through elements in an array:
for (type variableName : arrayName) {
// code block to be executed
}
EXample
String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
2
2017 E.C
8
Chapter 1: Introduction
Datatypes and Variables
Arrays
Decision and Repetition statement
Exception Handling
Exception handling overview
Syntax
2
2017 E.C
9
Exception Handling
The technical term for this is: Java will throw an exception
(throw an error).
3
2017 E.C
4
0
try and catch
The try statement allows you to define a block of code to be tested
for errors while it is being executed.
3
2017 E.C
2
…
If an error occurs, we can use try...catch to catch the error and
execute some code to handle it:
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
3
2017 E.C
3
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
public class Main {
public static void main(String[] args) {
try {
int[ ] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Output:
TheSomething went wrong.
The 'try catch' is finished. 'try catch' is finished.
3
2017 E.C
4
…
The throw keyword:
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type.
There are many exception types available in Java:
ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException,
etc:
3
2017 E.C
5
…
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
3
2017 E.C
7
Syntax
Case sensitive
Class Names
Method names
Program File Name
public static void main(String args[])
Java Identifiers
Java Modifiers
Java Variables (local, instance, static)
Java Arrays
Java Enums
Java Keywords
Comments in Java