Wolaita Sodo University
School of Informatics
Department of Computer Science
Java Programming (CoSc3053)
Compiled by Dawit Uta. (M. Tech.)
Computer Science Department, WSU
website address: www.davidtechnotips.com
2 Course outline
Chapter one: Overview of Java Programming
Data types and variables
Arrays
Decision and Repetition statement
Exception handling overview and syntax
3 Chapter I
Overview of Java Programming
Java is a high level, general-purpose, robust, class-based, object-oriented
programming language designed for having lesser implementation
dependencies.
It is a computing platform for application development. Java is a, object-
oriented and secure programming language
It is widely used for developing Java applications in laptops, data centers,
game consoles, scientific supercomputers, cell phones, etc.
History of Java Programming Language
4
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling, Canadian computer scientist (born 19 May 1955) is a best
known as the founder and lead designer behind the Java programming language
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
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of
three key Sun software assets: Java, MySQL, and Solaris.
James Gosling developed the Java platform at Sun Microsystems, and the Oracle
Corporation later acquired it.
Java Programming
5
Application of Java programming
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
Java Programming
6
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application : they are also known as desktop applications or window-based
applications.
These are traditional software that we need to install on every machine. Examples of
standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for
creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used
for creating web applications in Java.
Java Programming
7
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an
enterprise application. It has advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
Java Programming
8
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang,
java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.
Java Programming
9
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It
is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services,
EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Java Programming
10
The Java Programming Language is a high-level language. Its Syntax is similar to C and
C++, but it removes many of the complex , confusing features of C and C++.
The Java Programming Language includes the feature of automatic storage management by
using a garbage collector.
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming language in the world
It has a large demand in the current job market
The Java programming language source code is compiled into the bytecode instruction set
which can be run inside the Java Virtual Machine (JVM) process.
Java Programming …
11
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a
Java program.
Java Application
In the Java Language, all of the source code is written in plain text files with the .java
extension. The java source code files are then compiled into .class extension files by the
command javac
A .class file contains bytecode which is a platform independent instruction set. The java
command then runs the application
Java application translation from source code to byte code procedure.
12 Java Programming …
Oracle has two products that implement Java Platform Standard Edition, Java SE
development Kit and Java SE Runtime Environment
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.
JDK (Java Development Kit) is a
software development kit required to
develop applications in Java. When you
download JDK, JRE is also downloaded
with it.
In addition to JRE, JDK also contains a
number of development tools (compilers,
JavaDoc, Java Debugger, etc).
Java Programming …
13 Java Application Example
Step 1: create a sample source code file Test.java
Step 2. Compile the Source code to generate the Class file
javac HelloWorld.java
Step 3. Run the Application
java HelloWorld
Step 4. Print out the result
Hello World!
now let's see the internal details of the hello Java program
14
class this keyword is used to declare a class in Java public this keyword is an access
modifier which represents visibility it means it is visible to all.
static it is a keyword if we declare any method as static it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method the main method is executed by the JVM so it doesn't require
to create an object to invoke the main method so it saves memory
void it is the return type of the method w/c means it doesn't return any value. Main
represents the starting point of the program. string args is used for command line
argument.
System.out.println it is used print statement. At compile time Java file is compiled by
Java compiler and converts the Java code into bytecode at runtime the class file is
loaded into the java virtual machine using the java class loader the bytecode verifier
then checks the code fragments for illegal code that can violate access rights to objects
the byte codes are then interpreted and the instructions are executed at the runtime
that's all for today thank you for watching you
15
Java Programming …
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets.
It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler
(javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in
Java development.
The Java Virtual Machine gives runtime support to the application and can make the
application independent from different hardware systems.
16 Data types and variables
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Java has primitive and non-primitive data types. Primitive data types are a special group of
data types that do not use the keyword new when initialized.
There are eight primitive data types that are used to store data during a program's operation.
17 Data types and variables…
Java creates them as automatic variables that are not references, which are stored in
memory with the name of the variable.
To display Variables
The println() method is often used to display variables. To combine both text and a
variable, use the + character:
Data Type Size Example Data Data Description
boolean 1 bit true, false true, false
1 byte
byte 12, 128 Stores integers from -128 to 127
(8 bits)
18 Data types and variables…
Stores a 16-bit Unicode
char 2 bytes 'A', '5', '#'
character
short 2 bytes 6, -14, 2345 Stores integers from -32,768 to 32,767.
4 Stores integers from:
int 6, -14, 2345
bytes -2,147,483,648 to 2,147,483,647
8 Stores integers from:-9,223,372,036,854,775,808
long 3459111, 2
bytes to 9,223,372,036,854,775,807
4 Stores a positive or negative decimal number
float 3.145, .077
bytes from: 1.4023x10-45 to 3.4028x10+38
8 Stores a positive or negative decimal number
double .0000456, 3.7
bytes from: 4.9406x10-324 to 1.7977x10+308
19 Data types and variables…
Variables are containers for storing data values. Variable is a name of memory location.
In Java, there are different types of variables, for example: 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 3. float-
stores floating point numbers, with decimals, such as 19.99
Declaring Variables and Using Literals
• The keyword new is not used when initializing a variable primitive type.
• Instead, a literal value should be assigned to each variable upon initialization.
• A literal can be any number, text, or other information that represents a value.
• Examples of declaring a variable and assigning it a literal value:
20 Data types and variables…
There are three types of variables in Java:
i. local variable
ii. instance variable
iii. static variable
21 Data types and variables…
i. local variable: is 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.
ii. 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.
iii. 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.
22 Data types and variables…
23 Arrays
Non-primitive data types: The non-primitive data types include Arrays, Classes, and
Interfaces. Arrays are data structures consisting of related data items of the same type.
These items are sometimes referred to as the elements of the array.
All elements must be of the same type BUT there is no restriction on which type this is.
Length of the array is set when the array is declared, so the size is fixed.
arrays can be used to hold a collection of int values; or a collection of char values;
BUT they cannot be used to hold a mixture of int and char values.
Declaring arrays
24
Need to state
the size of the array ;
the type of each individual array element .
The array type and size are then put together with a special new operator that allocates
memory.
For example
Declaring arrays
25
Example 2
The effect on computer memory of declaring an array
Naming the array elements
26
The first element in the temperature array is temperature[0]
The second element is temperature[1] and so on:
Initializing an array
27
This is the only instance in which all the elements of an array can be assigned
explicitly by listing out the elements in a single assignment statement.
Accessing array elements
Array can be used like any other variable of the given type in Java.
The assignment operator can be used to enter a value.
You must specify which element to place the value in.
For example: Allowing the user of the program to enter the value of the first temperature:
Assume that i is some integer variable:
Operators in Java
28
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators Assignment Operators
Relational Operators Bitwise Operators
Other Operators
Logical Operators
Arithmetic operators: are used in mathematical expressions in the same way that they are
used in algebra. These are addition, Subtraction, multiplication, division, modulus,
increment and decrement operators.
Operators in Java
29 The following program is a simple example which demonstrates the arithmetic operators.
Operators in Java
30
output
Operators in Java
31 Relational operators
Java has six relational operators used to test primitive or literal numerical values.
Relational operators are used to evaluate if-else and loop conditions
Logic Operators
Java has three logic operators used to combine
Boolean expressions into complex tests.
Operators in Java
32
Relational operator example: output
Decision and Repetition statement
33
Control structures alter the flow of the program, the sequence of statements that are executed
in a program.
They act as "direction signals" to control the path a program takes.
Two types of control structures in Java:
decision statements
Repeating / iterating statements
Decision statements have one or more conditions to be evaluated or tested by the program,
along with a statement or statements that are to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is determined to be
false.
Types of decisions statements in Java:
if statements, if else statement, if else if, else statement
switch statements
Decision and Repetition statement
34
If Statement
if (expression) {
statement;
}
rest_of_program;
expression must evaluate to a boolean value, either true or false
If expression is true, statement is executed and then rest_of_program
If expression is false, statement is not executed and the program continues
at rest_of_program
Decision and Repetition statement
35 If-Else Statement If-Else Statement Example
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
Again, expression must produce a boolean value
If expression is true, statement1 is executed and then next_statement is
executed.
If expression is false, statement2 is executed and then next_statement is
executed.
Decision and Repetition statement
36 Chained If-Else Statement syntax Chained If-Else Statement Example
if-else chains can be sometimes be rewritten as a “switch” statement. switches are usually
simpler and faster
Decision and Repetition statement
37 switch Statement switch Statement Example
The switch statement enables you to test
several cases generated by a given expression.
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed
The expression must evaluate to a char, byte,
short or int, Character, Byte, Short, Integer,
String, enum but not float, or double or long
The break statement tells the computer to exit the switch statement
38 Decision and Repetition/Itration statement
Iteration is the form of program control that allows us to repeat a section of code.
This form of control is often also referred to as repetition.
The programming structure that is used to control this repetition is often called a loop.
There are three types of loops in Java:
for loop;
while loop;
do…while loop.
The ‘for’ loop
If we wish to repeat a section of code a fixed number of times we would use Java's for
loop.
The for loop is usually used in conjunction with a counter to keep track of how many
times we have been through the loop so far:
The ‘for’ loop
39 for (init_expr; loop_condition; increment_expr) {
statement;
}
The control of the for loop appear in parentheses and is made up of three parts:
1. The first part, the init_expression, sets the initial conditions for the loop and is executed
before the loop starts.
2. Loop executes so long as the loop_condition is true and exits otherwise.
3. The third part of the control information, the increment_expr, is usually used to
increment the loop counter. This is executed at the end of each loop iteration.
Example
output
Decision and Repetition statement
40
while loop: while loop statement in Java programming language repeatedly executes a
target statement as long as a given condition is true.
while Statement syntax Here, statement(s) may be a single statement or a block of
statements.
The condition may be any expression, and true is any non
zero value. When executing, if the boolean_expression result
is true, then the actions inside the loop will be executed. This
will continue as long as the expression result is true.
When the condition becomes false, program control passes
to the line immediately following the loop
Decision and Repetition statement
41 while Statement Example
output
Decision and Repetition statement
42
do...while: A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
do…while Statement syntax Notice that the Boolean expression appears at the end of
the loop, so the statements in the loop execute once before
the Boolean is tested.
If the Boolean expression is true, the control jumps back up
to do statement, and the statements in the loop execute
again.
This process repeats until the Boolean expression is false.
43 Decision and Repetition statement
do…while Statement Example
output
44 Exception handling overview
What is an Exception? is a problem that arises during the execution of a program that disrupts
the program flow and may cause a program to fail or terminates abnormally, which is not
recommended, therefore, these exceptions are to be handled
Some examples are:.
Accessing an out-of-bounds array element
Performing illegal arithmetic
Illegal arguments to methods
Hardware failures
Writing to a read-only file
45
Exception Class Hierarchy
All exceptions are instances of classes that are subclasses of Exception
46 Exception terminologies
When an exception happens we say it was thrown or raised
When an exception is dealt with, we say the exception was handled or caught
Unchecked Exceptions: is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API. Runtime exceptions are numerous and ignored at the time of compilation.
Checked Exceptions: an exception that occurs at the compile time, these are also called as compile
time exceptions. These exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.
Example reading data from a non existing file.
47
Exception handling overview
For example, if you have declared an array of size 2 in your program, and trying to call the 3rd
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class ExceptionExample {
public static void main(String
args[]) {
String[] greek = {"Alpha",
"Beta"};
System.out.println(greek[2]);
}
}
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception handling overview
48
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
What exception class? ArrayIndexOutOfBoundsException
Which array index is out of bounds? 2
What method throws the exception? main
What file contains the method? ExceptionExample.java
What line of the file throws the exception? 4
49 Exception Handling
Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
50 Example
The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which
throws an exception.