0% found this document useful (0 votes)
0 views46 pages

3.All About JavaScript

Uploaded by

Dharsha .v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views46 pages

3.All About JavaScript

Uploaded by

Dharsha .v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

TOPICS

 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

let number = 100;

// Both statements will add 10


number = number + 10;
number += 10;

console.log(number);
// Prints: 120

String Interpolation
String interpolation is the process of evaluating string literals
containing one or more placeholders (expressions, variables, etc).

It can be performed using template literals: text ${expression} text.


let age = 7;

// 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;

console.log(currency + userIncome + ' is more than the average income.');


// Prints: $85000 is more than the average income.

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

Learn Javascript: Variables


A variable is a container for data that is stored in computer memory.
It is referenced by a descriptive name that a programmer can call to
assign a specific value and retrieve it.
// Examples of variables
let name = "Tammy";
const found = false;
var age = 3;
console.log(name, found, age);
// Prints: Tammy false 3

Declaring Variables
To declare a variable in JavaScript, any of these three keywords can
be used along with a variable name:

 var is used in pre-ES6 versions of JavaScript.


 let is the preferred way to declare a variable when it can be
reassigned.
 const is the preferred way to declare a variable with a constant
value.

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

console.log(`Billy is ${6+8} years old.`);


// Prints: Billy is 14 years old.

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

The .length property of a string returns the number of characters that


make up the string.
let message = 'good nite';
console.log(message.length);
// Prints: 9

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

Single Line Comments


In JavaScript, single-line comments are created with two consecutive
forward slashes //.
// This line will denote a comment

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.
*/

let baseUrl = 'localhost/taxwebapp/country';

Remainder / Modulo Operator


The remainder operator, sometimes called modulo, returns the
number that remains after the right-hand number divides into the
left-hand number as many times as it evenly can.
// calculates # of weeks in a year, rounds down to nearest integer
const weeksInYear = Math.floor(365/7);

// calcuates the number of days left over after 365 is divded by 7


const daysLeftOver = 365 % 7 ;

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";

day === "Monday" ? price -= 1.5 : price += 1.5;

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');
}

Logical Operator &&


The logical AND operator && checks two values and returns a boolean. If both values
are truthy, then it returns true. If one, or both, of the values is falsy, then it
returns false.
true && true; // true
1 > 2 && 2 > 1; // false
true && false; // false
4 === 4 && 3 > 1; // true

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');
}

// Prints: 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.

const isMailSent = true;


if (isMailSent) {
console.log('Mail sent to recipient');
}

Logical Operator !
The logical NOT operator ! can be used to do one of the following:

 Invert a Boolean value.


 Invert the truthiness of non-Boolean values.

let lateToWork = true;


let oppositeValue = !lateToWork;

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:

 === strict equal


 !== strict not equal
 > greater than
 >= greater than or equal
 < less than
 <= less than or equal

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;

if (size > 100) {


console.log('Big');
} else if (size > 20) {
console.log('Medium');
} else if (size > 4) {
console.log('Small');
} else {
console.log('Tiny');
}
// Print: Small

Truthy and Falsy


In JavaScript, values evaluate to true or false when evaluated as
Booleans.

 Values that evaluate to true are known as truthy


 Values that evaluate to false are known as falsy

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

Arrow Functions (ES6)


Arrow function expressions were introduced in ES6. These
expressions are clean and concise. The syntax for an arrow function
expression does not require the function keyword and uses a fat
arrow => to separate the parameter(s) from the body.

There are several variations of arrow functions:

 Arrow functions with a single parameter do not


require () around the parameter list.
 Arrow functions with a single expression can use the concise
function body which returns the result of the expression
without the return keyword.

// Arrow function with two parameters


const sum = (firstParam, secondParam) => {
return firstParam + secondParam;
};
console.log(sum(2,5)); // Prints: 7

// Arrow function with no parameters


const printHello = () => {
console.log('hello');
};
printHello(); // Prints: hello

// Arrow functions with a single parameter


const checkWeight = weight => {
console.log(`Baggage weight : ${weight} kilograms.`);
};
checkWeight(25); // Prints: Baggage weight : 25 kilograms.

// Concise arrow functions


const multiply = (a, b) => a * b;
console.log(multiply(2, 30)); // Prints: 60

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.

The example code provided contains a function that takes in 2


values and returns the sum of those numbers.
// Defining the function:
function sum(num1, num2) {
return num1 + num2;
}

// Calling the function:


sum(3, 6); // 9

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

// Without return, so the function doesn't output the sum


