Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 85

Learning to Program with

By: Michael Ikhane (Abuja)


08034810470,
Michael.ikhane@gmail.com
ABOUT THIS COURSE
Upon completion of this course, the participant should be able to:
Demonstrate knowledge of Java™ technology, the Java
programming language, and the product life cycle
Use various Java programming language constructs to create
several Java technology applications
Use decision and looping constructs and methods to dictate
program flow
Implement intermediate Java technology programming and
object-oriented (OO) concepts in Java technology programs
Develop a small Java programme.
KEY CONCEPTS OF THE JAVA
PROGRAMMING LANGUAGE
Described below are the concepts behind the development of the
Java language.
 Object-oriented

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

 Each programme consists of a set of courses grouped into


levels.

 Each student can only belong to a programme and be at a


particular level until successfully passing all courses.

 Each course is taken by a lecturer.



ANALYZING A PROBLEM
USING OOA: DEPARTMENT
CASE STUDY
 Identify the problem domain

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

 Uses for Variables


 Holding unique data for an object instance
 Assigning the value of one variable to another
 Representing values within a mathematical expression
 Printing the values to the screen
 Holding references to other objects

DECLARING, INITIALIZING,
AND USING VARIABLES
 Variable Declaration and Initialization
Syntax (attribute or instance variables):
 [modifiers] type identifier [= value];
  
Syntax (local variables):
 type identifier;
  
Syntax (local variables):
 type identifier [= value];

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

Example of potential issue:


int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (num1 + num2); // causes compiler error
  
Example of potential solution:
int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (byte)(num1 + num2); // no data loss
CREATING AND USING
OBJECTS
 What does it mean to create an instance of a blueprint for a
house? How do you refer to different houses on the same
street? When a builder builds a house, does the builder build
every component of the house, including the windows, doors,
and cabinets?

 Declaring Object Reference Variables


 Classname identifier;
 Instantiating an Object
 new Classname();
 Initializing Object Reference Variables
 Identifier = new Classname();
CREATING AND USING
OBJECTS
Example:
1 class Student {
2
3 public String firstname;
4 public String surname;
5
6 public static void main (String args[]) {
7
8 Student myStudent;
9 myStudent = new Student();
10 myStudent.displayInformation();
11
12 myStudent.firstname = “John”;
13 myStudent.surname = “Doko”;
14 myStudent.displayInformation();
15
16 }
17 }
18
USING THE STRING CLASS
 Java does not have a built-in string type. Instead, the standard
Java library contains a predefined class called, naturally
enough, String. Each quoted string is an instance of the String
class.
 Creating a String object with the new keyword:
 String myName = new String(“Kalu Zakari”);
  
 Creating a String object without the new keyword:
 String myName = “Kalu Zakari”;

 The length method yields the number of code units


required for a given string. For example:
 int n = myName.length();
USING THE STRING CLASS
Substrings
 You extract a substring from a larger string with the substring
method of the String class. For example,
 String s = myName.substring(0, 3);
 creates a string consisting of the characters "Kal".
  

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

 To test whether two strings are identical except for the


upper/lowercase letter distinction, use the equalsIgnoreCase
method.
 "Hello".equalsIgnoreCase("hello")

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

Invoking a Method From a Different Class


 To invoke a method from a different class, you can use the dot (.)
operator with an object reference variable, just as you do access the
public variables of an object.
DEVELOPING AND USING
METHODS
Invoking a Method in the Same Class
 Calling a method in the same class is easy. Just include the name of the
method and its arguments, if any.

Guidelines for Invoking Methods


 There is no limit to the number of method calls that a calling method can
make.
 The calling method and the worker method can be in the same class or in
different classes.
 The way you invoke the worker method is different, depending on
whether it is in the same class or in a different class from the calling
method.
 You can invoke methods in any order. Methods do not need to be
completed in the order in which they are listed in the class where they are
declared (the class containing the worker methods).
DEVELOPING AND USING
METHODS
Passing Arguments and Returning Values
 Methods can be invoked by the calling method with a list of
