Java Programming
Java Programming
Simple
Multithreaded
KEY CONCEPTS OF THE JAVA
PROGRAMMING LANGUAGE
Distributed
Secure
Platform Independent
PRODUCT LIFE CYCLE
(PLC) STAGES
Analysis
Design
PRODUCT LIFE CYCLE
(PLC) STAGES
Development
Testing
PRODUCT LIFE CYCLE
(PLC) STAGES
Implementation
Maintenance
PRODUCT LIFE CYCLE
(PLC) STAGES
End of Life
ANALYZING A PROBLEM
AND DESIGNING A SOLUTION
How do you decide what components are needed for something
you are going to build, such as a house or a piece of furniture?
Lets;
Analyze a problem using object-oriented analysis (OOA)
Design classes from which objects will be created
ANALYZING A PROBLEM
USING OOA: DEPARTMENT
CASE STUDY
A department offers programmes to students through
lecturers.
Identify objects
POSSIBLE OBJECTS IN THE
DEPARTMENT CASE STUDY
DESIGNING CLASSES
Structure of a class
The class declaration
Syntax:
[modifiers] class class_identifier
Attribute variable declarations and initialization (optional)
Methods (optional)
Comments (optional)
DESIGNING CLASSES
1 class Student {
2 String firstname;
3 String surname;
4
5 public static void main (String args[]) {
6
7 Student myStudent;
8 myStudent = new Student();
9
10 //Display Student’s Information
11 myStudent.displayInformation();
12
13
14 }
15 }
16
DESIGNING CLASSES
The main Method
Compiling a Program
Syntax:
javac filename
Example:
javac Student.java
Executing a Programming
Syntax
java classname
Example
java Student
DECLARING, INITIALIZING,
AND USING VARIABLES
A variable refers to something that can change. Variables can
contain one of a set of values..
Examples:
public String matriculationNumber;
public double currentGPA = 0.0;
public int level = 100;
DECLARING, INITIALIZING,
AND USING VARIABLES
Describing Primitive Data Types
Integral types (byte, short, int, and long)
Floating point types (float and double)
Textual type (char)
Logical type (boolean)
Naming a Variable
Rules:
Variable identifiers must start with either an uppercase or
lowercase letter, an underscore (_), or a dollar sign ($).
Variable identifiers cannot contain punctuation, spaces, or
dashes.
Java technology keywords cannot be used.
DECLARING, INITIALIZING,
AND USING VARIABLES
Naming a Variable
Guidelines:
Begin each variable with a lowercase letter; subsequent words
should be capitalized, such as myVariable.
Choose names that are mnemonic and that indicate to the casual
observer the intent of the variable.
DECLARING, INITIALIZING,
AND USING VARIABLES
Assigning a Value to a Variable
Example:
double price = 12.99;
Example (boolean):
boolean isOpen = false;
Constants
Variable (can change):
double salesTax = 6.25;
Constant (cannot change):
final double SALES_TAX = 6.25;
Guideline – Constants should be capitalized with words separated by
an underscore (_).
DECLARING, INITIALIZING,
AND USING VARIABLES
DECLARING, INITIALIZING,
AND USING VARIABLES
DECLARING, INITIALIZING,
AND USING VARIABLES
DECLARING, INITIALIZING,
AND USING VARIABLES
Operator Precedence
Promotion
Type Casting
Syntax:
identifier = (target_type) value
Concatenation
Java, like most programming languages, allows you to use the
+ sign to join (concatenate) two strings.
String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;
USING THE STRING CLASS
Testing Strings for Equality
To test whether two strings are equal, use the equals method. The
expression
s.equals(t)
returns true if the strings s and t are equal, false otherwise. Note
that s and t can be string variables or string constants
Do not use the == operator to test whether two strings are equal!
riables or string constants.
USING THE STRING CLASS
More about Strings
The String class in Java contains more than 50 methods. A surprisingly
large number of them are sufficiently useful so that we can imagine
using them frequently. The following API note summarizes the
ones we found most useful.
DEVELOPING AND USING
METHODS
Creating and Invoking Methods
Most of the code you write for a class is contained with one or
more methods. Methods let you divide the work that your
programme does into separate logical tasks or behaviours. The
basic form of method accepts no arguments and returns nothing.
Syntax:
[modifiers] return_type method_identifier ([arguments]) {
method_code_block
}
You also have used methods that do not require object instantiation such
as the println method, these are called class methods or static methods.
Java allows you to create static variables and methods which do not
require object instantiation. Static variables and methods are declared with
the static keyword.
Syntax:
expression1 && expression2
FLOW CONTROL
Finally, Java supports the ternary ?: operator that is occasionally
useful. The expression
condition ? expression1 : expression2
evaluates to the first expression if the condition is true, to the second
expression otherwise. For example,
int k = x < y ? x : y;
gives the smaller of x and y.
FLOW CONTROL
The if Construct
Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
// program continues here
Example:
1 if (totalUnitsPassed >= 20)
2 {
3 performance = "Satisfactory";
4 level = getNextLevel();
5 }
FLOW CONTROL
The if/else Construct
Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
else {
code_block;
} // end of else construct
// program continues here
FLOW CONTROL
Chaining if/else Constructs
Syntax:
if (boolean_expression) {
code_block;
} // end of if construct
else if (boolean_expression){
code_block;
} // end of else if construct
else {
code_block;
}
// program continues here
FLOW CONTROL
Using the switch Construct
Syntax:
switch (variable) {
case literal_value:
code_block;
[break;]
case another_literal_value:
code_block;
[break;]
[default:]
code_block;
}
USING LOOP
CONSTRUCTS
What are some situations when you would want to continue
performing a certain action, as long as a certain condition existed?
A while loop tests at the top. Therefore, the code in the block may
never be executed.
USING LOOP
CONSTRUCTS
If you want to make sure a block is executed at least once, you will
need to move the test to the bottom. You do that with the
do/while loop. Its syntax looks like this:
Syntax:
do {
code_block;
}
while (boolean_expression);// Semicolon is mandatory.
Syntax:
for (initialize[,initialize]; boolean_expression;
update[,update])
{
code_block;
}
Example:
1 for (int i = 1; i <= 10; i++){
2
3 System.out.println(“Counting ...” + i);
4
5 }
CREATING AND USING
ARRAYS
An array is an orderly arrangement of something, such as an ordered
list. What are some things that people use arrays for in their daily
lives? If a one-dimensional array is a list of items, what is a two-
dimensional array? How do you access items in an array?
Syntax:
type [] array_identifier;
CREATING AND USING
ARRAYS
You declare an array variable by specifying the array type—which is
the element type followed by []—and the array variable name.
For example, here is the declaration of an array a of integers:
int[] a;
However, this statement only declares the variable a. It does not yet
initialize a with an actual array. You use the new operator to create
the array.
Syntax:
array_identifier = new type [length];
CREATING AND USING
ARRAYS
Example:
Syntax:
type [] array_identifier = {comma-separated list of
values or expressions};
Examples:
int [] ages = {19, 42, 92, 33, 46};
CREATING AND USING
ARRAYS
To find the number of elements of an array, use array.length. For
example,
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
Once you create an array, you CANNOT CHANGE its size
CREATING AND USING
ARRAYS
The "for each" Loop
From JDK 5.0, Java introduces a powerful looping construct that
allows you to loop through each element in an array (as well as
other collections of elements) without having to fuss with index
values.
The enhanced for loop
Syntax;
for (variable : collection) {
code_block;
}
Example:
for (int myInt : a)
System.out.println(myInt);
CREATING AND USING
ARRAYS
Declaring a Two-Dimensional Array
Syntax:
type [][] array_identifier;
Example:
int [][] yearlySales;
Instantiating a Two-Dimensional Array
Syntax:
array_identifier = new type [number_of_arrays] [length];
Example:
// Instantiates a two-dimensional array: 5 arrays of 4 elements each
yearlySales = new int[5][4];
CREATING AND USING
ARRAYS
Initializing a Two-Dimensional Array
Example:
yearlySales[0][0] = 1000;
yearlySales[0][1] = 1500;
yearlySales[0][2] = 1800;
yearlySales[1][0] = 1000;
yearlySales[2][0] = 1400;
yearlySales[3][3] = 2000;
CREATING AND USING
ARRAYS
Initializing a Two-Dimensional Array
Example:
yearlySales[0][0] = 1000;
yearlySales[0][1] = 1500;
yearlySales[0][2] = 1800;
yearlySales[1][0] = 1000;
yearlySales[2][0] = 1400;
yearlySales[3][3] = 2000;
IMPLEMENTING
ENCAPSULATION AND
CONSTRUCTORS
What do you think of when you hear the words private
and public?
IMPLEMENTING
ENCAPSULATION AND
CONSTRUCTORS
Using Encapsulation
The public Modifier
Example:
public class Student {
private String matricNumber;
public Student(){
this.matricNumber = “no-number”;
}
}
...
Student student = new Student(“SCN980322200”);
TYPE SAFETY
The Java language is designed to enforce type safety. This means that
programs are prevented from accessing memory in inappropriate
ways. More specifically, every piece of memory is part of some
Java object. Each object has some class. Each class defines both a
set of objects and operations to be performed on the objects of that
class. Type safety means that a program cannot perform an
operation on an object unless that operation is valid for that object.
Linked Lists
Arrays and array lists suffer from a major drawback. Removing an
element from the middle of an array is expensive since all array
elements beyond the removed one must be moved toward the
beginning of the array. The same is true for inserting elements in
the middle.
THE COLLECTIONS
FRAMEWORK
Linked Lists
Another well-known data structure, the linked list, solves this problem.
Whereas an array stores object references in consecutive memory
locations, a linked list stores each object in a separate link. In the Java
programming language, all linked lists are actually doubly linked; that is,
each link also stores a reference to its predecessor.
1 try
2 {
3 code_block;
4 }
5 catch (ExceptionType e)
6 {
7 handler for this type
8 }
CATCHING EXCEPTIONS
If any of the code inside the try block throws an exception of the class
specified in the catch clause, then
The program skips the remainder of the code in the try block;
The program executes the handler code inside the catch clause.
If none of the code inside the try block throws an exception, then the program
skips the catch clause.
JDBC lets you communicate with databases using SQL, which is the
command language for essentially all modern relational databases.
Desktop databases usually have a graphical user interface that lets
users manipulate the data directly, but server-based databases are
accessed purely through SQL. Most desktop databases have a SQL
interface as well, but it often does not support the full SQL
standard.
JAVA DATABASE
CONNECTIVITY
DATABASE CONNECTION URLS
When connecting to a database, you must specify the data source and
you may need to specify additional parameters. For example,
network protocol drivers may need a port, and ODBC drivers may
need various attributes.
Next, place the statement that you want to execute into a string, for example,
stat.executeUpdate(command);
JAVA DATABASE
CONNECTIVITY
When you execute a query, you are interested in the result. The
executeQuery object returns an object of type ResultSet that you
use to walk through the result one row at a time.
The basic loop for analyzing a result set looks like this:
Syntax:
while (rs.next())
{
//look at a row of the result set
}
THREADS
Multithreaded programs extend the idea of multitasking by taking it
one level lower: individual programs will appear to do multiple
tasks at the same time. Each task is usually called a thread which is
short for thread of control. Programs that can run more than one
thread at once are said to be multithreaded.
Port numbers:
Range from 0 to 65535