function sum(num1, num2) {
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 {}.

function add(num1, num2) {


return num1 + num2;
}

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

// Calling the function


sum(2, 4); // 6

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:

 Global scope (a value/function in the global scope can be used


anywhere in the entire program)
 File or module scope (the value/function can only be accessed
from within the file)
 Function scope (only visible within the function),
 Code block scope (only visible within a { ... } codeblock)

function myFunction() {

var pizzaName = "Volvo";


// Code here can use pizzaName

// Code here can't use pizzaName

Block Scoped Variables


constand let are block scoped variables, meaning they are only
accessible in their block or nested blocks. In the given code block,
trying to print the statusMessage using the console.log() method will result
in a ReferenceError. It is accessible only inside that if block.
const isLoggedIn = true;

if (isLoggedIn == true) {
const statusMessage = 'User is logged in.';
}

console.log(statusMessage);

// Uncaught ReferenceError: statusMessage is not defined

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.

Note: It is best practice to keep global variables to a minimum.


// Variable declared globally
const color = 'blue';

function printColor() {
console.log(color);
}

printColor(); // Prints: blue


TOPICS
 Introduction
 Conditionals
 Functions
 Scope
 Arrays
 Loops
 Iterators
 Objects

Property .length

The .length property of a JavaScript array indicates the number of


elements the array contains.
const numbers = [1, 2, 3, 4];

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()

The .push() method of JavaScript arrays can be used to add one or


more elements to the end of an array. .push() mutates the original
array and returns the new length of the array.
// Adding a single element:
const cart = ['apple', 'orange'];
cart.push('pear');

// Adding multiple elements:


const numbers = [1, 2];
numbers.push(3, 4, 5);

Method .pop()

The .pop() method removes the last element from an array and
returns that element.
const ingredients = ['eggs', 'flour', 'chocolate'];

const poppedIngredient = ingredients.pop(); // 'chocolate'


console.log(ingredients); // ['eggs', 'flour']

Mutable
JavaScript arrays are mutable, meaning that the values they contain
can be changed.

Even if they are declared using const, the contents can be


manipulated by reassigning internal values or using methods
like .push() and .pop().
const names = ['Alice', 'Bob'];

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];

// An array containing different data types


const mixedArray = [1, 'chicken', false];
TOPICS
 Introduction
 Conditionals
 Functions
 Scope
 Arrays
 Loops
 Iterators
 Objects

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'];

for (let i = items.length - 1; i >= 0; i -= 1) {


console.log(`${i}. ${items[i]}`);
}

// 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 ;:

 The initialization defines where to begin the loop by declaring


(or referencing) the iterator variable
 The stopping condition determines when to stop looping (when
the expression evaluates to false)
 The iteration statement updates the iterator each time the loop
is completed

for (let i = 0; i < 4; i += 1) {


console.log(i);
};

// Output: 0, 1, 2, 3

Looping Through Arrays


An array’s length can be evaluated with the .length property. This is
extremely helpful for looping through arrays, as the .length of the
array can be used as the stopping condition in the loop.
for (let i = 0; i < array.length; i++){
console.log(array[i]);
}

// Output: Every item in the array

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

Nested For Loop


A nested for loop is when a for loop runs inside another for loop.

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

The .reduce() Method


The .reduce() method iterates through an array and returns a single
value.

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];

const sum = arrayOfNumbers.reduce((accumulator, currentValue) => {


return accumulator + currentValue;
});

console.log(sum); // 10

The .forEach() Method


The .forEach() method executes a callback function on each of the
elements in an array in order.

In the above example code, the callback function containing


a console.log() method will be executed 5 times, once for each
element.
const numbers = [28, 77, 45, 99, 27];

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 .map() Method


The .map() method executes a callback function on each element in
an array. It returns a new array made up of the return values from
the callback function.

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'];

// add string after each final participant


const announcements = finalParticipants.map(member => {
return member + ' joined the contest.';
})

console.log(announcements);

Functions Assigned to Variables


In JavaScript, functions are a data type just as strings, numbers, and
arrays are data types. Therefore, functions can be assigned as
values to variables, but are different from all other data types
because they can be invoked.
let plusFive = (number) => {
return number + 5;
};
// f is assigned the value of plusFive
let f = plusFive;

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

Since, in JavaScript, functions are objects, functions can be passed


as arguments.
const isEven = (n) => {
return n % 2 == 0;
}

let printMsg = (evenFunc, num) => {


const isNumEven = evenFunc(num);
console.log(`The number ${num} is an even number: ${isNumEven}.`)
}

// Pass in isEven as the callback function


printMsg(isEven, 4);
// Prints: The number 4 is an even number: True.

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.

A “higher-order function” is a function that accepts functions as


parameters and/or returns a function.

JavaScript Functions: First-Class Objects


JavaScript functions are first-class objects. Therefore:

 They have built-in properties and methods, such as


the name property and the .toString() method.
 Properties and methods can be added to them.
 They can be passed as arguments and returned from other
functions.
 They can be assigned to variables, array elements, and other
objects.

//Assign a function to a variable originalFunc


const originalFunc = (num) => { return num + 2 };

//Re-assign the function to a new variable newFunc


const newFunc = originalFunc;

//Access the function's name property


newFunc.name; //'originalFunc'

//Return the function's body as a string


newFunc.toString(); //'(num) => { return num + 2 }'

//Add our own isMathFunction property to the function


newFunc.isMathFunction = true;

//Pass the function as an argument


const functionNameLength = (func) => { return func.name.length };
functionNameLength(originalFunc); //12
//Return the function
const returnFunc = () => { return newFunc };
returnFunc(); //[Function: originalFunc]

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.