arguments (variables of values to be used). Additionally, methods
can return a value to the calling method that can be used in the
calling method.
DEVELOPING AND USING
METHODS
Methods With Arguments and Return Values
 
Declaration:
public int sum(int numberOne, int numberTwo)
 
Returning a Value:
Example:
public int sum(int numberOne, int numberTwo) {
int result= numberOne + numberTwo;
return result;
}
DEVELOPING AND USING
METHODS
Methods With Arguments and Return Values
 
Declaration:
public int sum(int numberOne, int numberTwo)
 
Returning a Value:
Example:
public int sum(int numberOne, int numberTwo) {
int result= numberOne + numberTwo;
return result;
}
DEVELOPING AND USING
METHODS
Advantages of Method Use
 Methods make programs more readable and easier to maintain.
 Methods make development and maintenance quicker.
 Methods are central to reusable software.
 Methods allow separate objects to communicate and to distribute
the work performed by the program.
DEVELOPING AND USING
METHODS
Creating static Methods and Variables
 So far we have learned how to access methods and variables by creating an
object of the class that the method or variable belongs to. Methods and
variables that are unique to an instance are called instance variables and
instance methods.

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

 Declaring static methods:


 static Properties getProperties()
  
 Invoking static methods: Accessing static variables:
 Classname.method(); Classname.variable;
DEVELOPING AND USING
METHODS
Example overloaded methods:
1
2 public class Calculator {
3
4 public int sum(int numberOne, int numberTwo){
5
6 System.out.println(“Method One”);
7
8 return numberOne + numberTwo;
9 }
10
11 public float sum(float numberOne, float numberTwo) {
12
13 System.out.println(“Method Two”);
14
15 return numberOne + numberTwo;
16 }
17
18 public float sum(int numberOne, float numberTwo) {
19
20 System.out.println(“Method Three”);
21
22 return numberOne + numberTwo;
23 }
24 }
25
DEVELOPING AND USING
METHODS
When to declare a static method or variable:
 Performing the operation on an individual object or associating the
variable with a specific object type is not important.
 Accessing the variable or method before instantiating an object is
important.
 The method or variable does not logically belong to an object, but
possibly belongs to a utility class, such as the Math class, included
in the Java API.

Using Method Overloading


 In Java programming language, there can be several methods in a
class that have the same name but different arguments (different
method signatures). Keep in mind that you must define overloaded
methods if the action a method completes is performed on different
types of data or number of data.
BASIC INPUT AND
OUTPUT (I/O)
Basic Input and Output (I/O)
 To make our example programs more interesting, we want to
accept input and properly format the program output. Of course,
modern programs use a GUI for collecting user input. However,
programming such an interface requires more tools and techniques
than we have at our disposal at this time. Because the first order of
business is to become more familiar with the Java programming
language, we make do with the humble console for input and
output for now.

 You saw that it is easy to print output to the "standard output


stream" (that is, the console window) just by calling
System.out.println.
BASIC INPUT AND
OUTPUT (I/O)
To read console input, you first construct a Scanner that is attached to
the "standard input stream" System.in. First, add the line
  
 import java.util.*;

1. Scanner in = new Scanner(System.in);


2. System.out.print("What is your name? ");
3. String name = in.nextLine();

4. String firstName = in.next();

5. System.out.print("How old are you? ");


6. int age = in.nextInt();

7. double score = in.nextDouble();


INHERITANCE
The idea behind inheritance is that you can create new classes that are
built on existing classes. When you inherit from an existing class,
you reuse (or inherit) its methods and fields and you add new
methods and fields to adapt your new class to new situations. This
technique is essential in Java programming.

More abstractly, there is an obvious "is–a" relationship between


Lecturer and Employee. Every lecturer is an employee: this "is–a"
relationship is the hallmark of inheritance.
INHERITANCE
Syntax:
[class_modifier] class class_identifier extends
superclass_identifier
 
Example:
class Lecturer extends Employee
{
   //added methods and fields
}
FLOW CONTROL
When you must make a decision that has several different paths, how
do you ultimately choose one path over all the other paths?

