Queue is an ordered list in which insertions are done at one end (back) and deletions are done at other end (front). The first element to be inserted is the first one to be deleted. Hence, it is called First in First out (FIFO) or Last in Last out (LILO) list.
In general, a queue is a line of people or things waiting to be served in sequential order starting at the beginning of the line or sequence.

When an element is inserted in a queue, the concept is called EnQueue, and when an element is removed from the queue, the concept is called DeQueue. DeQueueing an empty queue is called underflow and EnQueuing an element in a full queue is called overflow.
peek() function is oftenly used to return the value of first element without dequeuing it.Queue, as the name suggests is used whenever we need to manage any group of objects in an order in which the first one coming in, also gets out first while the others wait for their turn, like in the following scenarios:
Just like Stack, in case of a Queue too, we know exactly, on which position new element will be added and from where an element will be removed, hence both these operations requires a single step.

Queue can be implemented using an Array, List, or Linked List. LinkedList has the best performance.
@Data
@NoArgsConstructor
public class MyQueue<E> {
private LinkedList<E> list = new LinkedList<>();
public E enqueue(E item) {
list.addFirst(item);
return item;
}
public E dequeue() {
if (list.size() <= 0) {
throw new EmptyStackException();
}
return list.removeLast();
}
public int getSize() {
return list.size();
}
public void print() {
int size = getSize();
int count = 1;
if (count >= size) {
return;
}
E item = list.getFirst();
while (item != null) {
System.out.println(item.toString());
if (count >= size) {
break;
}
item = list.get(count);
count++;
}
}
}
Show connections that your MySQL server has
show status like 'Conn%';
show status like '%onn%';
Show all users of your MySQL server
select * from mysql.user;
select host, user, password from mysql.user;
Describe a table
desc user;October 31, 2019
The this keyword references the object of which the function is a property. In other words, the this references the object that is currently calling the function.
When this is used alone, the owner is the Global object, so this refers to the Global object. In a browser window the Global object is the Window object.
this in global object
/*
* Global this
* Alone, this refers to the global object.
*/
var pageName = "This Keyword";
function showPageName(){
console.log("pageName: " + this.pageName);//This Keyword
}
showPageName();
this in a method
JavaScript “strict mode” does not allow default binding. So, when this is used in a function, in strict mode, this is undefined.
/**
* In a method, this refers to the owner object
*/
let person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {// person is the owner of this function
return this.firstName + " " + this.lastName;
}
};
console.log("fullName: "+person.fullName());//John Doe
this in an arrow function
If this is used in an arrow function, this is referencing outer fields or methods.
/*
* this in arrow funciton
* Arrow functions are special: they don’t have their “own” this.
* If we reference this from such a function, it’s taken from the outer “normal” function.
*/
let user = {
name: "Folau",
sayHi() {
//If we reference this from such a function, it’s taken from the outer “normal” function.
let arrow = () => console.log("arrow name: "+this.name);//arrow name: Folau
arrow();
function sayMyName(){
console.log("my name: "+this.name);//my name:
}
sayMyName();
}
};
user.sayHi();
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A promise is in one of these states:
A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
As the then() and catch() methods return promises, they can be chained. The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
<script>
let successAction = new Promise((resolve, reject) => {
console.log('Initial');
document.getElementById("promisePending").innerHTML = "Starting...";
// do async action here.
setTimeout( function() {
let apiResponse = {};
apiResponse.id = 1;
apiResponse.name = "Folau";
resolve(apiResponse);
document.getElementById("promiseFullFilled").innerHTML = "fullfilled";
}, 3000);
});
successAction.then((reponse) => {
console.log(reponse);
console.log('Do this');
})
.catch((error) => {
// This is skiped because resolve is called above.
console.error('Error');
console.log(error);
}).finally(() => {
console.log('finally!');
});
let failedAction = new Promise((resolve, reject) => {
console.log('Initial');
document.getElementById("promisePending").innerHTML = "Starting...";
// do async action here.
setTimeout( function() {
let apiResponse = {};
apiResponse.id = 1;
apiResponse.name = "Folau";
reject(apiResponse);
document.getElementById("promiseRejected").innerHTML = "rejected";
}, 3000);
});
failedAction.then((reponse) => {
// This is skiped because reject is called above.
console.log(reponse);
console.log('Do this');
})
.catch((error) => {
console.error('Error');
console.log(error);
}).finally(() => {
console.log('finally!');
});
</script>
Promise with API HTTP requests
<script>
const axiosInstance = axios.create({
baseURL: 'http://localhost:8888',
timeout: 1000,
headers: {
"Content-type": "application/json",
"token": "foobar"
}
});
function getUser(){
console.log("getUser");
let headers = {
"Content-Type": "application/json",
"token":"lovemesomecoding-token"
};
let options = {};
options.method = "GET";
options.headers = headers;
let id = 1;
let url = "http://localhost:8888/users/"+id;
let response = axiosInstance(url, options);
response.then(response => {
let data = response.data;
let content = "";
content += "id: "+data.id+"<br>";
content += "firstName: "+data.firstName+"<br>";
content += "lastName: "+data.lastName+"<br>";
content += "email: "+data.email+"<br>";
document.getElementById("getUserContent").innerHTML = content;
}).catch(error => {
console.log("error");
let errorResponse = error.response.data;
console.log(errorResponse);
document.getElementById("errorMsg").innerHTML = errorResponse.message;
});
}
function updateUser(){
console.log("update user");
let headers = {
"Content-Type": "application/json",
"token":"lovemesomecoding"
};
let user = {
firstName: 'Folau',
lastName: 'Kaveinga',
email: 'folaukaveinga@gmail.com',
id: 1
};
let options = {};
options.method = "PUT";
options.body = JSON.stringify(user);
options.headers = headers;
let url = "http://localhost:8888/users";
let response = axiosInstance(url, options);
response.then(response => {
let data = response.data;
let content = "";
content += "id: "+data.id+"<br>";
content += "firstName: "+data.firstName+"<br>";
content += "lastName: "+data.lastName+"<br>";
content += "email: "+data.email+"<br>";
document.getElementById("updateUserContent").innerHTML = content;
document.getElementById("errorMsg").innerHTML = "";
}).catch(error => {
console.log("error");
let errorResponse = error.response.data;
console.log(errorResponse);
document.getElementById("errorMsg").innerHTML = errorResponse.message;
});
}
</script>
Asnyc/await
The async keyword before a function means that function always returns a promise. Other values are wrapped in a resolved promise automatically.
The await keyword makes JavaScript wait until that promise settles and returns its result.
<div class="row">
<div class="col-1">
</div>
<div class="col-4">
Get Average Number
<br>
<button onclick="getAverageNumber()" type="button" class="btn btn-outline-primary">Get It</button>
</div>
<div class="col-7" id="averageNum">
</div>
</div>
<script>
/*
* Async and await
*/
async function calculateAverage(num1, num2, num3){
// This could be a REST API call
let someNumber = await new Promise(resolve => {
setTimeout(() => {
resolve(3);
}, 2000);
});
console.log("num1: "+num1 + ", num2: "+ num2 +", num3: "+ num3 + ", someNumber: "+someNumber);
return (num1 + num2 + num3 + someNumber) / 4;
}
function getAverageNumber(){
calculateAverage(2, 3, 4).then(average => {
console.log("average");
console.log(average);
document.getElementById("averageNum").innerHTML = average;
});
}
</script>
ArrayList is a resizable array or dynamic array implementation in java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object class. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is transient . It implements RandomAccess, Cloneable, java.io.Serializable.
Internally an ArrayList uses an Object[] Array which is an array of objects. All operation like deleting, adding and updating the elements happens in this Object[] array.
ArrayList is one of the most used data structure in Java today.
ArrayList<String> fruits = new ArrayList<>(2);
fruits.add("apple");
fruits.add("banana");
// by adding this, the internal array is doubled it's size
fruits.add("cantalope");
System.out.println(fruits.toString());
Array is a fixed size data structure while ArrayList is not. Even if we specify some initial capacity, we can add more elements.
If we try to add an element using the add() method in the array list, Internally it checks for the capacity to store the new element, If the internal array is full then a new capacity(more than old capacity by 50% at least) is calculated and a new array is created and copied over the old array to it.
The time complexity of the common operations in ArrayList java.