Compiling Java Programs


Java programs must first be compiled into bytes, and only then can they be run using
the terminal or command prompt.

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

Serializable Field Objects


During serialization in Java, associated field objects must be serializable.

Writing Serialized Objects to a File


In Java, a serialized object may be written to a file and read
using FileOutputStream and FileInputStream.

writeObject() and readObject()


In Java, implementing the writeObject() and readObject() will define a customized way
of serializing and deserializing an object.

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.

Static and Transient Fields


In Java, any field not marked as static or transient is serializable.
TOPICS
 Input and Output
 Serialization
 Generics and Collections
 Threading

Universal (Generic) Algorithms


When using generics in Java, universal (generic) algorithms can be created for
different types.

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.

Queue and Deque Interfaces


The Queue and Deque interfaces are used to hold elements in a collection to process in
a specific order.

Map Interface
The Map interface stores elements as key-value pairs.

Iterators and Enhanced For Loops


Iterators and enhanced for loops are used to traverse collections in Java.

Type Parameters
Collections are generic, and a type parameter must be specified.
TOPICS
 Input and Output
 Serialization
 Generics and Collections
 Threading

Extending the Thread class


Threads can be created by extending the Thread class.

Creating Threads Using Lambda Expressions


Threads can be created using lambda expressions.

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.

Thread Communication in Java


Threads can communicate with each other in Java by polling the state of a shared
resource.

Java Thread Lifecycle Methods


A programmer can control Java thread lifecycle states using the following methods:
 .start()
 .sleep()
 .join()
 .isAlive()

Threads Communication Methods In Java


Threads can communicate with each other in Java using
the .wait(), .notify() and .notifyAll() methods.

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

Race Conditions in Java Threads


A race condition occurs when a multi-threaded program produces
unexpected behavior due to the timing or interleaving of the
execution of threads.
ADVANCED
What is Parallel and Concurrent Programming?

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.

An easy-to-remember distinction between concurrency and parallelism looks like this:


“Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of
things at once.”

Or in other words, concurrency is about “structure” and parallelism is about “execution.”

Concurrency and Parallelism Combos:


Concurrency without Parallelism
More than one task is processed at seemingly the same time (concurrently), but in actuality, the
application is switching between making progress on each task until the tasks are done.

There is no true parallel execution in parallel threads or CPUs.

Parallelism without Concurrency


Only one task is worked on at a time, but that task is broken down into subtasks that are
processed in parallel. This only works if each task, and its subtasks, completes before the next
task is split and executed in parallel.

Neither Concurrent nor Parallel


Only one task is worked on at a time, and the task is never broken down into subtasks for parallel
execution.

Concurrent and Parallel


There are two ways to do this:

 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…

Then… humans can, by this particular definition, multitask.

They just have to do it together.


Back (alt + , )

Back

Next (alt + . )

TOPICS
 Parallel and Concurrent Programming
 Servlets
 Sockets
 Java Native Interface (JNI)
 Java Database Connectivity (JDBC)

Java Parallel Streams


Java Parallel Streams divide a running process into multiple streams
that execute in parallel on separate cores, returning a combined
result of all the individual outcomes.

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.

Memory Consistency Errors


Memory consistency errors occur when different threads have
inconsistent views of what should be the same data.

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.

Servlets and CGI


In Java, servlets overcame all the deficiencies that came with
creating Common Gateway Interface (CGI) applications.

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.

Servlet Request and Response


In Java, HttpServlet classes use the HttpServletRequest object to receive
parameters from the client and HttpServletResponse object to provide a
response back.

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:

 Client - A tool (computer or software) used to request data from a server.


 Server - A tool (computer or software) used to respond to client requests.
 Request/Response - Communication model used by computer to communicate
over a network.

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)

Compiling and Running JNI


Compiling and running a program that uses JNI requires a compiler, a JVM, a native
method C generator, native header files, and all the library files that have been
referenced in the program.

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.

Native Libraries and JNI


Native libraries from third-party APIs may be integrated into JNI by simply ensuring
the library files are added to the folders from which this program will be launching,
and by making minor additions to the compilation statement.

Implementing JNI in Java


When implementing JNI on the Java side it is important to declare native methods
using the keyword native. Implementation will be done in the native language in a
different file. To initialize function names you can compile and generate headers
using the Java file in the terminal.

JNI, Java, and C++


JNI lets programmers integrate C++ and Java to create cross-
platform applications. Such an application has the ability to call C++
functions from Java, and to call Java methods from C++.
TOPICS
 Parallel and Concurrent Programming
 Servlets
 Sockets
 Java Native Interface (JNI)
 Java Database Connectivity (JDBC)

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();

Third Party Drivers


Third-party drivers must be registered with the JVM at run time,
JDBC 4.0 now performs this task implicitly as long as driver classes
are provided in the classpath of the program.

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.

 | column1 | column2 | etc… — | — | — | — row1 | r1, c1 | r1, c2


| etc… row2 | r2, c1 | r2, c2 | etc…

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);

You might also like