3.All About JavaScript
3.All About JavaScript
Introduction
Conditionals
Functions
Scope
Arrays
Loops
Iterators
Objects
Assignment Operators
An assignment operator assigns a value to its left operand based on
the value of its right operand. Here are some of them:
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
console.log(number);
// Prints: 120
String Interpolation
String interpolation is the process of evaluating string literals
containing one or more placeholders (expressions, variables, etc).
// String concatenation
'Tommy is ' + age + ' years old.';
// String interpolation
`Tommy is ${age} years old.`;
Variables
Variables are used whenever there’s a need to store a piece of data.
A variable contains data that can be used in the program elsewhere.
Using variables also ensures code re-usability since it can be used to
replace the same value in multiple places.
const currency = '$';
let userIncome = 85000;
Undefined
is a primitive JavaScript value that represents lack of
undefined
defined value. Variables that are declared but not initialized to a
value will have the value undefined.
var a;
console.log(a);
// Prints: undefined
Declaring Variables
To declare a variable in JavaScript, any of these three keywords can
be used along with a variable name:
var age;
let weight;
const numberOfFingers = 20;
Template Literals
Template literals are strings that allow embedded expressions, $
{expression}. While regular strings use single ' or double " quotes,
template literals use backticks instead.
let name = "Codecademy";
console.log(`Hello, ${name}`);
// Prints: Hello, Codecademy
let Keyword
letcreates a local variable in JavaScript & can be re-assigned.
Initialization during the declaration of a let variable is optional.
A let variable will contain undefined if nothing is assigned to it.
let count;
console.log(count); // Prints: undefined
count = 10;
console.log(count); // Prints: 10
const Keyword
A constant variable can be declared using the keyword const. It must
have an assignment. Any attempt of re-assigning a const variable will
result in JavaScript runtime error.
const numberOfColumns = 4;
numberOfColumns = 8;
// TypeError: Assignment to constant variable.
String Concatenation
In JavaScript, multiple strings can be concatenated together using
the + operator. In the example, multiple strings and variables
containing string values have been concatenated. After execution of
the code block, the displayText variable will contain the concatenated
string.
let service = 'credit card';
let month = 'May 30th';
let displayText = 'Your ' + service + ' bill is due on ' + month + '.';
console.log(displayText);
// Prints: Your credit card bill is due on May 30th.
console.log()
The console.log() method is used to log or print messages to the
console. It can also be used to print objects and other info.
console.log('Hi there!');
// Prints: Hi there!
JavaScript
JavaScript is a programming language that powers the dynamic
behavior on most websites. Alongside HTML and CSS, it is a core
technology that makes the web run.
Methods
Methods return information about an object, and are called by
appending an instance with a period ., the method name, and
parentheses.
// Returns a number between 0 and 1
Math.random();
Built-in Objects
Built-in objects contain methods that can be called by appending the
object name with a period ., the method name, and a set of
parentheses.
Math.random();
// ☝️Math is the built-in object
Numbers
Numbers are a primitive data type. They include the set of all
integers and floating point numbers.
let amount = 6;
let price = 4.99;
String .length
console.log('howdy'.length);
// Prints: 5
Data Instances
When a new piece of data is introduced into a JavaScript program,
the program keeps track of it in an instance of that data type. An
instance is an individual case of a data type.
Booleans
Booleans are a primitive data type. They can be either true or false.
let lateToWork = true;
Math.random()
The Math.random() method returns a floating-point, random number in
the range from 0 (inclusive) up to but not including 1.
console.log(Math.random());
// Prints: 0 - 0.9999999999999999
Math.floor()
The Math.floor() function returns the largest integer less than or equal
to the given number.
console.log(Math.floor(5.95));
// Prints: 5
Null
Null is a primitive data type. It represents the intentional absence of
value. In code, it is represented as null.
let x = null;
Strings
Strings are a primitive data type. They are any grouping of
characters (letters, spaces, numbers, or symbols) surrounded by
single quotes ' or double quotes ".
let single = 'Wheres my bandit hat?';
let double = "Wheres my bandit hat?";
Arithmetic Operators
JavaScript supports arithmetic operators for:
+ addition
- subtraction
* multiplication
/ division
% modulo
// Addition
5+5
// Subtraction
10 - 5
// Multiplication
5 * 10
// Division
10 / 5
// Modulo
10 % 5
Multi-line Comments
In JavaScript, multi-line comments are created by surrounding the
lines with /* at the beginning and */ at the end. Comments are good
ways for a variety of reasons like explaining a code block or
indicating some hints, etc.
/*
The below configuration must be
changed before deployment.
*/
console.log("A year has " + weeksInYear + " weeks and " + daysLeftOver + " days");
TOPICS
Introduction
Conditionals
Functions
Scope
Arrays
Loops
Iterators
Objects
Control Flow
Control flow is the order in which statements are executed in a program. The default
control flow is for statements to be read and executed in order from left-to-right, top-
to-bottom in a program file.
Control structures such as conditionals (if statements and the like) alter control flow
by only executing blocks of code if certain conditions are met. These structures
essentially allow a program to make decisions about which code is executed as the
program runs.
Logical Operator ||
The logical OR operator || checks two values and returns a boolean. If one or both
values are truthy, it returns true. If both values are falsy, it returns false.
A B A || B
false false false
A B A || B
false true true
true false true
true true true
true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false
Ternary Operator
The ternary operator allows for a compact syntax in the case of binary (choosing
between two choices) decisions. It accepts a condition followed by a ? operator, and
then two expressions separated by a :. If the condition evaluates to truthy, the first
expression is executed, otherwise, the second expression is executed.
let price = 10.5;
let day = "Monday";
else Statement
An else block can be added to an if block or series of if-else if blocks. The else block
will be executed only if the if condition fails.
const isTaskCompleted = false;
if (isTaskCompleted) {
console.log('Task completed');
} else {
console.log('Task incomplete');
}
switch Statement
The switch statements provide a means of checking an expression against
multiple case clauses. If a case matches, the code inside that clause is executed.
The case clause should finish with a break keyword. If no case matches but
a default clause is included, the code inside default will be executed.
Note: If break is omitted from the block of a case, the switch statement will continue
to check against case values until a break is encountered or the flow is broken.
const food = 'salad';
switch (food) {
case 'oyster':
console.log('The taste of the sea 🦪');
break;
case 'pizza':
console.log('A delicious pie 🍕');
break;
default:
console.log('Enjoy your meal');
}
if Statement
An if statement accepts an expression with a set of parentheses:
If the expression evaluates to a truthy value, then the code within its code body
executes.
If the expression evaluates to a falsy value, its code body will not execute.
Logical Operator !
The logical NOT operator ! can be used to do one of the following:
console.log(oppositeValue);
// Prints: false
Comparison Operators
Comparison operators are used to comparing two values and
return true or false depending on the validity of the comparison:
1>3 // false
3>1 // true
250 >= 250 // true
1 === 1 // true
1 === 2 // false
1 === '1' // false
else if Clause
After an initial if block, else if blocks can each check an additional condition. An
optional else block can be added after the else if block(s) to run by default if none of
the conditionals evaluated to truthy.
const size = 10;
Falsy values include false, 0, empty strings, null undefined, and NaN. All
other values are truthy.
TOPICS
Introduction
Conditionals
Functions
Scope
Arrays
Loops
Iterators
Objects
Functions
Functions are one of the fundamental building blocks in JavaScript.
A function is a reusable set of statements to perform a task or
calculate a value. Functions can be passed one or more values and
can return a value at the end of their execution. In order to use a
function, you must define it somewhere in the scope where you wish
to call it.
Anonymous Functions
Anonymous functions in JavaScript do not have a name property.
They can be defined using the function keyword, or as an arrow
function. See the code example for the difference between a named
function and an anonymous function.
// Named function
function rocketToMars() {
return 'BOOM!';
}
// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}
Function Expressions
Function expressions create functions inside an expression instead
of as a function declaration. They can be anonymous and/or
assigned to a variable.
const dog = function() {
return 'Woof!';
}
Function Parameters
Inputs to functions are known as parameters when a function is
declared or defined. Parameters are used as variables inside the
function body. When the function is called, these parameters will
have the value of whatever is passed in as arguments. It is possible
to define a function without parameters.
// The parameter is name
function sayHello(name) {
return `Hello, ${name}!`;
}
return Keyword
Functions return (pass back) values using
the return keyword. return ends function execution and returns the
specified value to the location where it was called. A common
mistake is to forget the return keyword, in which case the function
will return undefined by default.
// With return
function sum(num1, num2) {
return num1 + num2;
}
Function Declaration
Function declarations are used to create named functions. These
functions can be called using their declared name. Function
declarations are built from:
The function keyword.
The function name.
An optional list of parameters separated by commas enclosed
by a set of parentheses ().
A function body enclosed in a set of curly braces {}.
Calling Functions
Functions can be called, or executed, elsewhere in code using
parentheses following the function name. When a function is called,
the code inside its function body runs. Arguments are values passed
into a function when it is called.
// Defining the function
function sum(num1, num2) {
return num1 + num2;
}
TOPICS
Introduction
Conditionals
Functions
Scope
Arrays
Loops
Iterators
Objects
Scope
Scope is a concept that refers to where values and functions can be
accessed.
Various scopes include:
function myFunction() {
if (isLoggedIn == true) {
const statusMessage = 'User is logged in.';
}
console.log(statusMessage);
Global Variables
JavaScript variables that are declared outside of blocks or functions
can exist in the global scope, which means they are accessible
throughout a program. Variables declared outside of smaller block
or function scopes are accessible inside those smaller scopes.
function printColor() {
console.log(color);
}
Property .length
numbers.length // 4
Index
Array elements are arranged by index values, starting at 0 as the
first element index. Elements can be accessed by their index using
the array name, and the index surrounded by square brackets.
// Accessing an array element
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
console.log(myArray[2]); // 300
Method .push()
Method .pop()
The .pop() method removes the last element from an array and
returns that element.
const ingredients = ['eggs', 'flour', 'chocolate'];
Mutable
JavaScript arrays are mutable, meaning that the values they contain
can be changed.
names.push('Carl');
// ['Alice', 'Bob', 'Carl']
Arrays
Arrays are lists of ordered, stored data. They can hold items that are
of any data type. Arrays are created by using square brackets, with
individual elements separated by commas.
// An array containing numbers
const numberArray = [0, 1, 2, 3];
Reverse Loop
A for loop can iterate “in reverse” by initializing the loop variable to
the starting value, testing for when the variable hits the ending
value, and decrementing (subtracting from) the loop variable at
each iteration.
const items = ['apricot', 'banana', 'cherry'];
// Prints: 2. cherry
// Prints: 1. banana
// Prints: 0. apricot
Do…While Statement
A do...while statement creates a loop that executes a block of code
once, checks if a condition is true, and then repeats the loop as long
as the condition is true. They are used when you want the code to
always execute at least once. The loop ends when the condition
evaluates to false.
x=0
i=0
do {
x = x + i;
console.log(x)
i++;
} while (i < 5);
// Prints: 0 1 3 6 10
For Loop
A for loop declares looping instructions, with three important pieces
of information separated by semicolons ;:
// Output: 0, 1, 2, 3
Break Keyword
Within a loop, the break keyword may be used to exit the loop
immediately, continuing execution after the loop body.
Here, the break keyword is used to exit the loop when i is greater
than 5.
for (let i = 0; i < 99; i += 1) {
if (i > 5) {
break;
}
console.log(i)
}
// Output: 0 1 2 3 4 5
The inner loop will run all its iterations for each iteration of the outer
loop.
for (let outer = 0; outer < 2; outer += 1) {
for (let inner = 0; inner < 3; inner += 1) {
console.log(`${outer}-${inner}`);
}
}
/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/
Loops
A loop is a programming tool that is used to repeat a set of
instructions. Iterate is a generic term that means “to repeat” in the
context of loops. A loop will continue to iterate until a specified
condition, commonly known as a stopping condition, is met.
While Loop
The while loop creates a loop that is executed as long as a specified
condition evaluates to true. The loop will continue to run until the
condition evaluates to false. The condition is specified before the
loop, and usually, some variable is incremented or altered in
the while loop body to determine when the loop should stop.
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
TOPICS
Introduction
Conditionals
Functions
Scope
Arrays
Loops
Iterators
Objects
In the above code example, the .reduce() method will sum up all the
elements of the array. It takes a callback function with two
parameters (accumulator, currentValue) as arguments. On each
iteration, accumulator is the value returned by the last iteration, and
the currentValue is the current element. Optionally, a second argument
can be passed which acts as the initial value of the accumulator.
const arrayOfNumbers = [1, 2, 3, 4];
console.log(sum); // 10
numbers.forEach(number => {
console.log(number);
});
The .filter() Method
The .filter() method executes a callback function on each element in
an array. The callback function for each of the elements must return
either true or false. The returned array is a new array with any
elements for which the callback function returns true.
In the above code example, the array filteredArray will contain all the
elements of randomNumbers but 4.
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {
return n > 5;
});
The original array does not get altered, and the returned array may
contain different elements than the original array.
In the example code above, the .map() method is used to add ' joined
the contest.' string at the end of each element in
the finalParticipants array.
const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
console.log(announcements);
plusFive(3); // 8
// Since f has a function value, it can be invoked.
f(9); // 14
Callback Functions
In JavaScript, a callback function is a function that is passed into
another function as an argument. This function can then be invoked
during the execution of that higher order function (that it is an
argument of).
Higher-Order Functions
In Javascript, functions can be assigned to variables in the same way
that strings or arrays can. They can be passed into other functions
as parameters or returned from them as well.
TOPICS
Input and Output
Serialization
Generics and Collections
Threading
Scanner class
The Scanner class is used to read user input in a Java program. It requires declaration
within a program before a user of the program is prompted to input values.
IOExceptions
IOExceptions refer to any errors that a program may encounter that are related to the
input or output of a Java program.
FileInputStream
In Java, FileInputStream is used to read data from a file into the program.
FileOutputStream
In Java, FileOutputStream is used to output data from a program into a file on your
computer.
System.out
In order to print output using a Java program, a developer can use
the following three commands:
System.out.print(): prints in the same line a when a program is
running
System.out.println(): prints output in
a new line
System.out.printf(): prints formatted
string. It allows for the use of
format specifiers such as “%s” or “%c” that can be used to
insert variable values
TOPICS
Input and Output
Serialization
Generics and Collections
Threading
Serialization
Serialization is the process of converting an object’s state into a stream of bytes.
serialVersionUID
In Java, a class implementing Serializable needs a serialVersionUID to confirm class
compatibility during deserialization.
Serializable Class
A class (or any of its parent classes) must implement the Serialiazable interface (or
any of its children interfaces) in order to be serializable.
Deserialization
Deserialization is the process of converting a stream of bytes, created after
serialization, back into an object.
Benefits of Serialization
Serialization is beneficial when an object needs to be stored or sent over a network.
Generics
In Java, generics allow classes and interface types to be used as parameters to define
classes, interfaces, or methods.
Benefits of Generics
In Java, generics allow for stronger type checking and bug detection at compile time.
Diamond Operators
When using generics in Java, the diamond operator (<>) is used to declare the type
parameter.
super
When using generics in Java, the super keyword is used to define a lower bound type
on a wildcard.
Wildcards
In Java, the wildcard (?) is used to specify an unknown generic type parameter.
extends
When using generics in Java, the extends keyword is used to define an upper bound
type on type parameter or wildcard.
Wrapper Classes
Wrapper classes are provided to allow primitive values to be used with generic code.
Collections
A collection stores many elements within a single object.
Collections Framework
The collections framework provides ready to use collection data structures and
algorithms.
Aggregrate Operations
When using collections in Java, aggregate operations are used to access and modify a
stream of elements.
Collection Interface
The Collection interface is the root interface of the collections framework.
List Interface
The List interface is used to store elements in an ordered collection.
Set Interface
The Set interface is used to store unique elements in a collection.
Map Interface
The Map interface stores elements as key-value pairs.
Type Parameters
Collections are generic, and a type parameter must be specified.
TOPICS
Input and Output
Serialization
Generics and Collections
Threading
Purpose of Threads
Threads are used in Java to improve performance for processes that can be split into
code that can run concurrently.
Java Thread Lifecycle
A Java thread can, throughout its lifecycle, be in New, Running/Active, Blocked,
Waiting, or Terminated/Joined states.
Synchronized in Java
In Java, the synchronized keyword is used to ensure that methods in two different
threads do not access a shared resource at the same time.
Thread
A thread is a part of a program that follows a path of execution independently.
Multiple threads can run at the same time (concurrently).
The various ways to add concurrency and parallelism to your programs can be tricky and
difficult to differentiate. Implementing one may not actually be implementing the other,
and vice versa. Let’s discuss the vital differences between these concepts.
Humans can multitask. We can talk and drive, listen to music and read, watch an animation and
eat, or all of the above at the same time if you play video games.
We, as a race, have proven time and time again that we can in fact multitask. We can focus our
minds and operate on such an efficient level that even complex tasks become autonomous,
allowing us to adopt additional tasks to juggle our ever-evolving mental goals.
Even a task as simple as opening a door involves a complicated series of sub-tasks that happen
simultaneously. For instance, understanding a door is a door, stepping toward the door, knowing
the door can even be opened, finding the doorknob, turning the doorknob, and applying enough
force to open the door in the proper direction.
That’s not even half of it and yet we’re able to perform every listed subtask with a mere thought
and autonomous action. When we consider the fact we can also hold a cup of coffee, maintain a
conversation with someone, plan our next walking path, and avoid obstacles
while simultaneously opening this door is an incredible display of human ability.
By all definitions, humans can and have always been able to “multitask,” right?
Well, technically… no. Every claim made above is actually a misrepresentation and humans
can’t, by any definition, truly “multitask.”
But to explain why this is, we need to talk about concurrent and parallel programming. Or more
specifically, we need to discuss the differences between concurrency and parallelism.
Concurrent Programming
Concurrency is the act of processing more than one task at seemingly the same time on the
same CPU, requiring the ability to switch between tasks. This means the actual processing of
these tasks can’t happen at exactly the same time, only seemingly.
This is what humans do. Humans can’t multitask, we’re just really good at switching tasks so fast
and effortlessly that we appear to be processing more than one task simultaneously. This is
concurrency, but not parallelism.
Parallel Programming
Parallelism is the act of splitting tasks into smaller subtasks and processing those subtasks in
parallel, for instance across multiple CPUs at the exact same time. True parallelism happens
when each thread processing a designated subtask runs on a separate CPU / CPU core / GPU
core.
An important distinction to note as well is the difference between parallel execution and
parallelism.
Parallel execution is the act of processing more than one task simultaneously across more than
one CPU, but with the distinction that the tasks being processed stay on their designated CPU
and never leave it.
This means that a program can perform concurrent parallel execution, but not implement
parallelism.
To do this, multiple CPUs are used and each CPU is processing more than one task, but each
individual task remains and eventually fully processes on the CPU that started it.
Application starts multiple threads which are then executed on multiple CPUs
Application both works on multiple tasks concurrently and also breaks each task down into
subtasks for parallel execution. However, some of the benefits unique to each case may be lost
in this scenario.
Conclusion
Humans can’t multitask. We’ve proven this by discussing the differences between concurrent
and parallel programming, and we’ve seen that we’re just really good at switching tasks very
quickly.
However, applying what we’ve learned about parallelism, we can extrapolate that two humans
can simultaneously work on the same task and operate in parallel. An easy example of this can
be found in any typical group project.
The task, to get the project done, is broken up into subtasks that are assigned to the individuals
comprising the group. This means these subtasks are processed in parallel by separate
individuals, or metaphorical CPUs / threads, simultaneously. And because these subtasks are all
processing the same primary task, this is an example of parallelism. If we wanted to sprinkle in
some concurrency, we can assign some members of this group more than one subtask to switch
between.
This analogy can delve further and further into the realm of parallel and concurrent programming
simply by broadening the scope of the project.
For example, say the group we’ve been talking about is only one group, and other groups exist
that are also working on their own projects and subdividing their projects into subtasks. We can
also say that all projects are acting toward the completion of one large business venture, or in
other words one large task.
This thought exercise only further reinforces the importance of parallel and concurrent
programming and helps differentiate the two conceptually. But, if we’re capable of doing
projects like this…
Back
Next (alt + . )
TOPICS
Parallel and Concurrent Programming
Servlets
Sockets
Java Native Interface (JNI)
Java Database Connectivity (JDBC)
Parallelism
Parallelism is the act of splitting tasks into smaller subtasks and
processing those subtasks in parallel, for instance across multiple
CPUs at the exact same time.
Java Streams
A Java Stream is used to process a collection of objects which can be
pipelined to produce a desired result.
Executor Framework
The Executor framework implements thread pooling through
an Executor interface.
Concurrency
Concurrency is the act of processing more than one task at
seemingly the same time on the same CPU, requiring the ability to
switch between tasks.
Fork-Join Framework
The Fork-Join framework uses ForkJoinPool to distribute a task across
several worker threads and then wait for a result.
Thread Interference
Thread interference can occur when one thread overwrites the
results of another thread in an unpredictable way, which can cause
unexpected results when reading the altered data.
Thread Pools
A thread pool manages a pool of worker threads which connect to a
work queue of Runnable tasks waiting to be executed.
TOPICS
Parallel and Concurrent Programming
Servlets
Sockets
Java Native Interface (JNI)
Java Database Connectivity (JDBC)
Servlet Containers
In Java, the servlet container manages servlets and communicates
with the server on behalf of the servlet.
Servlets
In Java, a servlet is a class that responds to server requests.
Deploying Servlets
Java servlet applications are deployed using Tomcat.
Creating Servlets
Servlets in Java are created by extending
the GenericServlet or HttpServlet classes.
web.xml
When working with Java servlets, the web.xml file is used to register
them and map URL paths to them.
HTTPServlet Overriding
In Java, HttpServlet applications are implemented by overriding
the doGet(), doPost(), doPut(), or doDelete().
TOPICS
Parallel and Concurrent Programming
Servlets
Sockets
Java Native Interface (JNI)
Java Database Connectivity (JDBC)
What is TCP?
Transmission Control Protocol (TCP) is a communication protocol that enables
applications to exchange messages over a network and ensure the successful delivery
of exchanged data packets. Due to its reliability, TCP is the favored protocol for many
types of common applications.
Sockets
A socket is an endpoint that essentially allows us to connect the client and server
using transmission control protocol.
Client-Server Architecture
Client-server architecture is made up of the following:
Creating a ServerSocket
To create a ServerSocket in java, use the following code:
ServerSocket firstServerSocket = new ServerSocket(6868);
DataInputStream
A DataInputStream allows a program to read primitive data from an underlying input
stream, while a DataOutputStream is used to write the primitive data.
Port Numbers
A socket is tied to a specific port number so that data can be sent
between the client and server.
TOPICS
Parallel and Concurrent Programming
Servlets
Sockets
Java Native Interface (JNI)
Java Database Connectivity (JDBC)
JNI Definition
JNI stands for Java Native Interface. It is used to link Java programs and native
languages together so that a Java program may take advantage of non-Java classes and
methods.
JDBC: Review
The Java Database Connectivity (JDBC) is an Oracle-provided library
to connect Java applications to relational databases through
standard methods and interfaces. Some frequently used classes
include:
DriverManager
Connection
Statement
ResultSet
SQLException
Exception Handling
A SQLExeception is thrown by objects that interact with the database
and is used to notify the user of errors.
Connection
The Connection class creates and manages Statement objects.
Statement statement = Connection.createStatement();
ResultSet Structure
A ResultSet object mimics a database table and can be referenced by
row and column indexes. You must be careful with these references
because they are one of the few 1-based indices in the Java
language.
Creating a ResultSet
A ResultSet object is created when an .executeQuery() method is called
on the database. This method comes from the Statement class.
ResultSet results = statement.executeQuery(sql); // This returns a ResultSet Object
Iterating over ResultSet Objects
The .next() method of ResultSet allows a user to iterate over each row
and process data. Remember, when a ResultSet object is returned, the
row-pointer is initially established before the first row.
ResultSet results = statement.executeQuery("SELECT * FROM SOME_TABLE");
while (results.next()) {
// This while loop will iterate over all valid rows of the ResultSet
// Do something here with each row of data
}
Database Connections
Database resources are costly and must be closed to ensure data
leaks do not occur. One method to ensure the connections are
always closed is to put your code in a try-with-resources block that
automatically closes all resources after execution.
try (
Connection connection = DriverManager.getConnection(url);
Statement statement = Connection.createStatement();
ResultSet results = statement.executeQuery(sql);
){
// Do something with 'results' here
} catch (SQLException e) {
System.out.println("There was an error performing this task.");
}
JVM Registration
The DriverManager class registers drivers with the JVM at run time, this
is done by dynamically loading the class with Class.forName().
Class.forName("com.sqlite.JDBC.Driver");
Statements
Statement objects execute SQL statements on the relational database,
this is done by passing the SQL as an argument to the methods
of Statement.
DriverManager
The DriverManager class establishes the connection to the database in
the form of a Connection object.
Connection connection = DriverManager.getConnection(url);