Java, like any programming language, supports both conditional


statements and loops to determine control flow. We start with the
conditional statements and then move on to loops. We end with the
somewhat cumbersome switch statement that you can use when
you have to test for many values of a single expression.
FLOW CONTROL
Relational and boolean Operators
 
FLOW CONTROL
Relational and boolean Operators

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?

Creating while Loops


The while loop executes a statement (which may be a block
statement) while a condition is true.
 
Syntax:
while (boolean_expression) {
code_block;
} // end of while construct
// program continues here
 
USING LOOP
CONSTRUCTS
Example:  
1 int counter = 1;
2 while (counter < 10)
3 {
4 System.out.println(“Counting ...” + counter);
5 counter++;
6 }

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.

Convert the while loop example to do/while


USING LOOP
CONSTRUCTS
Developing a for Loop

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?

An array is a data structure that stores a collection of values of the


same type. You access each individual value through an integer
index. For example, if a is an array of integers, then a[i] is the ith
integer in the 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:

1 int[] a = new int[100];


2
3 for (int i = 0; i < 100; i++)
4 a[i] = i; // fills the array with 0 to 99
 
Declaring, instantiating, and initializing one-dimensional arrays

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
 

public String matricNumber;


...
myStudent.matricNumber = “SCN980323230”;
IMPLEMENTING
ENCAPSULATION AND
CONSTRUCTORS
The private Modifier
 

private String matricNumber;


public void setMatricNumber(String newMatricNumber) {
this.matricNumber = newMatricNumber;
}
public String getMatricNumber() {
return this.matricNumber;
}
...
student.setMatricNumber(“SCN980323230”);
student.getMatricNumber();
IMPLEMENTING
ENCAPSULATION AND
CONSTRUCTORS
Creating Constructors
Syntax:
[modifiers] class ClassName {
[modifiers] ConstructorName([arguments]) {
code_block;
}
}
Example:
public class Student {
private String matricNumber;
public Student(){
this.matricNumber = “no-number”;
}
}
IMPLEMENTING
ENCAPSULATION AND
CONSTRUCTORS
Overloading Creating Constructors

Example:
public class Student {
private String matricNumber;
public Student(){
this.matricNumber = “no-number”;
}

public Student(String newMatricNumber){


this.matricNumber = newMatricNumber;
}

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

Every Java object is stored in some region of the computer's memory.


Java labels every object by putting a class tag next to the object.
One simple way to enforce type safety is to check the class tag of
the object before every operation on the object. This will help
make sure the object's class allows the operation. This approach is
called dynamic type checking.
TYPE SAFETY
Though dynamic type checking works, it is inefficient. The more time
a system spends checking class tags, the more slowly programs
run. To improve performance, Java uses static type checking
whenever it can. Java looks at the program before it is run and
carefully tries to determine which way the tag checking operations
will come out. This is more complicated, but more efficient than
dynamic type checking.
If Java can figure out that a particular tag checking operation will
always succeed, then there is no reason to do it more than once.
The check can safely be removed, speeding up the program.
Similarly, if Java can figure out that a particular tag checking
operation will always fail, then it can generate an error before the
program is even loaded.
TYPE SAFETY AND
ENCAPSULATION
The typing constraints in Java exist to prevent arbitrary access to
memory. This in turn makes it possible for a software module to
encapsulate its state. This encapsulation takes the form of allowing
a software module to declare that some of its methods and
variables may not be accessed by anything outside the code itself.
The more control is placed on access points (and the fewer access
points there are), the better a module can control access to its state.
It is this idea that permeates the design of the Security Manager. The
VM controls access to potentially dangerous operating system calls
by wrapping the calls in an API that invokes a security check
before making the call. Only the VM can make a direct system call.
All other code must call into the VM through explicit entry points
that implement security checks.
THE COLLECTIONS
FRAMEWORK
The Java collections library forms a framework for collection classes.
It defines a number of interfaces and abstract classes for
implementors of collections, and it prescribes certain mechanisms,
such as the iteration protocol.
Rather than getting into more details about all the interfaces, we
thought it would be helpful to first discuss the concrete data
structures that the Java library supplies.

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.

// LinkedList implements List


1 List<String> staff = new LinkedList<String>();
2 staff.add("Amy");
3 staff.add("Bob");
4 staff.add("Carl");
5 Iterator iter = staff.iterator();
6 String first = iter.next(); // visit first element
7 String second = iter.next(); // visit second element
8 iter.remove(); // remove last visited element
EXCEPTIONS AND
EXCEPTION HANDLING
In a perfect world, users would never enter data in the wrong form,
files they choose to open would always exist, and code would
never have bugs. So far, we have mostly presented code as though
we lived in this kind of perfect world. It is now time to turn to the
mechanisms the Java programming language has for dealing with
the real world of bad data and buggy code.

Encountering errors is unpleasant. If a user loses all the work he or she


did during a program session because of a programming mistake or
some external circumstance, that user may forever turn away from
your program. At the very least, you must

 Notify the user of an error;


 Save all work;
 Allow users to gracefully exit the program.
EXCEPTIONS AND
EXCEPTION HANDLING
To handle exceptional situations in your program, you must take into
account the errors and problems that may occur. What sorts of
problems do you need to consider?
○ User input errors.
○ Device errors.
○ Physical limitations.
○ Code errors.
CATCHING EXCEPTIONS
If an exception occurs that is not caught anywhere, the program will
terminate and print a message to the console, giving the type of the
exception and a stack trace. To catch an exception, you set up a
try/catch block. The simplest form of the try block is as follows:

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.

The Finally Clause


When your code throws an exception, it stops processing the remaining code
in your method and exits the method. This is a problem if the method has
acquired some local resource that only it knows about and if that resource
must be cleaned up. Java has a better solution, the finally clause.
Here we show you how to properly dispose of a Graphics object. The
code in the finally clause executes whether or not an exception was
caught.
CATCHING EXCEPTIONS
1 int num1 = 10; int num2 = 20; byte g;
2 try
3 {
4 // code that might throw exceptions
5 g = num1 + num2;
6 }
7 catch (IOException e)
8 {
9 // show error dialog
10 e.printStacktrace();
11 }
12 finally
13 {
14 g = 0;
15 }
JAVA DATABASE
CONNECTIVITY
In 1996, Sun released the first version of the Java Database
Connectivity (JDBC) API. This API lets programmers connect to a
database and then query or update it, using the Structured Query
Language or SQL. (SQL, usually pronounced like "sequel," is an
industry standard for relational database access.)

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.

After registering drivers, you open a database connection with code


that is similar to the following example:

String url = " jdbc:mysql://localhost:3306/database_name";


String username = "dbuser";
String password = "secret";
Connection conn = DriverManager.getConnection(url, username,
password);
JAVA DATABASE
CONNECTIVITY
EXECUTING SQL COMMANDS
To execute a SQL command, you first create a Statement object. To create
statement objects, use the Connection object that you obtained from the
call to DriverManager.getConnection.

Statement stat = conn.createStatement();

Next, place the statement that you want to execute into a string, for example,

String command = "UPDATE Students"


+ " SET GPA = 4.5"
+ " WHERE MatricNumber = ‘SCN980340394'";

Then call the executeUpdate method of the Statement class:

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.

ResultSet rs = stat.executeQuery("SELECT * FROM Books")

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.

So, what is the difference between multiple processes and multiple


threads? The essential difference is that while each process has a
complete set of its own variables, threads share the same data. This
sounds somewhat risky, and indeed it can be. However, shared
variables make communication between threads more efficient and
easier to program than inter-process communication.
THREADS
THREE PARTS OF A THREAD
 Virtual CPU
 Code that the CPU executes
 Data on which the codes works
NETWORKING
PROGRAMMING
Addressing the connection:
 The address or name of remote machine
 Port number to identify purpose

Port numbers:
 Range from 0 to 65535

You might also like