Interview Preparation
Practice real interview questions with detailed answers
1226 Questions
Easy
352 questions
PHP
#1.1
Q1:
What does PHP stand for?
Ans:
PHP originally stood for 'Personal Home Page' and now stands for 'PHP: Hypertext Preprocessor', a recursive acronym.
PHP
#1.2
Q2:
What type of language is PHP?
Ans:
PHP is a server-side scripting language mainly used for web development, but it can also be used as a general-purpose programming language.
PHP
#1.3
Q3:
How do you write a basic PHP script?
Ans:
A PHP script starts with the opening tag . Code is written between these tags.
Code Example
<?php
echo 'Hello World';
?>
PHP
#1.4
Q4:
How do you add comments in PHP?
Ans:
Single line comments use // or #, and multi-line comments use /* ... */.
Code Example
// single line
# also single line
/* multi
line */
PHP
#1.5
Q5:
What is the correct file extension for PHP files?
Ans:
PHP files use the .php extension.
PHP
#1.6
Q6:
How do you print output in PHP?
Ans:
You can use echo or print to output data. echo can take multiple parameters while print returns a value of 1 and takes only one argument.
Code Example
echo 'Hello', ' ', 'World';
print('Hello World');
PHP
#1.7
Q7:
What is the difference between echo and print?
Ans:
echo has no return value and can output multiple comma-separated values, while print returns 1 and only accepts a single argument. echo is generally slightly faster.
PHP
#1.8
Q8:
How do you declare a variable in PHP?
Ans:
Variables in PHP start with a dollar sign ($) followed by the variable name, and do not need explicit type declaration.
Code Example
$name = 'John';
$age = 25;
PHP
#1.9
Q9:
Are PHP variable names case sensitive?
Ans:
Yes, PHP variable names are case sensitive, so $name and $Name are treated as different variables. Function names, however, are not case sensitive.
PHP
#1.10
Q10:
What are the rules for naming PHP variables?
Ans:
A variable name must start with a letter or underscore, followed by any number of letters, numbers, or underscores; it cannot start with a number.
PHP
#1.11
Q11:
What is the difference between single and double quoted strings?
Ans:
Double quoted strings parse variables and escape sequences (like \n), while single quoted strings treat content mostly literally without variable interpolation.
Code Example
$name='Tom';
echo "Hi $name"; // Hi Tom
echo 'Hi $name'; // Hi $name
PHP
#1.12
Q12:
How do you concatenate strings in PHP?
Ans:
You use the dot (.) operator to concatenate strings.
Code Example
$full = 'Hello' . ' ' . 'World';
PHP
#1.13
Q13:
What is a constant in PHP and how is it defined?
Ans:
A constant is a name for a value that cannot change during script execution. It is defined using define() or the const keyword.
Code Example
define('SITE_NAME', 'MyApp');
const PI = 3.14;
PHP
#1.14
Q14:
How do you check if a variable is set?
Ans:
The isset() function checks whether a variable is declared and is not null.
Code Example
if (isset($name)) { echo 'set'; }
PHP
#1.15
Q15:
What does the empty() function do?
Ans:
empty() checks if a variable is empty, meaning it is unset, null, false, 0, '0', an empty string, or an empty array.
PHP
#1.16
Q16:
How do you remove a variable in PHP?
Ans:
The unset() function destroys the specified variable, freeing its memory.
Code Example
unset($name);
PHP
#1.17
Q17:
What is the purpose of the die() or exit() function?
Ans:
die() and exit() are equivalent functions that terminate script execution immediately, optionally printing a message first.
PHP
#1.18
Q18:
How do you include another PHP file?
Ans:
You can use include, include_once, require, or require_once to import another PHP file's content into the current script.
Code Example
include 'header.php';
PHP
#1.19
Q19:
How do you get PHP configuration settings?
Ans:
You can use phpinfo() to display all configuration settings, or ini_get('setting_name') to retrieve a specific one.
PHP
#1.20
Q20:
What is the PHP superglobal $_SERVER used for?
Ans:
$_SERVER is an array containing information about headers, paths, and script locations, such as $_SERVER['REQUEST_METHOD'] or $_SERVER['HTTP_HOST'].
PHP
#1.21
Q21:
How do you find the PHP version currently running?
Ans:
You can use the phpversion() function or run 'php -v' from the command line.
Code Example
echo phpversion();
PHP
#1.22
Q22:
What is the use of the ternary operator in PHP?
Ans:
The ternary operator (condition ? value_if_true : value_if_false) is a shorthand for an if-else statement that returns one of two values.
Code Example
$status = ($age >= 18) ? 'Adult' : 'Minor';
PHP
#1.23
Q23:
What are the data types supported by PHP?
Ans:
PHP supports scalar types (int, float, string, bool), compound types (array, object, callable, iterable), and special types (resource, null).
PHP
#1.24
Q24:
How do you check the data type of a variable?
Ans:
You can use gettype() to get the type as a string, or is_int(), is_string(), is_array(), etc. for specific type checks.
Code Example
var_dump(gettype(5)); // 'integer'
PHP
#1.25
Q25:
What is the difference between == and === in PHP?
Ans:
== compares values only after type juggling (loose comparison), while === compares both value and type without conversion (strict comparison).
Code Example
var_dump(0 == 'a'); // false in PHP8, true in PHP7
var_dump(1 === '1'); // false
PHP
#1.26
Q26:
What is the difference between != and !==?
Ans:
!= checks value inequality with type coercion, while !== checks both value and type inequality without coercion.
PHP
#1.27
Q27:
What does var_dump() do?
Ans:
var_dump() displays structured information about a variable including its type and value, useful for debugging.
Code Example
var_dump([1, 'two', 3.0]);
PHP
#1.28
Q28:
What is NULL in PHP?
Ans:
NULL is a special data type representing a variable with no value assigned. A variable is null if it has been set to NULL, unset, or never assigned.
PHP
#1.29
Q29:
What is an associative array?
Ans:
An associative array uses named keys (strings) instead of numeric indexes to access its elements.
Code Example
$user = ['name' => 'Alice', 'age' => 30];
PHP
#1.30
Q30:
What is the difference between indexed and associative arrays?
Ans:
Indexed arrays use sequential numeric keys starting from 0, while associative arrays use custom string or non-sequential keys to identify values.
PHP
#1.31
Q31:
What is a multidimensional array?
Ans:
A multidimensional array is an array containing one or more arrays as its elements, allowing storage of data in rows and columns.
Code Example
$matrix = [[1,2],[3,4]];
PHP
#1.32
Q32:
How do you convert a string to a number in PHP?
Ans:
You can cast it using (int) or (float), or use functions like intval() and floatval().
Code Example
$n = (int) '42'; $f = floatval('3.14');
PHP
#1.33
Q33:
What are the different types of operators in PHP?
Ans:
PHP supports arithmetic, assignment, comparison, logical, string, array, increment/decrement, and bitwise operators.
PHP
#1.34
Q34:
What is the modulus operator used for?
Ans:
The % operator returns the remainder of dividing two numbers.
Code Example
echo 10 % 3; // 1
PHP
#1.35
Q35:
What are PHP's control structures?
Ans:
PHP control structures include if/else, switch, while, do-while, for, foreach, and match (PHP 8+).
PHP
#1.36
Q36:
What is the difference between while and do-while loops?
Ans:
A while loop checks the condition before executing the loop body, while a do-while loop executes the body at least once before checking the condition.
Code Example
do { echo $i; $i++; } while ($i < 5);
PHP
#1.37
Q37:
How does a foreach loop work in PHP?
Ans:
foreach iterates over each element of an array or object, optionally exposing both key and value.
Code Example
foreach ($arr as $key => $value) { echo "$key: $value"; }
PHP
#1.38
Q38:
What is the switch statement used for?
Ans:
switch evaluates an expression once and compares it against multiple case values, executing the matching block; it uses loose comparison by default.
Code Example
switch($day){
case 1: echo 'Mon'; break;
default: echo 'Other';
}
PHP
#1.39
Q39:
How do you break out of a loop early?
Ans:
The break statement immediately exits the current loop or switch block, optionally taking a numeric argument to break out of nested loops.
PHP
#1.40
Q40:
What does the continue statement do?
Ans:
continue skips the rest of the current loop iteration and proceeds to the next iteration.
PHP
#1.41
Q41:
How do you define a function in PHP?
Ans:
Functions are defined using the function keyword followed by a name, parameters in parentheses, and a body in braces.
Code Example
function greet($name) {
return "Hello, $name";
}
PHP
#1.42
Q42:
What are default parameter values in PHP functions?
Ans:
You can assign a default value to a parameter so it becomes optional; if the caller omits it, the default is used.
Code Example
function greet($name = 'Guest') { echo $name; }
PHP
#1.43
Q43:
How do you create an array in PHP?
Ans:
Arrays can be created using the array() construct or the shorter [] syntax.
Code Example
$fruits = array('apple', 'banana');
$fruits2 = ['apple', 'banana'];
PHP
#1.44
Q44:
How do you add an element to the end of an array?
Ans:
You can use $array[] = $value or the array_push() function.
Code Example
$arr[] = 'new item';
array_push($arr, 'new item');
PHP
#1.45
Q45:
How do you remove the last element of an array?
Ans:
array_pop() removes and returns the last element of an array.
Code Example
$last = array_pop($arr);
PHP
#1.46
Q46:
How do you remove the first element of an array?
Ans:
array_shift() removes and returns the first element, reindexing the remaining numeric keys.
Code Example
$first = array_shift($arr);
PHP
#1.47
Q47:
How do you add an element to the beginning of an array?
Ans:
array_unshift() adds one or more elements to the start of the array and reindexes numeric keys.
Code Example
array_unshift($arr, 'first');
PHP
#1.48
Q48:
How do you check if a value exists in an array?
Ans:
in_array() checks whether a value exists among the array's elements, returning true or false.
Code Example
if (in_array('apple', $fruits)) { echo 'found'; }
PHP
#1.49
Q49:
How do you check if a key exists in an array?
Ans:
array_key_exists() or isset() can check for a key's presence, though isset() returns false if the key's value is null.
Code Example
if (array_key_exists('name', $user)) { echo 'yes'; }
PHP
#1.50
Q50:
How do you get the number of elements in an array?
Ans:
count() or sizeof() returns the number of elements in an array.
Code Example
echo count($arr);
PHP
#1.51
Q51:
How do you sort an array in descending order?
Ans:
rsort() sorts a numerically indexed array in descending order, and arsort() does so for associative arrays while preserving keys.
PHP
#1.52
Q52:
How do you extract a portion of an array?
Ans:
array_slice() returns a sequence of elements from an array based on offset and length parameters without modifying the original array.
Code Example
$part = array_slice($arr, 1, 2);
PHP
#1.53
Q53:
How do you get only the keys or only the values of an array?
Ans:
array_keys() returns all the keys, and array_values() returns all the values, both as new indexed arrays.
PHP
#1.54
Q54:
How do you find unique values in an array?
Ans:
array_unique() removes duplicate values from an array, comparing items as strings by default.
Code Example
$unique = array_unique([1,2,2,3]);
PHP
#1.55
Q55:
How do you reverse an array?
Ans:
array_reverse() returns a new array with elements in reverse order, optionally preserving keys with a second parameter.
Code Example
$reversed = array_reverse([1,2,3]);
PHP
#1.56
Q56:
How do you check if a variable is an array?
Ans:
is_array() returns true if the given variable is an array.
PHP
#1.57
Q57:
How do you find the length of a string?
Ans:
strlen() returns the number of bytes in a string.
Code Example
echo strlen('Hello'); // 5
PHP
#1.58
Q58:
How do you convert a string to uppercase or lowercase?
Ans:
strtoupper() converts a string to uppercase and strtolower() converts it to lowercase.
PHP
#1.59
Q59:
How do you find a substring within a string?
Ans:
strpos() returns the position of the first occurrence of a substring, or false if not found.
Code Example
$pos = strpos('Hello World', 'World'); // 6
PHP
#1.60
Q60:
What is the difference between strpos() and stripos()?
Ans:
strpos() is case-sensitive while stripos() performs a case-insensitive search for a substring's position.
PHP
#1.61
Q61:
How do you replace text within a string?
Ans:
str_replace() replaces all occurrences of a search string with a replacement string.
Code Example
echo str_replace('World', 'PHP', 'Hello World');
PHP
#1.62
Q62:
How do you extract part of a string?
Ans:
substr() returns a portion of a string starting at a given position with an optional length.
Code Example
echo substr('Hello World', 0, 5); // 'Hello'
PHP
#1.63
Q63:
How do you split a string into an array?
Ans:
explode() splits a string by a delimiter into an array of substrings.
Code Example
$parts = explode(',', 'a,b,c'); // ['a','b','c']
PHP
#1.64
Q64:
How do you join array elements into a string?
Ans:
implode() (also called join()) combines array elements into a single string using a specified separator.
Code Example
echo implode(', ', ['a','b','c']); // 'a, b, c'
PHP
#1.65
Q65:
How do you trim whitespace from a string?
Ans:
trim() removes whitespace (or other specified characters) from both ends of a string; ltrim() and rtrim() trim only the left or right side.
PHP
#1.66
Q66:
How do you format numbers as strings in PHP?
Ans:
number_format() formats a number with grouped thousands and a specified number of decimal points.
Code Example
echo number_format(1234567.891, 2); // '1,234,567.89'
PHP
#1.67
Q67:
How do you repeat a string multiple times?
Ans:
str_repeat() returns a new string consisting of the input string repeated a specified number of times.
Code Example
echo str_repeat('ab', 3); // 'ababab'
PHP
#1.68
Q68:
How do you reverse a string?
Ans:
strrev() returns the string with its characters reversed.
Code Example
echo strrev('hello'); // 'olleh'
PHP
#1.69
Q69:
What is a class in PHP?
Ans:
A class is a blueprint for creating objects, defining properties (attributes) and methods (functions) that describe the object's behavior.
Code Example
class Car {
public string $model;
function drive() { echo 'Driving'; }
}
PHP
#1.70
Q70:
How do you create an object from a class?
Ans:
You use the 'new' keyword followed by the class name and any constructor arguments.
Code Example
$car = new Car();
PHP
#1.71
Q71:
What is a constructor in PHP?
Ans:
The constructor is a special method named __construct() that runs automatically when a new object is instantiated, typically used to initialize properties.
Code Example
class User {
public function __construct(public string $name) {}
}
PHP
#1.72
Q72:
What is inheritance in PHP OOP?
Ans:
Inheritance allows a class (child) to inherit properties and methods from another class (parent) using the extends keyword.
Code Example
class Animal { function eat(){} }
class Dog extends Animal {}
PHP
#1.73
Q73:
What is the difference between public, protected, and private visibility?
Ans:
public members are accessible from anywhere, protected members are accessible within the class and its subclasses, and private members are accessible only within the defining class.
PHP
#1.74
Q74:
What are class constants in PHP?
Ans:
Class constants are defined using the const keyword inside a class and hold values that cannot be changed, accessed via ClassName::CONSTANT.
Code Example
class Circle { const PI = 3.14159; }
PHP
#1.75
Q75:
What is encapsulation in OOP?
Ans:
Encapsulation is the bundling of data and methods within a class while restricting direct access to some components using visibility modifiers like private and protected.
PHP
#1.76
Q76:
What is the instanceof operator used for?
Ans:
instanceof checks whether an object is an instance of a specified class, interface, or subclass.
Code Example
if ($car instanceof Vehicle) { echo 'yes'; }
PHP
#1.77
Q77:
How do you handle exceptions in PHP?
Ans:
You wrap risky code in a try block, catch specific exception types in one or more catch blocks, and optionally use a finally block for cleanup code that always runs.
Code Example
try {
$result = 10 / $divisor;
} catch (DivisionByZeroError $e) {
echo $e->getMessage();
} finally {
echo 'Done';
}
PHP
#1.78
Q78:
How do you open a file in PHP?
Ans:
fopen() opens a file or URL and returns a file handle resource, with a mode parameter like 'r' for read or 'w' for write.
Code Example
$handle = fopen('data.txt', 'r');
PHP
#1.79
Q79:
How do you read the entire contents of a file?
Ans:
file_get_contents() reads an entire file into a string in one call, which is simpler than manually looping with fopen/fread.
Code Example
$content = file_get_contents('data.txt');
PHP
#1.80
Q80:
How do you write data to a file?
Ans:
file_put_contents() writes a string to a file, creating the file if it doesn't exist, and can append using the FILE_APPEND flag.
Code Example
file_put_contents('log.txt', 'Hello', FILE_APPEND);
PHP
#1.81
Q81:
How do you check if a file exists?
Ans:
file_exists() returns true if the specified file or directory exists.
Code Example
if (file_exists('config.php')) { ... }
PHP
#1.82
Q82:
How do you delete a file in PHP?
Ans:
unlink() deletes the specified file from the filesystem.
Code Example
unlink('old_file.txt');
PHP
#1.83
Q83:
What are PHP superglobals?
Ans:
Superglobals are built-in variables always accessible in all scopes, including $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_REQUEST, $_ENV, and $GLOBALS.
PHP
#1.84
Q84:
What is the difference between $_GET and $_POST?
Ans:
$_GET retrieves data sent via URL query parameters and is visible in the URL with limited size, while $_POST retrieves data sent in the HTTP request body, typically used for form submissions and larger or sensitive data.
PHP
#1.85
Q85:
How do you redirect to another page in PHP?
Ans:
You send a Location header before any output using the header() function, followed by exit() to stop further script execution.
Code Example
header('Location: login.php');
exit();
PHP
#1.86
Q86:
How do you start a session in PHP?
Ans:
session_start() must be called before any output to initiate or resume a session, enabling use of the $_SESSION superglobal.
Code Example
session_start();
$_SESSION['user_id'] = 5;
PHP
#1.87
Q87:
How do you destroy a session?
Ans:
session_destroy() removes all session data on the server, often paired with unset($_SESSION) and clearing the session cookie.
Code Example
session_start();
session_unset();
session_destroy();
PHP
#1.88
Q88:
How do you set a cookie in PHP?
Ans:
setcookie() sends a cookie to the client's browser, accepting parameters for name, value, expiration, path, domain, and security flags.
Code Example
setcookie('user', 'John', time() + 3600);
PHP
#1.89
Q89:
How do you read a cookie value?
Ans:
You access it through the $_COOKIE superglobal array using the cookie's name as the key.
Code Example
echo $_COOKIE['user'] ?? 'Guest';
PHP
#1.90
Q90:
How do you connect to a MySQL database using MySQLi?
Ans:
You create a new mysqli object with hostname, username, password, and database name parameters.
Code Example
$conn = new mysqli('localhost', 'user', 'pass', 'mydb');
if ($conn->connect_error) { die($conn->connect_error); }
PHP
#1.91
Q91:
How do you connect to a database using PDO?
Ans:
You instantiate a new PDO object with a DSN string, username, and password, typically wrapped in a try-catch to handle connection errors.
Code Example
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
} catch (PDOException $e) {
echo $e->getMessage();
}
PHP
#1.92
Q92:
How do you fetch results from a PDO query?
Ans:
You call fetch() to get one row at a time, or fetchAll() to retrieve all rows at once, typically specifying a fetch mode like PDO::FETCH_ASSOC.
Code Example
$stmt = $pdo->query('SELECT * FROM users');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
PHP
#1.93
Q93:
How do you close a database connection in PHP?
Ans:
You typically set the connection variable to null (for PDO) or call close() on a MySQLi connection object, though PHP closes connections automatically at script end.
PHP
#1.94
Q94:
How do you check if a database query failed in MySQLi?
Ans:
You check the mysqli object's error property or use mysqli_error() after running the query to retrieve the error message.
PHP
#1.95
Q95:
What is the purpose of htmlspecialchars()?
Ans:
htmlspecialchars() converts special characters like <, >, and & into HTML entities, preventing browsers from interpreting user input as executable HTML or script tags.
PHP
#1.96
Q96:
What does the 'i' modifier do in a PHP regex pattern?
Ans:
The 'i' modifier makes the pattern match case-insensitively.
Code Example
preg_match('/hello/i', 'HELLO World'); // matches
PHP
#1.97
Q97:
How do you get the current date and time in PHP?
Ans:
The date() function formats the current timestamp according to a format string, and time() returns the current Unix timestamp.
Code Example
echo date('Y-m-d H:i:s');
PHP
#1.98
Q98:
What is strtotime() used for?
Ans:
strtotime() parses an English textual date/time description into a Unix timestamp.
Code Example
echo date('Y-m-d', strtotime('next Friday'));
PHP
#1.99
Q99:
How do you format a timestamp into a readable date string?
Ans:
The date() function accepts a Unix timestamp and a format string of placeholder characters like Y, m, d, H, i, s to produce a formatted string.
Code Example
echo date('l, F j, Y', time());
PHP
#1.100
Q100:
What is a Unix timestamp?
Ans:
A Unix timestamp is the number of seconds elapsed since January 1, 1970 (the Unix epoch), used internally by PHP to represent points in time.
PHP
#1.101
Q101:
What is Composer in PHP?
Ans:
Composer is PHP's dependency manager, allowing developers to declare, install, and autoload libraries their project depends on via a composer.json file.
PHP
#1.102
Q102:
What is the composer.json file used for?
Ans:
composer.json declares a project's metadata, required dependencies and their version constraints, and autoloading configuration.
Code Example
{
"require": {
"monolog/monolog": "^3.0"
}
}
PHP
#1.103
Q103:
How do you check the type of an object dynamically?
Ans:
get_class() returns the name of an object's class as a string, useful when the class type must be determined at runtime.
Code Example
echo get_class($car); // 'Car'
JAVA
#1.104
Q104:
What is Java?
Ans:
Java is a general-purpose, class-based, object-oriented programming language designed to have as few implementation dependencies as possible, following the 'write once, run anywhere' principle via the JVM.
JAVA
#1.105
Q105:
What is the difference between JDK, JRE, and JVM?
Ans:
JVM (Java Virtual Machine) executes Java bytecode; JRE (Java Runtime Environment) includes the JVM plus standard libraries needed to run applications; JDK (Java Development Kit) includes the JRE plus development tools like the compiler (javac) needed to build applications.
JAVA
#1.106
Q106:
What is bytecode in Java?
Ans:
Bytecode is the intermediate, platform-independent code produced by the Java compiler (javac) from source code, which the JVM interprets or compiles just-in-time into native machine code.
JAVA
#1.107
Q107:
Why is Java considered platform independent?
Ans:
Java source code is compiled into bytecode, which can run on any device with a compatible JVM, so the same compiled code runs on different operating systems without recompilation.
JAVA
#1.108
Q108:
What is the entry point of a Java application?
Ans:
The main method, public static void main(String[] args), is the entry point where the JVM begins executing a standalone Java application.
Code Example
public class App {
public static void main(String[] args) {
System.out.println("Hello");
}
}
JAVA
#1.109
Q109:
What are the basic data types in Java?
Ans:
Java has eight primitive types: byte, short, int, long, float, double, char, and boolean.
JAVA
#1.110
Q110:
What is the difference between primitive types and reference types?
Ans:
Primitive types store actual values directly in memory (like int, boolean), while reference types (objects, arrays) store a reference/address pointing to the object's data on the heap.
JAVA
#1.111
Q111:
What are wrapper classes in Java?
Ans:
Wrapper classes (Integer, Double, Boolean, Character, etc.) encapsulate primitive types as objects, enabling their use in collections and providing utility methods.
JAVA
#1.112
Q112:
What is the default value of an int and a boolean instance variable?
Ans:
An uninitialized int instance variable defaults to 0, and an uninitialized boolean defaults to false; local variables, however, have no default and must be explicitly initialized before use.
JAVA
#1.113
Q113:
What is the difference between == and .equals() in Java?
Ans:
== compares object references (memory addresses) for objects or actual values for primitives, while .equals() compares the logical content of objects, and can be overridden to define custom equality.
Code Example
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
JAVA
#1.114
Q114:
What are the access modifiers in Java?
Ans:
Java has four access levels: private (class only), default/package-private (same package), protected (same package plus subclasses), and public (accessible everywhere).
JAVA
#1.115
Q115:
What is a package in Java?
Ans:
A package is a namespace that organizes related classes and interfaces together, helping avoid naming conflicts and controlling access with package-private visibility.
Code Example
package com.example.app;
JAVA
#1.116
Q116:
How do you import a class from another package?
Ans:
You use the import statement at the top of the file, specifying the fully qualified class name or a wildcard to import all classes from a package.
Code Example
import java.util.List;
import java.util.*;
JAVA
#1.117
Q117:
What is the difference between an object and a class?
Ans:
A class is a blueprint or template defining properties and behaviors, while an object is a concrete instance of a class created at runtime using the new keyword.
JAVA
#1.118
Q118:
What is the 'this' keyword used for?
Ans:
'this' refers to the current instance of the class, commonly used to distinguish instance variables from parameters with the same name or to invoke another constructor.
Code Example
class Point {
int x;
Point(int x) { this.x = x; }
}
JAVA
#1.119
Q119:
What is the 'super' keyword used for?
Ans:
'super' refers to the immediate parent class, used to access parent class methods, fields, or invoke the parent's constructor.
Code Example
class Dog extends Animal {
Dog() { super(); }
void sound() { super.sound(); System.out.println("Bark"); }
}
JAVA
#1.120
Q120:
What are command-line arguments in Java?
Ans:
Command-line arguments are values passed to the main method's String[] args parameter when running a Java program from the terminal.
Code Example
public static void main(String[] args) {
System.out.println(args[0]);
}
JAVA
#1.121
Q121:
What is the difference between a local variable and an instance variable?
Ans:
A local variable is declared within a method and only exists during that method's execution, while an instance variable belongs to an object and persists for the object's lifetime.
JAVA
#1.122
Q122:
What is a static variable in Java?
Ans:
A static variable belongs to the class rather than any instance, is shared among all objects of that class, and is initialized only once when the class is loaded.
Code Example
class Counter {
static int count = 0;
Counter() { count++; }
}
JAVA
#1.123
Q123:
What is the difference between static and instance methods?
Ans:
Static methods belong to the class and can be called without creating an instance, while instance methods operate on a specific object and require an instance to be invoked.
JAVA
#1.124
Q124:
What is a constant in Java and how do you declare one?
Ans:
A constant is declared using the final keyword (often combined with static), indicating its value cannot be reassigned after initialization.
Code Example
static final double PI = 3.14159;
JAVA
#1.125
Q125:
What is the instanceof operator used for?
Ans:
instanceof checks whether an object is an instance of a specified class or interface, returning a boolean, and can be used for safe downcasting.
Code Example
if (obj instanceof String) { String s = (String) obj; }
JAVA
#1.126
Q126:
What are the different categories of operators in Java?
Ans:
Java has arithmetic, relational, logical, bitwise, assignment, unary, ternary, and the instanceof operator.
JAVA
#1.127
Q127:
What is the difference between ++i and i++?
Ans:
++i (pre-increment) increments the value before it is used in the expression, while i++ (post-increment) uses the current value in the expression first and then increments it.
Code Example
int i = 5;
int a = ++i; // a=6, i=6
int b = i++; // b=6, i=7
JAVA
#1.128
Q128:
What is the ternary operator in Java?
Ans:
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand conditional expression that evaluates to one of two values.
Code Example
int max = (a > b) ? a : b;
JAVA
#1.129
Q129:
What are Java's control flow statements?
Ans:
Java supports if-else, switch, for, while, do-while loops, along with break, continue, and return statements to control execution flow.
JAVA
#1.130
Q130:
What is the enhanced for loop (for-each) in Java?
Ans:
The for-each loop iterates over elements of an array or a Collection without needing an explicit index or iterator.
Code Example
for (int num : numbers) {
System.out.println(num);
}
JAVA
#1.131
Q131:
How does a traditional switch statement work in Java?
Ans:
switch evaluates an expression and executes the matching case block; without a break statement, execution falls through to subsequent cases.
Code Example
switch (day) {
case 1: System.out.println("Mon"); break;
default: System.out.println("Other");
}
JAVA
#1.132
Q132:
What is the difference between break and continue?
Ans:
break exits the loop or switch entirely, while continue skips the rest of the current iteration and proceeds to the next one.
JAVA
#1.133
Q133:
What is the difference between while and do-while loops?
Ans:
A while loop checks its condition before executing the loop body, potentially not running at all, while a do-while loop executes the body at least once before checking the condition.
JAVA
#1.134
Q134:
What are the four pillars of OOP?
Ans:
The four pillars are encapsulation (bundling data and methods), inheritance (reusing behavior from parent classes), polymorphism (many forms via overriding/overloading), and abstraction (hiding implementation details behind interfaces).
JAVA
#1.135
Q135:
What is encapsulation in Java?
Ans:
Encapsulation is the practice of keeping fields private and exposing controlled access through public getter and setter methods, protecting an object's internal state from unintended modification.
Code Example
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { balance += amt; }
}
JAVA
#1.136
Q136:
What is inheritance in Java?
Ans:
Inheritance allows a class (subclass) to acquire the fields and methods of another class (superclass) using the extends keyword, promoting code reuse.
Code Example
class Animal { void eat() {} }
class Dog extends Animal {}
JAVA
#1.137
Q137:
What is method overloading?
Ans:
Method overloading occurs when multiple methods in the same class share a name but differ in parameter type, number, or order, resolved at compile time (static polymorphism).
Code Example
void print(int a) {}
void print(String s) {}
void print(int a, int b) {}
JAVA
#1.138
Q138:
What is method overriding?
Ans:
Method overriding occurs when a subclass provides its own implementation of a method already defined in its superclass, with the same signature, resolved at runtime (dynamic polymorphism).
Code Example
class Animal { void sound() { System.out.println("..."); } }
class Cat extends Animal { @Override void sound() { System.out.println("Meow"); } }
JAVA
#1.139
Q139:
What is constructor overloading?
Ans:
Constructor overloading is defining multiple constructors in a class with different parameter lists, allowing objects to be created in different ways.
Code Example
class Box {
Box() {}
Box(int size) {}
}
JAVA
#1.140
Q140:
What is a default constructor?
Ans:
If no constructor is explicitly defined, Java automatically provides a no-argument default constructor that initializes fields to their default values.
JAVA
#1.141
Q141:
What is the toString() method used for?
Ans:
toString() returns a string representation of an object, automatically called when the object is used in string concatenation or printed with System.out.println(), and is commonly overridden for meaningful output.
Code Example
@Override
public String toString() { return "Point(" + x + ", " + y + ")"; }
JAVA
#1.142
Q142:
What is an exception in Java?
Ans:
An exception is an event that disrupts normal program flow, represented as an object of a class extending Throwable, which can be thrown and caught to handle errors gracefully.
JAVA
#1.143
Q143:
How do you handle exceptions in Java?
Ans:
You use a try block for risky code, one or more catch blocks to handle specific exception types, and an optional finally block for cleanup code that always runs.
Code Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Done");
}
JAVA
#1.144
Q144:
What is a stack trace?
Ans:
A stack trace is a report of the call stack at the point an exception was thrown, showing the sequence of method calls that led to the error, useful for debugging.
JAVA
#1.145
Q145:
What is the Java Collections Framework?
Ans:
The Collections Framework is a unified architecture of interfaces (List, Set, Map, Queue) and classes (ArrayList, HashMap, HashSet, etc.) for storing and manipulating groups of objects.
JAVA
#1.146
Q146:
What is the difference between List, Set, and Map?
Ans:
A List is an ordered collection that allows duplicate elements, a Set is a collection that disallows duplicates, and a Map stores key-value pairs where each key is unique.
JAVA
#1.147
Q147:
What is the difference between Array and ArrayList in Java?
Ans:
An array has a fixed size determined at creation and can hold primitives or objects, while an ArrayList is a resizable collection that can only hold objects (using autoboxing for primitives) and provides many convenience methods.
JAVA
#1.148
Q148:
How do you sort a List in Java?
Ans:
You can use Collections.sort() for natural ordering (requires Comparable) or pass a Comparator, or call the list's own sort() method introduced in Java 8.
Code Example
Collections.sort(names);
names.sort(Comparator.reverseOrder());
JAVA
#1.149
Q149:
How do you compare two strings for equality in Java?
Ans:
You should use the .equals() method to compare the content of two strings, since == compares references and may return false even for strings with identical content.
Code Example
String a = "hi";
String b = new String("hi");
System.out.println(a.equals(b)); // true
JAVA
#1.150
Q150:
What is the difference between equals() and equalsIgnoreCase()?
Ans:
equals() performs a case-sensitive comparison of string content, while equalsIgnoreCase() ignores letter case when comparing.
JAVA
#1.151
Q151:
How do you convert a String to an int and vice versa?
Ans:
Integer.parseInt() converts a String to a primitive int, and String.valueOf() or Integer.toString() converts an int to a String.
Code Example
int n = Integer.parseInt("42");
String s = String.valueOf(42);
JAVA
#1.152
Q152:
How do you split a String in Java?
Ans:
The split() method divides a string into an array of substrings based on a given regular expression delimiter.
Code Example
String[] parts = "a,b,c".split(",");
JAVA
#1.153
Q153:
How do you check if a string is null or empty in Java?
Ans:
You can check (str == null || str.isEmpty()), or use isBlank() (Java 11+) to also treat whitespace-only strings as empty.
JAVA
#1.154
Q154:
What is the difference between length() and length in Java?
Ans:
length() is a method used on String objects to get the number of characters, while length is a field (not a method) used on arrays to get the number of elements.
Code Example
String s = "hello"; s.length(); // 5
int[] arr = new int[5]; arr.length; // 5
JAVA
#1.155
Q155:
How do you create a multidimensional array in Java?
Ans:
You declare it with multiple sets of square brackets, and can initialize it with nested array literals or by specifying dimensions with new.
Code Example
int[][] matrix = new int[3][3];
int[][] grid = {{1,2},{3,4}};
JAVA
#1.156
Q156:
How do you sort an array in Java?
Ans:
Arrays.sort() sorts a primitive or object array in place, using natural ordering by default or a supplied Comparator for object arrays.
Code Example
int[] nums = {5,3,1,4};
Arrays.sort(nums);
JAVA
#1.157
Q157:
How do you reverse a String in Java?
Ans:
You can convert it to a StringBuilder and call reverse(), since String itself has no reverse method.
Code Example
String reversed = new StringBuilder("hello").reverse().toString();
JAVA
#1.158
Q158:
What is a thread in Java?
Ans:
A thread is a lightweight sub-process, the smallest unit of execution, allowing a program to perform multiple operations concurrently.
JAVA
#1.159
Q159:
What are the two ways to create a thread in Java?
Ans:
You can extend the Thread class and override its run() method, or implement the Runnable interface and pass an instance to a Thread object.
Code Example
class MyThread extends Thread {
public void run() { System.out.println("Running"); }
}
class MyTask implements Runnable {
public void run() { System.out.println("Running"); }
}
new Thread(new MyTask()).start();
JAVA
#1.160
Q160:
What is garbage collection in Java?
Ans:
Garbage collection is the automatic process by which the JVM reclaims memory occupied by objects that are no longer reachable from any live references, freeing developers from manual memory deallocation.
JAVA
#1.161
Q161:
What is the difference between an interface and a class regarding instantiation?
Ans:
An interface cannot be instantiated directly (though Java 8+ allows default/static methods), while a class can be instantiated using the new keyword unless it's declared abstract.
JAVA
#1.162
Q162:
What is the purpose of the @Override annotation?
Ans:
@Override signals to the compiler that a method is intended to override a superclass or interface method, causing a compile-time error if no matching method actually exists to override, helping catch typos or signature mismatches.
JAVA
#1.163
Q163:
What is JDBC?
Ans:
JDBC (Java Database Connectivity) is a Java API that provides a standard way to connect to and interact with relational databases using SQL, regardless of the specific database vendor.
JAVA
#1.164
Q164:
How do you convert a List to an array and vice versa?
Ans:
You use list.toArray() to convert a List to an array, and Arrays.asList() or List.of() to create a List view or immutable list from an array.
Code Example
String[] arr = list.toArray(new String[0]);
List<String> list2 = Arrays.asList(arr);
JAVA
#1.165
Q165:
What happens when you don't override toString() for a custom object?
Ans:
The default Object.toString() implementation is used, which returns the class name followed by an '@' and the object's hash code in hexadecimal, which is rarely useful for debugging.
PYTHON
#1.166
Q166:
What is Python?
Ans:
Python is a high-level, interpreted, general-purpose programming language known for its readable syntax, dynamic typing, and large standard library, supporting multiple programming paradigms.
PYTHON
#1.167
Q167:
Is Python interpreted or compiled?
Ans:
Python is generally interpreted; source code is compiled to bytecode (.pyc files) which is then executed by the Python Virtual Machine (PVM), so it involves both a compilation step and interpretation.
PYTHON
#1.168
Q168:
What are the key features of Python?
Ans:
Python offers dynamic typing, automatic memory management, a large standard library, readable indentation-based syntax, support for multiple paradigms (procedural, object-oriented, functional), and cross-platform portability.
PYTHON
#1.169
Q169:
What is PEP 8?
Ans:
PEP 8 is Python's official style guide, providing conventions for code layout, naming, and formatting to improve readability and consistency across Python codebases.
PYTHON
#1.170
Q170:
How do you write comments in Python?
Ans:
Single-line comments start with #, and multi-line comments/docstrings are typically written using triple quotes (''' or """).
Code Example
# This is a comment
"""
This is a docstring or multi-line comment
"""
PYTHON
#1.171
Q171:
How do you declare a variable in Python?
Ans:
Python variables don't require explicit type declaration; you simply assign a value to a name, and the interpreter infers the type dynamically.
Code Example
x = 10
name = 'Alice'
PYTHON
#1.172
Q172:
What are the rules for naming variables in Python?
Ans:
Variable names must start with a letter or underscore, can contain letters, digits, and underscores, cannot be a reserved keyword, and are case-sensitive.
PYTHON
#1.173
Q173:
What is dynamic typing in Python?
Ans:
Dynamic typing means a variable's type is determined at runtime based on the value assigned to it, and the same variable name can be reassigned to hold values of different types.
Code Example
x = 5
x = 'hello' # allowed, x is now a string
PYTHON
#1.174
Q174:
What are Python's built-in data types?
Ans:
Python's core built-in types include int, float, complex, str, bool, list, tuple, dict, set, frozenset, and NoneType.
PYTHON
#1.175
Q175:
What is the difference between a list and a tuple?
Ans:
A list is mutable (elements can be changed, added, or removed) and defined with square brackets, while a tuple is immutable and defined with parentheses, making tuples generally faster and hashable when containing only immutable elements.
Code Example
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
PYTHON
#1.176
Q176:
How do you check the type of a variable in Python?
Ans:
The type() function returns an object's type, and isinstance() checks whether an object is an instance of a given type or class.
Code Example
print(type(5)) # <class 'int'>
print(isinstance(5, int)) # True
PYTHON
#1.177
Q177:
What is None in Python?
Ans:
None is a special singleton value representing the absence of a value or a null value, and is the default return value of functions that don't explicitly return anything.
PYTHON
#1.178
Q178:
How do you check if a variable is None?
Ans:
You should use 'is None' rather than '== None', since 'is' checks identity and None is a singleton, making it the recommended and slightly faster comparison.
Code Example
if value is None:
print('No value')
PYTHON
#1.179
Q179:
What is the difference between == and is in Python?
Ans:
== compares the values of two objects for equality, while 'is' compares their identity, checking whether they refer to the exact same object in memory.
Code Example
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
PYTHON
#1.180
Q180:
What are Python keywords?
Ans:
Keywords are reserved words with special meaning in the language (like if, else, def, class, import, return) that cannot be used as variable or function names.
PYTHON
#1.181
Q181:
How do you take user input in Python?
Ans:
The input() function reads a line of text from standard input as a string, which can then be converted to another type if needed.
Code Example
name = input('Enter your name: ')
age = int(input('Enter your age: '))
PYTHON
#1.182
Q182:
What is an f-string in Python?
Ans:
f-strings (formatted string literals), introduced in Python 3.6, allow embedding expressions directly inside string literals using curly braces, prefixed with an 'f'.
Code Example
name = 'Tom'
print(f'Hello, {name}! You are {2024-1999} years old.')
PYTHON
#1.183
Q183:
What are the different types of operators in Python?
Ans:
Python supports arithmetic, comparison, assignment, logical, bitwise, membership (in, not in), and identity (is, is not) operators.
PYTHON
#1.184
Q184:
What is the difference between / and // in Python?
Ans:
/ performs true division and always returns a float, while // performs floor division, returning the largest integer less than or equal to the result.
Code Example
print(7 / 2) # 3.5
print(7 // 2) # 3
PYTHON
#1.185
Q185:
What does the ** operator do?
Ans:
** is the exponentiation operator, raising the left operand to the power of the right operand.
Code Example
print(2 ** 3) # 8
PYTHON
#1.186
Q186:
What is the modulus operator used for in Python?
Ans:
The % operator returns the remainder of dividing the left operand by the right operand.
Code Example
print(10 % 3) # 1
PYTHON
#1.187
Q187:
How do you write an if-elif-else statement in Python?
Ans:
Python uses if, elif (else if), and else keywords, with code blocks defined by indentation rather than braces.
Code Example
if age < 13:
print('Child')
elif age < 20:
print('Teenager')
else:
print('Adult')
PYTHON
#1.188
Q188:
How does Python define code blocks instead of using braces?
Ans:
Python uses consistent indentation (whitespace) to define the scope of code blocks like loops, functions, and conditionals, rather than curly braces used in many other languages.
PYTHON
#1.189
Q189:
What is a for loop used for in Python?
Ans:
A for loop iterates over the items of any iterable (list, tuple, string, range, dict, etc.), executing the loop body once per item.
Code Example
for i in range(5):
print(i)
PYTHON
#1.190
Q190:
What is the range() function used for?
Ans:
range() generates a sequence of numbers, commonly used for looping a specific number of times, accepting start, stop, and step arguments.
Code Example
for i in range(2, 10, 2):
print(i) # 2 4 6 8
PYTHON
#1.191
Q191:
What is the difference between break, continue, and pass?
Ans:
break exits the loop entirely, continue skips to the next iteration, and pass is a no-op placeholder statement that does nothing, often used where syntax requires a statement but no action is needed.
PYTHON
#1.192
Q192:
What is a while loop used for?
Ans:
A while loop repeatedly executes a block of code as long as a specified condition remains true.
Code Example
i = 0
while i < 5:
print(i)
i += 1
PYTHON
#1.193
Q193:
How do you define a function in Python?
Ans:
Functions are defined using the def keyword, followed by the function name, parameters in parentheses, a colon, and an indented body.
Code Example
def greet(name):
return f'Hello, {name}'
PYTHON
#1.194
Q194:
What is a default parameter value in Python?
Ans:
A default value can be assigned to a parameter in the function definition, making that argument optional when the function is called.
Code Example
def greet(name='Guest'):
return f'Hello, {name}'
PYTHON
#1.195
Q195:
What is the difference between positional and keyword arguments?
Ans:
Positional arguments are matched to parameters by their order in the function call, while keyword arguments are matched by explicitly naming the parameter, allowing them to be passed in any order.
Code Example
def greet(name, greeting):
print(f'{greeting}, {name}')
greet(greeting='Hi', name='Tom')
PYTHON
#1.196
Q196:
What are lambda functions in Python?
Ans:
A lambda function is a small, anonymous function defined with the lambda keyword, limited to a single expression, often used for short throwaway functions passed to other functions.
Code Example
square = lambda x: x * x
print(square(5)) # 25
PYTHON
#1.197
Q197:
What does the return statement do in a function without an explicit value?
Ans:
A bare return statement (or falling off the end of a function without any return) causes the function to return None.
PYTHON
#1.198
Q198:
What is a docstring in Python?
Ans:
A docstring is a string literal that appears as the first statement in a module, function, class, or method, used to document its purpose, accessible via the __doc__ attribute or help().
Code Example
def add(a, b):
"""Return the sum of a and b."""
return a + b
PYTHON
#1.199
Q199:
How do you find the length of a string in Python?
Ans:
The built-in len() function returns the number of characters in a string.
Code Example
print(len('Hello')) # 5
PYTHON
#1.200
Q200:
How do you concatenate strings in Python?
Ans:
Strings can be concatenated using the + operator, the join() method, or f-strings/format() for combining with other values.
Code Example
full = 'Hello' + ' ' + 'World'
PYTHON
#1.201
Q201:
What is string slicing in Python?
Ans:
Slicing extracts a substring using the syntax string[start:stop:step], where start is inclusive and stop is exclusive, and negative indices count from the end.
Code Example
s = 'Hello World'
print(s[0:5]) # 'Hello'
print(s[-5:]) # 'World'
PYTHON
#1.202
Q202:
How do you reverse a string in Python?
Ans:
A common idiom is to slice the string with a step of -1, though reversed() combined with ''.join() also works.
Code Example
s = 'hello'
print(s[::-1]) # 'olleh'
PYTHON
#1.203
Q203:
How do you check if a string contains a substring?
Ans:
You can use the 'in' operator to check membership, or the str.find()/str.index() methods to locate the position.
Code Example
if 'World' in 'Hello World':
print('found')
PYTHON
#1.204
Q204:
How do you split a string into a list?
Ans:
The str.split() method divides a string into a list of substrings based on a specified delimiter (whitespace by default).
Code Example
parts = 'a,b,c'.split(',') # ['a', 'b', 'c']
PYTHON
#1.205
Q205:
How do you join a list of strings into one string?
Ans:
The str.join() method concatenates elements of an iterable using the string it's called on as the separator.
Code Example
result = ', '.join(['a', 'b', 'c']) # 'a, b, c'
PYTHON
#1.206
Q206:
How do you convert a string to uppercase or lowercase?
Ans:
str.upper() converts all characters to uppercase, and str.lower() converts all characters to lowercase.
PYTHON
#1.207
Q207:
How do you remove leading/trailing whitespace from a string?
Ans:
str.strip() removes whitespace (or specified characters) from both ends; lstrip() and rstrip() remove only from the left or right respectively.
Code Example
print(' hello '.strip()) # 'hello'
PYTHON
#1.208
Q208:
How do you check if a string starts or ends with a given substring?
Ans:
str.startswith() and str.endswith() check whether a string begins or ends with a specified substring, returning a boolean.
Code Example
print('hello.py'.endswith('.py')) # True
PYTHON
#1.209
Q209:
How do you add an element to a list?
Ans:
list.append() adds a single element to the end, while list.extend() adds all elements from an iterable, and list.insert() adds an element at a specific index.
Code Example
nums = [1, 2]
nums.append(3) # [1, 2, 3]
PYTHON
#1.210
Q210:
How do you remove an element from a list?
Ans:
list.remove(value) removes the first matching value, list.pop(index) removes and returns an element at a given index (or the last one by default), and del list[index] deletes by index.
Code Example
nums = [1, 2, 3]
nums.remove(2) # [1, 3]
nums.pop() # removes last, returns 3
PYTHON
#1.211
Q211:
What is the difference between a list and a set in Python?
Ans:
A list is an ordered, mutable collection that allows duplicate elements, while a set is an unordered, mutable collection of unique, hashable elements optimized for fast membership testing.
PYTHON
#1.212
Q212:
What is a dictionary in Python?
Ans:
A dictionary is an unordered (insertion-ordered since Python 3.7) collection of key-value pairs, providing fast average O(1) lookup, insertion, and deletion by key.
Code Example
person = {'name': 'Alice', 'age': 30}
PYTHON
#1.213
Q213:
How do you safely get a value from a dictionary without raising an error if the key is missing?
Ans:
The dict.get(key, default) method returns the value for a key if present, or a specified default (None if omitted) instead of raising a KeyError.
Code Example
age = person.get('age', 0)
PYTHON
#1.214
Q214:
What is the difference between dict.get() and dict[key]?
Ans:
dict[key] raises a KeyError if the key doesn't exist, while dict.get(key) returns None (or a specified default) instead of raising an exception.
PYTHON
#1.215
Q215:
How do you iterate over key-value pairs of a dictionary?
Ans:
The dict.items() method returns key-value pairs as tuples, commonly used in a for loop to unpack both key and value.
Code Example
for key, value in person.items():
print(key, value)
PYTHON
#1.216
Q216:
What is the difference between append() and extend() on a list?
Ans:
append() adds its single argument as one new element at the end of the list, while extend() iterates over its argument and adds each individual element to the list.
Code Example
a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4]) # [1, 2, 3, 4]
PYTHON
#1.217
Q217:
What is the difference between list.sort() and sorted()?
Ans:
list.sort() sorts the list in place and returns None, while sorted() returns a new sorted list (or iterable-derived list) and leaves the original unchanged, working on any iterable.
PYTHON
#1.218
Q218:
What does the enumerate() function do?
Ans:
enumerate() adds a counter to an iterable, returning pairs of (index, element), commonly used in for loops when both the position and value are needed.
Code Example
for i, val in enumerate(['a', 'b', 'c']):
print(i, val)
PYTHON
#1.219
Q219:
How do you define a class in Python?
Ans:
Classes are defined using the class keyword followed by the class name and a colon, with methods and attributes defined in the indented body.
Code Example
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f'{self.name} says woof'
PYTHON
#1.220
Q220:
What is the __init__ method used for?
Ans:
__init__ is a special method (constructor) automatically called when a new instance of a class is created, typically used to initialize instance attributes.
PYTHON
#1.221
Q221:
What is 'self' in Python class methods?
Ans:
'self' refers to the current instance of the class and is conventionally the first parameter of instance methods, allowing access to instance attributes and other methods.
PYTHON
#1.222
Q222:
What is inheritance in Python?
Ans:
Inheritance allows a class (subclass) to acquire attributes and methods from another class (superclass), specified by passing the parent class in parentheses after the class name.
Code Example
class Animal:
def eat(self):
print('Eating')
class Dog(Animal):
pass
PYTHON
#1.223
Q223:
What is method overriding in Python?
Ans:
Method overriding occurs when a subclass defines a method with the same name as one in its parent class, replacing the inherited behavior for instances of the subclass.
PYTHON
#1.224
Q224:
How do you handle exceptions in Python?
Ans:
You use a try block to wrap risky code, one or more except blocks to catch specific exception types, an optional else block that runs if no exception occurred, and an optional finally block that always executes.
Code Example
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
finally:
print('Done')
PYTHON
#1.225
Q225:
What is the difference between a module and a package in Python?
Ans:
A module is a single .py file containing Python code, while a package is a directory containing multiple modules along with an __init__.py file (optional since Python 3.3 for namespace packages), organizing related modules together.
PYTHON
#1.226
Q226:
How do you import a module in Python?
Ans:
You use the import statement, optionally with 'as' to alias it, or 'from module import name' to import specific attributes directly.
Code Example
import math
from math import sqrt
import numpy as np
PYTHON
#1.227
Q227:
What is a virtual environment in Python and why is it used?
Ans:
A virtual environment is an isolated Python environment with its own installed packages, separate from the system-wide Python installation, allowing different projects to use different (potentially conflicting) package versions.
Code Example
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
PYTHON
#1.228
Q228:
What is pip and what is it used for?
Ans:
pip is Python's standard package manager, used to install, upgrade, and remove third-party packages from the Python Package Index (PyPI) or other sources.
Code Example
pip install requests
PYTHON
#1.229
Q229:
What is a requirements.txt file used for?
Ans:
requirements.txt lists a project's dependencies (often with pinned versions), allowing others to install the exact same set of packages using 'pip install -r requirements.txt'.
PYTHON
#1.230
Q230:
What is the Python Standard Library?
Ans:
The Standard Library is the collection of modules that ship with every Python installation, providing built-in functionality for tasks like file I/O, math, networking, data structures, and more, without needing external installation.
PYTHON
#1.231
Q231:
How do you open and read a file in Python?
Ans:
The built-in open() function returns a file object, and methods like read(), readline(), or readlines() retrieve its contents; using a 'with' statement ensures the file is properly closed.
Code Example
with open('data.txt', 'r') as f:
content = f.read()
PYTHON
#1.232
Q232:
What are the common file modes used with open()?
Ans:
Common modes include 'r' (read), 'w' (write, truncating existing content), 'a' (append), 'x' (exclusive creation), and 'b' suffix for binary mode (e.g., 'rb', 'wb').
PYTHON
#1.233
Q233:
Why is it recommended to use the 'with' statement when working with files?
Ans:
The 'with' statement acts as a context manager that automatically closes the file when the block exits, even if an exception occurs, preventing resource leaks from forgotten close() calls.
PYTHON
#1.234
Q234:
How do you write to a file in Python?
Ans:
You open the file in write ('w') or append ('a') mode and call the file object's write() or writelines() method.
Code Example
with open('log.txt', 'a') as f:
f.write('New log entry\n')
PYTHON
#1.235
Q235:
How do you check if a file exists in Python?
Ans:
The os.path.exists() function, or the more modern pathlib.Path.exists() method, checks whether a given path exists on the filesystem.
Code Example
from pathlib import Path
if Path('config.txt').exists():
print('File found')
PYTHON
#1.236
Q236:
How do you work with JSON data in Python?
Ans:
The json module's dumps()/dump() functions convert Python objects to JSON strings/files, while loads()/load() parse JSON strings/files back into Python objects.
Code Example
import json
data = json.loads('{"name": "Tom"}')
json_str = json.dumps(data)
PYTHON
#1.237
Q237:
What are the truthy and falsy values in Python?
Ans:
Falsy values include False, None, 0, 0.0, '', [], (), {}, and set(); virtually all other values, including non-empty containers and non-zero numbers, are truthy.
Code Example
if []: print('truthy')
else: print('falsy') # prints 'falsy'
PYTHON
#1.238
Q238:
What does the built-in sorted() function's key parameter do?
Ans:
The key parameter accepts a function used to extract a comparison value from each element, allowing custom sort criteria without modifying the comparison operators themselves.
Code Example
sorted(words, key=len) # sort strings by length
PYTHON
#1.239
Q239:
What is the difference between sorted() and list.sort() regarding return values?
Ans:
sorted() returns a new sorted list without modifying the original iterable, while list.sort() sorts the list in place and returns None.
PYTHON
#1.240
Q240:
What is the difference between a Python script and a Python module?
Ans:
A script is typically a standalone file meant to be run directly to perform a task, while a module is a file intended to be imported and reused by other scripts or modules, though the same .py file can serve both purposes.
PYTHON
#1.241
Q241:
What is the purpose of the enumerate() function's start parameter?
Ans:
The optional start parameter to enumerate() specifies the initial index value to begin counting from, instead of the default 0.
Code Example
for i, val in enumerate(['a','b','c'], start=1):
print(i, val) # 1 a, 2 b, 3 c
NODE.JS
#1.242
Q242:
What is Node.js?
Ans:
Node.js is an open-source, cross-platform JavaScript runtime built on Google's V8 engine that allows JavaScript to run outside the browser, commonly used for building server-side applications and command-line tools.
NODE.JS
#1.243
Q243:
Is Node.js a programming language or a framework?
Ans:
Node.js is neither a language nor a framework; it's a runtime environment that executes JavaScript code outside a web browser, providing APIs for file systems, networking, and more.
NODE.JS
#1.244
Q244:
What is the V8 engine?
Ans:
V8 is Google's open-source JavaScript and WebAssembly engine (used in Chrome and Node.js) that compiles JavaScript directly into optimized machine code for fast execution.
NODE.JS
#1.245
Q245:
What is the difference between Node.js and browser JavaScript?
Ans:
Node.js provides server-side APIs like file system access, networking, and process management but lacks browser-specific objects like window and document, while browser JavaScript includes the DOM API but lacks direct filesystem or OS-level access for security reasons.
NODE.JS
#1.246
Q246:
What is npm?
Ans:
npm (Node Package Manager) is the default package manager for Node.js, used to install, publish, and manage JavaScript packages and their dependencies via the npm registry.
NODE.JS
#1.247
Q247:
What is a package.json file?
Ans:
package.json is the manifest file for a Node.js project, containing metadata like the project name, version, dependencies, scripts, and entry point.
Code Example
{
"name": "my-app",
"version": "1.0.0",
"main": "index.js",
"dependencies": { "express": "^4.18.0" }
}
NODE.JS
#1.248
Q248:
What is the difference between dependencies and devDependencies in package.json?
Ans:
dependencies lists packages required for the application to run in production, while devDependencies lists packages only needed during development, like testing tools or bundlers.
NODE.JS
#1.249
Q249:
What is the difference between global and local npm package installation?
Ans:
A locally installed package (default) is placed in the project's node_modules folder and used only within that project, while a globally installed package (-g flag) is available system-wide as a command-line tool.
Code Example
npm install lodash # local
npm install -g nodemon # global
NODE.JS
#1.250
Q250:
What is the require() function used for?
Ans:
require() is the CommonJS function used to import modules, whether built-in Node.js modules, local files, or installed npm packages.
Code Example
const fs = require('fs');
const myModule = require('./myModule');
NODE.JS
#1.251
Q251:
How do you export multiple values from a Node.js module?
Ans:
In CommonJS, you attach multiple properties to module.exports (or exports); in ES Modules, you use named exports.
Code Example
// CommonJS
module.exports = { add, subtract };
// ES Modules
export { add, subtract };
NODE.JS
#1.252
Q252:
What are Node.js core (built-in) modules?
Ans:
Core modules are built into Node.js and available without installation, such as fs (file system), http, path, os, events, and crypto.
Code Example
const path = require('path');
const http = require('http');
NODE.JS
#1.253
Q253:
What are __dirname and __filename in Node.js?
Ans:
__dirname returns the absolute path of the directory containing the currently executing file, and __filename returns the absolute path of the file itself; both are only available in CommonJS modules.
Code Example
console.log(__dirname);
console.log(__filename);
NODE.JS
#1.254
Q254:
How do you read environment variables in Node.js?
Ans:
Environment variables are accessed through process.env, often combined with a package like dotenv to load variables from a .env file during development.
Code Example
require('dotenv').config();
const apiKey = process.env.API_KEY;
NODE.JS
#1.255
Q255:
What is a callback function in Node.js?
Ans:
A callback is a function passed as an argument to another function, invoked after an asynchronous (or synchronous) operation completes, historically the primary way to handle async code in Node.js.
Code Example
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
NODE.JS
#1.256
Q256:
What is the difference between synchronous and asynchronous code execution in Node.js?
Ans:
Synchronous code executes sequentially, blocking further execution until each operation completes, while asynchronous code allows Node.js to continue executing other code while waiting for operations like I/O to complete, improving throughput for I/O-bound workloads.
NODE.JS
#1.257
Q257:
What is the difference between setTimeout() and setInterval()?
Ans:
setTimeout() schedules a function to run once after a specified delay, while setInterval() repeatedly schedules a function to run at fixed intervals until cleared with clearInterval().
Code Example
setTimeout(() => console.log('once'), 1000);
const id = setInterval(() => console.log('repeating'), 1000);
clearInterval(id);
NODE.JS
#1.258
Q258:
What is the difference between a relative and an absolute module path in require()?
Ans:
A relative path (starting with ./ or ../) resolves relative to the requiring file's location, while a bare module name (like 'express') is resolved by searching node_modules directories up the folder tree.
NODE.JS
#1.259
Q259:
How do you read a file asynchronously in Node.js?
Ans:
The fs.readFile() method reads a file's contents asynchronously, accepting a callback (or returning a Promise via fs.promises/fs/promises) that receives the data once reading completes.
Code Example
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
NODE.JS
#1.260
Q260:
What is the difference between fs.readFile() and fs.readFileSync()?
Ans:
fs.readFile() performs the read asynchronously and doesn't block the event loop, using a callback for the result, while fs.readFileSync() blocks execution until the file is fully read, returning the data directly.
NODE.JS
#1.261
Q261:
What is the path module used for in Node.js?
Ans:
The path module provides utilities for working with file and directory paths in a cross-platform way, such as path.join(), path.resolve(), path.basename(), and path.extname().
Code Example
const path = require('path');
console.log(path.join('/users', 'tom', 'file.txt'));
NODE.JS
#1.262
Q262:
How do you create a basic HTTP server in Node.js?
Ans:
The built-in http module's createServer() method takes a request handler function and returns a server object that can listen() on a specified port.
Code Example
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
});
server.listen(3000);
NODE.JS
#1.263
Q263:
What is Express.js?
Ans:
Express is a minimal and flexible Node.js web application framework that simplifies building web servers and APIs, providing routing, middleware support, and template engine integration on top of the core http module.
Code Example
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000);
NODE.JS
#1.264
Q264:
How do you handle route parameters in Express?
Ans:
Route parameters are defined with a colon prefix in the route path and accessed via req.params in the handler function.
Code Example
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
NODE.JS
#1.265
Q265:
How do you parse JSON request bodies in Express?
Ans:
The built-in express.json() middleware parses incoming requests with a JSON payload and populates req.body with the parsed object.
Code Example
app.use(express.json());
app.post('/users', (req, res) => {
console.log(req.body);
});
NODE.JS
#1.266
Q266:
How do you serve static files in Express?
Ans:
The built-in express.static() middleware serves static files (like images, CSS, and client-side JS) from a specified directory.
Code Example
app.use(express.static('public'));
NODE.JS
#1.267
Q267:
What is the difference between req.query, req.params, and req.body in Express?
Ans:
req.query holds URL query string parameters, req.params holds named route parameters from the URL path, and req.body holds data sent in the request body (like from a POST request), typically requiring body-parsing middleware.
NODE.JS
#1.268
Q268:
How do you handle errors in synchronous Node.js code?
Ans:
You use a standard try-catch block to catch exceptions thrown during synchronous execution.
Code Example
try {
JSON.parse(invalidJson);
} catch (err) {
console.error('Parse error:', err.message);
}
NODE.JS
#1.269
Q269:
How do you handle errors with Promises?
Ans:
You attach a .catch() handler to the Promise chain, which catches any rejection from the Promise itself or any previous .then() callback in the chain.
Code Example
doAsyncTask()
.then(result => process(result))
.catch(err => console.error('Failed:', err));
NODE.JS
#1.270
Q270:
What are npm scripts and how do you run them?
Ans:
npm scripts are custom commands defined in the 'scripts' section of package.json, executed using 'npm run ' (or directly for 'start' and 'test').
Code Example
{
"scripts": {
"start": "node index.js",
"test": "jest"
}
}
// run with: npm start / npm test
NODE.JS
#1.271
Q271:
What is nodemon and why is it used?
Ans:
nodemon is a development utility that automatically restarts a Node.js application whenever file changes are detected in the project directory, speeding up the development feedback loop.
Code Example
npm install -g nodemon
nodemon app.js
NODE.JS
#1.272
Q272:
What is the difference between var, let, and const in JavaScript?
Ans:
var is function-scoped and hoisted with an initial value of undefined, let is block-scoped and hoisted without initialization (temporal dead zone), and const is block-scoped like let but cannot be reassigned after initial assignment.
Code Example
var a = 1;
let b = 2;
const c = 3;
NODE.JS
#1.273
Q273:
What are template literals in JavaScript?
Ans:
Template literals, enclosed in backticks, allow embedded expressions using ${} syntax and support multi-line strings without explicit concatenation.
Code Example
const name = 'World';
console.log(`Hello, ${name}!`);
NODE.JS
#1.274
Q274:
What is the difference between == and === in JavaScript?
Ans:
== compares values after type coercion (loose equality), while === compares both value and type without any coercion (strict equality), which is generally recommended to avoid unexpected behavior.
Code Example
console.log(0 == '0'); // true
console.log(0 === '0'); // false
NODE.JS
#1.275
Q275:
What is the os module used for in Node.js?
Ans:
The os module provides operating system-related utility methods and properties, such as os.platform(), os.cpus(), os.totalmem(), and os.freemem().
Code Example
const os = require('os');
console.log(os.cpus().length);
NODE.JS
#1.276
Q276:
What is the REPL in Node.js?
Ans:
REPL stands for Read-Eval-Print Loop; running 'node' without a filename starts an interactive shell where you can type and immediately execute JavaScript code, useful for quick experimentation.
NODE.JS
#1.277
Q277:
What is the difference between synchronous and asynchronous versions of fs module methods (naming convention)?
Ans:
Synchronous fs methods have a 'Sync' suffix (like fs.readFileSync) and block execution until complete, while their asynchronous counterparts (like fs.readFile) accept a callback or return a Promise (via fs.promises) and don't block the event loop.
NODE.JS
#1.278
Q278:
What is dotenv and why is it commonly used in Node.js projects?
Ans:
dotenv is a zero-dependency npm package that loads environment variables from a .env file into process.env, keeping sensitive configuration (like API keys and database URLs) out of source code and version control.
Code Example
// .env file: API_KEY=abc123
require('dotenv').config();
console.log(process.env.API_KEY);
NODE.JS
#1.279
Q279:
What is the difference between an HTTP 200, 201, 400, 401, 403, 404, and 500 status code?
Ans:
200 means success (OK), 201 means a resource was successfully created, 400 means bad request (client error), 401 means unauthorized (authentication required), 403 means forbidden (authenticated but not permitted), 404 means resource not found, and 500 means an internal server error occurred.
NODE.JS
#1.280
Q280:
What is the purpose of a .gitignore file in a Node.js project, and what is commonly included?
Ans:
A .gitignore file specifies files and directories that should not be tracked by Git; in Node.js projects, this typically includes node_modules/, .env files, log files, and build output directories, keeping the repository clean and free of environment-specific or generated content.
NODE.JS
#1.281
Q281:
How do you read command-line arguments passed to a Node.js script?
Ans:
Command-line arguments are available in the process.argv array, where the first two elements are the Node executable path and script path, with actual user-supplied arguments starting from index 2.
Code Example
// node script.js arg1 arg2
console.log(process.argv.slice(2)); // ['arg1', 'arg2']
NODE.JS
#1.282
Q282:
What is the difference between authentication and authorization in a Node.js API?
Ans:
Authentication verifies who a user is (e.g., via login credentials or a token), while authorization determines what an authenticated user is permitted to do (e.g., access control based on roles or permissions).
NODE.JS
#1.283
Q283:
How do you set custom response headers in Express?
Ans:
You use res.set(header, value) or res.setHeader(header, value) to add custom headers before sending the response.
Code Example
res.set('X-Custom-Header', 'value');
res.json({ ok: true });
NODE.JS
#1.284
Q284:
What is the difference between a 'dependency' and a 'devDependency' when installing with the --save-dev flag?
Ans:
Using 'npm install --save-dev' (or -D) adds the package to devDependencies, indicating it's only needed for development/build/testing, whereas the default 'npm install ' adds it to dependencies, needed at runtime in production.
REACT.JS
#1.285
Q285:
What is React.js?
Ans:
React is an open-source JavaScript library developed by Facebook (Meta) for building user interfaces, particularly single-page applications, using a component-based architecture and a virtual DOM for efficient rendering.
REACT.JS
#1.286
Q286:
Is React a framework or a library?
Ans:
React is a library focused specifically on the view layer of an application; unlike a full framework, it does not prescribe routing, state management, or HTTP handling out of the box, though these can be added via companion libraries like React Router or Redux.
REACT.JS
#1.287
Q287:
What is JSX?
Ans:
JSX (JavaScript XML) is a syntax extension for JavaScript that lets you write HTML-like markup directly within JavaScript code, which is then transpiled (typically by Babel) into React.createElement() calls.
Code Example
const element = <h1>Hello, world!</h1>;
// compiles to:
const element = React.createElement('h1', null, 'Hello, world!');
REACT.JS
#1.288
Q288:
Why do we use className instead of class in JSX?
Ans:
class is a reserved keyword in JavaScript, so JSX uses className to set the CSS class attribute on an element, which React then maps to the DOM's class attribute.
Code Example
<div className="container">Content</div>
REACT.JS
#1.289
Q289:
What is the Virtual DOM?
Ans:
The Virtual DOM is an in-memory, lightweight representation of the real DOM as a tree of JavaScript objects; React uses it to compute the minimal set of changes needed and batches updates to the real DOM for better performance.
REACT.JS
#1.290
Q290:
What is the difference between a React element and a React component?
Ans:
An element is a plain, immutable JavaScript object describing what should appear on screen (created via JSX or React.createElement), while a component is a function or class that returns elements, encapsulating logic and can accept props.
REACT.JS
#1.291
Q291:
What is the difference between functional and class components?
Ans:
Functional components are plain JavaScript functions that return JSX and use Hooks for state and lifecycle behavior, while class components extend React.Component, use this.state, and implement lifecycle methods; functional components with Hooks are now the recommended approach.
Code Example
function Greeting() {
return <h1>Hello</h1>;
}
class Greeting extends React.Component {
render() {
return <h1>Hello</h1>;
}
}
REACT.JS
#1.292
Q292:
What are props in React?
Ans:
Props (short for properties) are read-only inputs passed from a parent component to a child component, used to configure and customize how the child renders and behaves.
Code Example
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
<Welcome name="Sara" />
REACT.JS
#1.293
Q293:
What is state in React?
Ans:
State is data that is local to a component and can change over time; unlike props, state is managed within the component itself and triggers a re-render whenever it is updated.
REACT.JS
#1.294
Q294:
What is the difference between props and state?
Ans:
Props are passed in from a parent and are read-only within the receiving component, while state is owned and managed internally by the component and can be updated using setState or a state-updater function.
REACT.JS
#1.295
Q295:
What is the useState Hook?
Ans:
useState is a Hook that lets functional components hold local state; it returns a stateful value and a function to update it, and calling the updater re-renders the component with the new value.
Code Example
const [count, setCount] = useState(0);
setCount(count + 1);
REACT.JS
#1.296
Q296:
What are controlled components?
Ans:
A controlled component is a form element (like an input) whose value is driven by React state, with changes handled through an onChange handler that updates the state, making React the single source of truth.
Code Example
<input value={name} onChange={(e) => setName(e.target.value)} />
REACT.JS
#1.297
Q297:
What is conditional rendering in React?
Ans:
Conditional rendering means displaying different UI depending on certain conditions, typically implemented with JavaScript operators like ternaries, logical &&, or early returns within JSX.
Code Example
{isLoggedIn ? <Dashboard /> : <Login />}
{hasError && <ErrorMessage />}
REACT.JS
#1.298
Q298:
What are React Fragments?
Ans:
Fragments ( or the shorthand <>) let you group a list of children without adding an extra node to the DOM, useful when a component must return multiple elements without a wrapping div.
Code Example
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
REACT.JS
#1.299
Q299:
What is React Router used for?
Ans:
React Router is the most widely used routing library for React, enabling client-side navigation between different views/components based on the URL without triggering a full page reload.
Code Example
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
REACT.JS
#1.300
Q300:
What are React DevTools and what are they used for?
Ans:
React DevTools is a browser extension that lets you inspect the React component tree, view and edit props/state in real time, and profile component render performance to find unnecessary re-renders.
REACT.JS
#1.301
Q301:
What is the significance of children prop in React?
Ans:
props.children is a special prop that contains whatever is nested between a component's opening and closing tags, allowing components to be composed and to wrap arbitrary content passed by their parent.
Code Example
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card><p>Hello</p></Card>
REACT.JS
#1.302
Q302:
How does event handling differ in React compared to plain HTML/DOM?
Ans:
In React, event handlers are passed as camelCase props (like onClick) referencing functions rather than strings, and React attaches a single listener at the root and uses event delegation internally instead of attaching a listener to every DOM node.
Code Example
<button onClick={() => alert('Clicked')}>Click</button>
REACT.JS
#1.303
Q303:
What is the significance of e.preventDefault() in React event handlers?
Ans:
Calling e.preventDefault() inside a React event handler prevents the browser's default behavior for that event, such as stopping a form's default page-reload submission, just as it does with native DOM events.
Code Example
const handleSubmit = e => {
e.preventDefault();
submitForm();
};
REACT.JS
#1.304
Q304:
What are Prop Types and why use them?
Ans:
PropTypes is a runtime type-checking library for React props, letting developers document and validate the expected type and shape of props during development, producing console warnings when a mismatch occurs (largely superseded by TypeScript in modern codebases).
Code Example
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
};
REACT.JS
#1.305
Q305:
What is the significance of the key error 'Each child in a list should have a unique key prop'?
Ans:
This warning appears when rendering an array of elements without a key prop, which React needs to efficiently track identity across re-renders; while the app will typically still function, missing keys can lead to subtle bugs when the list changes.
REACT.JS
#1.306
Q306:
How do you update an object in state immutably?
Ans:
You create a new object using the spread operator (or Object.assign) that copies existing properties and overrides the ones that changed, rather than mutating the original object directly.
Code Example
setUser(prev => ({ ...prev, name: 'New Name' }));
ANGULAR.JS
#1.307
Q307:
What is Angular?
Ans:
Angular is a TypeScript-based, open-source front-end framework maintained by Google for building single-page applications, providing a complete solution including templating, dependency injection, routing, forms, and HTTP handling out of the box.
ANGULAR.JS
#1.308
Q308:
What is the difference between AngularJS and Angular?
Ans:
AngularJS (version 1.x) is the original JavaScript-based MVC framework released in 2010, while Angular (version 2 and above) is a complete rewrite in TypeScript with a component-based architecture, improved performance, and mobile support; they are largely incompatible with each other.
ANGULAR.JS
#1.309
Q309:
Why does Angular use TypeScript?
Ans:
TypeScript adds static typing, interfaces, and decorators to JavaScript, enabling compile-time error checking, better tooling and autocompletion, and clearer contracts between components, which Angular relies on heavily for features like dependency injection metadata.
ANGULAR.JS
#1.310
Q310:
What is a component in Angular?
Ans:
A component is the fundamental building block of an Angular UI, defined by a class decorated with @Component that specifies an HTML template, associated styles, and a selector used to instantiate it within other templates.
Code Example
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html'
})
export class HeroComponent {}
ANGULAR.JS
#1.311
Q311:
What is a module (NgModule) in Angular?
Ans:
An NgModule is a class decorated with @NgModule that groups related components, directives, pipes, and services together, declaring what belongs to the module and what external modules it depends on via the imports array.
Code Example
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule {}
ANGULAR.JS
#1.312
Q312:
What is data binding in Angular?
Ans:
Data binding is the mechanism that synchronizes data between a component's TypeScript class and its HTML template; Angular supports interpolation, property binding, event binding, and two-way binding.
ANGULAR.JS
#1.313
Q313:
What is interpolation in Angular?
Ans:
Interpolation uses double curly braces {{ }} to embed a component's property value directly into the template's text content, evaluated and inserted as a string.
Code Example
<p>Hello, {{ userName }}!</p>
ANGULAR.JS
#1.314
Q314:
What is property binding in Angular?
Ans:
Property binding, using square brackets [property], sets a DOM element's property or a directive/component's input property to the value of a component's expression, flowing data one-way from the class to the template.
Code Example
<img [src]="imageUrl">
ANGULAR.JS
#1.315
Q315:
What is event binding in Angular?
Ans:
Event binding, using parentheses (event), listens for a DOM event (like click) or a custom component event and calls a method on the component class when it fires.
Code Example
<button (click)="onSave()">Save</button>
ANGULAR.JS
#1.316
Q316:
What is two-way data binding in Angular?
Ans:
Two-way binding, using the banana-in-a-box syntax [(ngModel)], combines property and event binding so that changes in the UI update the component property and changes to the property update the UI simultaneously.
Code Example
<input [(ngModel)]="userName">
ANGULAR.JS
#1.317
Q317:
What does *ngIf do?
Ans:
*ngIf is a structural directive that conditionally adds or completely removes an element (and its subtree) from the DOM based on a boolean expression, unlike CSS-based hiding which keeps the element in the DOM.
Code Example
<div *ngIf="isLoggedIn">Welcome back!</div>
ANGULAR.JS
#1.318
Q318:
What does *ngFor do?
Ans:
*ngFor is a structural directive that repeats a template for each item in a collection, commonly used with the index and trackBy for performance optimization.
Code Example
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
ANGULAR.JS
#1.319
Q319:
What is ngClass used for?
Ans:
ngClass dynamically adds or removes CSS classes on an element based on an expression, object, or array, letting class names change in response to component state.
Code Example
<div [ngClass]="{ active: isActive, disabled: isDisabled }"></div>
ANGULAR.JS
#1.320
Q320:
What is ngStyle used for?
Ans:
ngStyle dynamically sets inline CSS styles on an element based on an object whose keys are style properties and values are expressions evaluated from the component.
Code Example
<div [ngStyle]="{ color: textColor, 'font-size.px': fontSize }"></div>
ANGULAR.JS
#1.321
Q321:
What are pipes in Angular?
Ans:
Pipes are simple functions used in templates to transform displayed data, such as formatting dates, numbers, or currency, applied using the pipe operator (|).
Code Example
<p>{{ birthday | date:'longDate' }}</p>
<p>{{ price | currency:'USD' }}</p>
ANGULAR.JS
#1.322
Q322:
What are Angular services used for?
Ans:
Services are classes with a focused, well-defined purpose (like fetching data, logging, or sharing state) that are injected into components or other services, promoting separation of concerns and code reuse instead of putting business logic directly in components.
ANGULAR.JS
#1.323
Q323:
What is the HttpClient module used for?
Ans:
HttpClient is Angular's built-in service for making HTTP requests, returning Observables for requests, and supporting features like interceptors, typed responses, and testing utilities via HttpClientTestingModule.
Code Example
this.http.get<User[]>('/api/users').subscribe(users => this.users = users);
ANGULAR.JS
#1.324
Q324:
What is the difference between @Input and @Output?
Ans:
@Input marks a property that receives data from a parent component via property binding, while @Output marks an EventEmitter property that lets a component emit custom events upward to a parent, which listens for them using event binding.
Code Example
@Input() userName: string;
@Output() save = new EventEmitter<void>();
ANGULAR.JS
#1.325
Q325:
What is Angular's Router used for?
Ans:
The Angular Router enables navigation between different views/components based on the URL in a single-page application, supporting features like route parameters, guards, lazy loading, and nested/child routes.
Code Example
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'users/:id', component: UserDetailComponent }
];
ANGULAR.JS
#1.326
Q326:
What is the purpose of the Angular CLI?
Ans:
The Angular CLI is a command-line tool that scaffolds new projects, generates components/services/modules with the correct boilerplate and file structure, and manages building, testing, and serving the application through commands like ng generate, ng build, and ng serve.
Code Example
ng generate component user-profile
ng build --configuration production
ng serve
ANGULAR.JS
#1.327
Q327:
What is the difference between Angular and React at a high level?
Ans:
Angular is a complete, opinionated framework providing routing, forms, HTTP client, and dependency injection out of the box using TypeScript and a component/module system, while React is a focused UI library that requires selecting and integrating separate libraries for routing, state management, and other concerns.
SQL
#1.328
Q328:
What is SQL?
Ans:
SQL (Structured Query Language) is a standard language used to create, query, update, and manage data stored in relational database management systems (RDBMS) like MySQL, PostgreSQL, SQL Server, and Oracle.
SQL
#1.329
Q329:
What is the difference between SQL and MySQL?
Ans:
SQL is a standardized query language for interacting with relational databases, while MySQL is a specific open-source RDBMS software that implements SQL (with some vendor-specific extensions) to store and manage data.
SQL
#1.330
Q330:
What are the different types of SQL commands?
Ans:
SQL commands are grouped into DDL (Data Definition Language: CREATE, ALTER, DROP), DML (Data Manipulation Language: SELECT, INSERT, UPDATE, DELETE), DCL (Data Control Language: GRANT, REVOKE), and TCL (Transaction Control Language: COMMIT, ROLLBACK, SAVEPOINT).
SQL
#1.331
Q331:
What is the difference between DDL and DML?
Ans:
DDL statements define or modify database structure (tables, schemas, indexes) and are auto-committed, while DML statements manipulate the actual data within tables (inserting, updating, deleting, or querying rows) and can typically be rolled back within a transaction.
Code Example
-- DDL
CREATE TABLE users (id INT, name VARCHAR(50));
-- DML
INSERT INTO users VALUES (1, 'Sara');
SQL
#1.332
Q332:
What is a primary key?
Ans:
A primary key is a column or set of columns that uniquely identifies each row in a table; it cannot contain NULL values and a table can have only one primary key.
Code Example
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50)
);
SQL
#1.333
Q333:
What is a foreign key?
Ans:
A foreign key is a column (or set of columns) in one table that references the primary key of another table, enforcing referential integrity by ensuring the referenced value actually exists in the parent table.
Code Example
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
SQL
#1.334
Q334:
What is a NULL value in SQL?
Ans:
NULL represents missing, unknown, or inapplicable data; it is not equal to zero, an empty string, or any other value, and comparisons with NULL using = or != always evaluate to unknown rather than true or false, which is why IS NULL / IS NOT NULL must be used.
Code Example
SELECT * FROM users WHERE phone IS NULL;
SQL
#1.335
Q335:
What is the difference between INNER JOIN and LEFT JOIN?
Ans:
INNER JOIN returns only rows that have matching values in both joined tables, while LEFT JOIN returns all rows from the left table regardless of a match, filling in NULLs for columns from the right table when no match exists.
Code Example
SELECT c.name, o.id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id;
SQL
#1.336
Q336:
What are aggregate functions in SQL?
Ans:
Aggregate functions perform a calculation across a set of rows and return a single value, including COUNT(), SUM(), AVG(), MIN(), and MAX(), commonly used together with GROUP BY.
Code Example
SELECT dept, AVG(salary) FROM employees GROUP BY dept;
SQL
#1.337
Q337:
What is the GROUP BY clause used for?
Ans:
GROUP BY groups rows that share the same values in specified columns into summary rows, typically used together with aggregate functions to compute per-group statistics like totals or averages.
Code Example
SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;
SQL
#1.338
Q338:
What is the difference between COUNT(*) and COUNT(column_name)?
Ans:
COUNT(*) counts all rows regardless of NULL values, while COUNT(column_name) counts only the rows where that specific column's value is not NULL.
Code Example
SELECT COUNT(*), COUNT(phone) FROM users;
SQL
#1.339
Q339:
What is the difference between COMMIT and ROLLBACK?
Ans:
COMMIT permanently saves all changes made during the current transaction to the database, while ROLLBACK undoes all changes made since the transaction began (or since the last savepoint), restoring the previous state.
Code Example
COMMIT;
-- or
ROLLBACK;
SQL
#1.340
Q340:
What are constraints in SQL?
Ans:
Constraints are rules enforced on table columns to maintain data integrity, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, preventing invalid data from being inserted or updated.
Code Example
CREATE TABLE products (
id INT PRIMARY KEY,
price DECIMAL(10,2) CHECK (price > 0)
);
SQL
#1.341
Q341:
What is the DEFAULT constraint used for?
Ans:
The DEFAULT constraint specifies a value to automatically use for a column when no explicit value is provided during an INSERT, ensuring consistent fallback values without requiring application-level logic.
Code Example
CREATE TABLE orders (
id INT PRIMARY KEY,
status VARCHAR(20) DEFAULT 'pending'
);
SQL
#1.342
Q342:
What is the ORDER BY clause used for?
Ans:
ORDER BY sorts the rows of a query's result set by one or more columns, ascending (ASC, the default) or descending (DESC).
Code Example
SELECT * FROM products ORDER BY price DESC;
SQL
#1.343
Q343:
What is the LIMIT (or TOP/FETCH) clause used for?
Ans:
LIMIT (MySQL/PostgreSQL) or TOP (SQL Server) or FETCH FIRST (standard SQL/Oracle) restricts the number of rows returned by a query, commonly combined with ORDER BY for pagination or 'top N' style queries.
Code Example
SELECT * FROM products ORDER BY price DESC LIMIT 10;
SQL
#1.344
Q344:
What are wildcard characters in SQL LIKE?
Ans:
% matches any sequence of zero or more characters, and _ matches exactly one character, both used within a LIKE pattern to perform flexible partial string matching.
Code Example
SELECT * FROM products WHERE name LIKE 'App%';
SQL
#1.345
Q345:
What is the difference between BETWEEN and comparison operators?
Ans:
BETWEEN is inclusive shorthand for checking whether a value falls within a range (equivalent to >= AND <=), improving readability compared to writing out two separate comparison conditions.
Code Example
SELECT * FROM orders WHERE order_date BETWEEN '2026-01-01' AND '2026-01-31';
SQL
#1.346
Q346:
What is an ER (Entity-Relationship) diagram?
Ans:
An ER diagram is a visual representation of a database's entities (tables), their attributes (columns), and the relationships between them (one-to-one, one-to-many, many-to-many), commonly used during database design.
SQL
#1.347
Q347:
What is the purpose of the ALTER TABLE statement?
Ans:
ALTER TABLE modifies an existing table's structure, such as adding, dropping, or modifying columns, adding or removing constraints, or renaming the table, without needing to drop and recreate it.
Code Example
ALTER TABLE users ADD COLUMN age INT;
ALTER TABLE users DROP COLUMN age;
SQL
#1.348
Q348:
What are the ANSI SQL date/time functions commonly used for?
Ans:
Common date/time functions include NOW()/CURRENT_TIMESTAMP for the current date and time, DATEADD/DATE_ADD for adding intervals, DATEDIFF for calculating the difference between two dates, and EXTRACT for pulling out a specific part (like year or month) from a date value.
Code Example
SELECT DATEDIFF(NOW(), created_at) AS days_since_signup FROM users;
SQL
#1.349
Q349:
What is MySQL?
Ans:
MySQL is an open-source relational database management system (RDBMS) that uses SQL to store, manage, and retrieve data, widely used in web applications for its speed, reliability, and free licensing.
SQL
#1.350
Q350:
What is the current stable version of MySQL?
Ans:
MySQL 8.0 is the current major stable version, which introduced features like window functions, common table expressions (CTEs), improved JSON support, and better default security compared to MySQL 5.7.
SQL
#1.351
Q351:
What is the difference between a primary key and a foreign key?
Ans:
A primary key uniquely identifies each row within its own table and cannot be NULL, while a foreign key is a column in one table that references the primary key of another table, establishing and enforcing a relationship between the two tables.
SQL
#1.352
Q352:
Can a table have multiple primary keys?
Ans:
No, a table can have only one primary key, though that primary key can be composite, meaning it spans multiple columns that together uniquely identify each row.
Medium
661 questions
PHP
#2.1
Q1:
What is the difference between define() and const?
Ans:
const is a language construct evaluated at compile time and used outside functions, while define() is a function evaluated at runtime and can be used conditionally inside functions.
PHP
#2.2
Q2:
What is the difference between isset() and empty()?
Ans:
isset() returns false only if the variable is not set or is null, while empty() also returns true for falsy values like 0, '', and false even if the variable is set.
PHP
#2.3
Q3:
What is the difference between include and require?
Ans:
If the file is not found, include produces a warning and the script continues, while require produces a fatal error and stops script execution.
PHP
#2.4
Q4:
What is the difference between include_once and include?
Ans:
include_once checks whether the file has already been included and skips it if so, preventing redeclaration errors, while include will include the file every time it's called.
PHP
#2.5
Q5:
What is the null coalescing operator?
Ans:
The ?? operator returns its first operand if it exists and is not null, otherwise it returns the second operand; it is a shorthand for isset() checks.
Code Example
$name = $_GET['name'] ?? 'Guest';
PHP
#2.6
Q6:
What is the null coalescing assignment operator?
Ans:
The ??= operator, introduced in PHP 7.4, assigns the right-hand value to the variable only if the variable is null or not set.
Code Example
$data['count'] ??= 0;
PHP
#2.7
Q7:
What is the spaceship operator in PHP?
Ans:
The spaceship operator (<=>) compares two expressions and returns -1, 0, or 1 depending on whether the left operand is less than, equal to, or greater than the right.
Code Example
echo 1 <=> 2; // -1
PHP
#2.8
Q8:
What is type juggling in PHP?
Ans:
Type juggling is PHP's automatic conversion of a variable's data type based on context, such as converting a numeric string to an integer during arithmetic operations.
Code Example
echo '5' + 3; // 8
PHP
#2.9
Q9:
What is type casting in PHP and how is it done?
Ans:
Type casting is explicitly converting a variable to another type by prefixing it with the desired type in parentheses.
Code Example
$num = (int) '123abc'; // 123
PHP
#2.10
Q10:
What is the difference between var_dump() and print_r()?
Ans:
print_r() displays a human-readable representation of a variable's value (mainly arrays/objects) without showing types, while var_dump() shows both the type and value with more detail.
PHP
#2.11
Q11:
How does PHP handle boolean conversion of values like '0' and empty string?
Ans:
In boolean context, 0, '0', '', empty array, and NULL are considered false; all other values, including '0.0' and whitespace strings, are considered true.
PHP
#2.12
Q12:
What is the PHP_EOL constant used for?
Ans:
PHP_EOL is a predefined constant representing the correct end-of-line sequence for the current operating system (\n on Unix, \r\n on Windows).
PHP
#2.13
Q13:
What is the difference between and/or and &&/||?
Ans:
They function the same logically, but && and || have higher precedence than and/or, which can affect how expressions are evaluated, especially with assignment.
PHP
#2.14
Q14:
How does the increment operator behave on strings?
Ans:
PHP's ++ operator can increment alphanumeric strings (e.g., 'a' becomes 'b', 'z' becomes 'aa'), following Perl-style string increment rules.
Code Example
$s = 'a'; $s++; echo $s; // 'b'
PHP
#2.15
Q15:
What is the match expression introduced in PHP 8?
Ans:
match is similar to switch but uses strict comparison, returns a value directly, requires no break statements, and throws an UnhandledMatchError if no case matches.
Code Example
$result = match($status) {
1, 2 => 'active',
0 => 'inactive',
default => 'unknown',
};
PHP
#2.16
Q16:
What is the difference between switch and match?
Ans:
match uses strict (===) comparison and is an expression that returns a value, while switch uses loose comparison, requires break to prevent fall-through, and is a statement.
PHP
#2.17
Q17:
How do you loop through an array by reference using foreach?
Ans:
You prefix the value variable with an ampersand (&) so modifications inside the loop affect the original array.
Code Example
foreach ($arr as &$val) { $val *= 2; }
unset($val);
PHP
#2.18
Q18:
What is the goto statement in PHP?
Ans:
goto allows jumping to another section of code marked by a label; it is rarely used because it can make code harder to follow.
PHP
#2.19
Q19:
What is a variadic function in PHP?
Ans:
A variadic function accepts a variable number of arguments using the ... operator, which collects them into an array.
Code Example
function sum(...$nums) { return array_sum($nums); }
PHP
#2.20
Q20:
How do you pass arguments by reference in PHP?
Ans:
Prefixing a parameter with an ampersand (&) passes it by reference so changes inside the function affect the original variable.
Code Example
function increment(&$num) { $num++; }
PHP
#2.21
Q21:
What is the difference between passing by value and by reference?
Ans:
Passing by value copies the argument so changes inside the function don't affect the original variable, while passing by reference lets the function modify the original variable directly.
PHP
#2.22
Q22:
Can PHP functions return multiple values?
Ans:
PHP functions can return an array or a list, and PHP 7.1+ supports list()/short array destructuring to unpack multiple returned values.
Code Example
function coords() { return [1, 2]; }
[$x, $y] = coords();
PHP
#2.23
Q23:
What is a recursive function?
Ans:
A recursive function is one that calls itself to solve smaller instances of the same problem, typically requiring a base case to stop recursion.
Code Example
function factorial($n) {
return $n <= 1 ? 1 : $n * factorial($n - 1);
}
PHP
#2.24
Q24:
What is an anonymous function (closure) in PHP?
Ans:
An anonymous function is a function without a name, often assigned to a variable or passed as a callback, defined using the function keyword or arrow syntax.
Code Example
$square = function($n) { return $n * $n; };
echo $square(4);
PHP
#2.25
Q25:
What is a closure's 'use' clause for?
Ans:
The use clause allows an anonymous function to inherit variables from the parent scope by value or by reference.
Code Example
$factor = 2;
$multiply = function($n) use ($factor) { return $n * $factor; };
PHP
#2.26
Q26:
What are arrow functions in PHP?
Ans:
Introduced in PHP 7.4, arrow functions (fn) provide a concise syntax and automatically capture outer scope variables by value.
Code Example
$multiply = fn($n) => $n * 2;
PHP
#2.27
Q27:
What is the difference between closures and arrow functions?
Ans:
Arrow functions automatically capture variables from the parent scope without needing 'use', while regular closures must explicitly import outer variables via use(); arrow functions are also limited to a single expression body.
PHP
#2.28
Q28:
What are type declarations (type hints) in PHP functions?
Ans:
Type declarations specify the expected data type of function parameters and return values, enforced at runtime, improving code reliability.
Code Example
function add(int $a, int $b): int {
return $a + $b;
}
PHP
#2.29
Q29:
What is strict_types in PHP?
Ans:
Declaring strict_types=1 at the top of a file enforces strict type checking for scalar type declarations, disabling automatic type coercion in that file.
Code Example
declare(strict_types=1);
PHP
#2.30
Q30:
What are nullable types in PHP?
Ans:
A nullable type is denoted by a question mark before the type (e.g., ?int) indicating the parameter or return value can be either that type or null.
Code Example
function find(?int $id): ?array { ... }
PHP
#2.31
Q31:
What is a callable in PHP?
Ans:
A callable is any PHP value that can be called as a function, such as a string function name, an array [object, method], or a Closure.
PHP
#2.32
Q32:
How do you call a function dynamically using a variable?
Ans:
You can store a function name in a variable and call it by appending parentheses, known as variable functions.
Code Example
function hello() { echo 'Hi'; }
$fn = 'hello';
$fn();
PHP
#2.33
Q33:
What are named arguments in PHP 8?
Ans:
Named arguments allow passing values to a function by specifying the parameter name, so arguments can be supplied in any order and optional ones can be skipped.
Code Example
function createUser(string $name, int $age = 18) {}
createUser(age: 25, name: 'Tom');
PHP
#2.34
Q34:
How do you set a default return type of void in PHP?
Ans:
You declare the function's return type as void to indicate it returns no meaningful value; PHP will error if such a function tries to return a value.
Code Example
function logMessage(string $msg): void {
echo $msg;
}
PHP
#2.35
Q35:
What is the difference between array_merge() and the + operator for arrays?
Ans:
array_merge() re-indexes numeric keys and later values overwrite earlier string keys, while the + operator preserves the original keys and only adds keys from the second array that don't already exist.
Code Example
print_r(array_merge([1,2],[3,4])); // [1,2,3,4]
print_r([1,2] + [0=>9,2=>3]); // [1,2,3]
PHP
#2.36
Q36:
What is the difference between sort() and asort()?
Ans:
sort() sorts values and reindexes keys numerically, while asort() sorts values but preserves the original key-value association.
PHP
#2.37
Q37:
What is the difference between sort() and ksort()?
Ans:
sort() sorts an array by its values, while ksort() sorts an array by its keys, both in ascending order.
PHP
#2.38
Q38:
What does usort() do?
Ans:
usort() sorts an array using a user-defined comparison callback function and reindexes the array's keys.
Code Example
usort($people, fn($a, $b) => $a['age'] <=> $b['age']);
PHP
#2.39
Q39:
What is the difference between usort() and uasort()?
Ans:
usort() reindexes the array after sorting, while uasort() preserves the original keys, making it suitable for associative arrays.
PHP
#2.40
Q40:
What does array_map() do?
Ans:
array_map() applies a callback function to every element of one or more arrays and returns a new array with the results.
Code Example
$squares = array_map(fn($n) => $n * $n, [1,2,3]);
PHP
#2.41
Q41:
What does array_filter() do?
Ans:
array_filter() filters elements of an array using a callback function, returning only elements for which the callback returns true, and preserves original keys.
Code Example
$even = array_filter([1,2,3,4], fn($n) => $n % 2 == 0);
PHP
#2.42
Q42:
What does array_reduce() do?
Ans:
array_reduce() iteratively reduces an array to a single value using a callback function and an optional initial value.
Code Example
$total = array_reduce([1,2,3], fn($carry, $item) => $carry + $item, 0);
PHP
#2.43
Q43:
What is the difference between array_map, array_filter, and array_reduce?
Ans:
array_map transforms every element and returns an array of the same size, array_filter selects a subset of elements based on a condition, and array_reduce collapses the array into a single accumulated value.
PHP
#2.44
Q44:
What is the difference between array_slice() and array_splice()?
Ans:
array_slice() returns a portion of the array without modifying the original, while array_splice() removes and optionally replaces a portion of the array, modifying it in place.
PHP
#2.45
Q45:
How do you combine two arrays into key-value pairs?
Ans:
array_combine() creates an array using one array's values as keys and another array's values as values.
Code Example
$combined = array_combine(['a','b'], [1,2]); // ['a'=>1,'b'=>2]
PHP
#2.46
Q46:
What is the spread operator in array context?
Ans:
The ... operator can unpack an array's elements into another array literal or function call arguments.
Code Example
$a = [1, 2];
$b = [0, ...$a, 3]; // [0,1,2,3]
PHP
#2.47
Q47:
What does array_column() do?
Ans:
array_column() returns the values from a single column of an input array of arrays or objects, optionally indexed by another column.
Code Example
$names = array_column($users, 'name');
PHP
#2.48
Q48:
What is list() used for?
Ans:
list() (or its short syntax []) assigns variables from an array's elements in a single statement, useful for destructuring.
Code Example
[$a, $b] = [1, 2];
PHP
#2.49
Q49:
What is the difference between array_walk() and foreach?
Ans:
array_walk() applies a callback to each element and can pass elements by reference to directly modify the original array, while foreach is a language construct for iteration that requires an explicit reference to modify elements.
PHP
#2.50
Q50:
How do you check if a string starts or ends with a specific substring?
Ans:
str_starts_with() and str_ends_with(), introduced in PHP 8, check whether a string begins or ends with a given substring.
Code Example
var_dump(str_starts_with('hello world', 'hello')); // true
PHP
#2.51
Q51:
How do you check if a string contains a substring?
Ans:
str_contains(), introduced in PHP 8, returns true if the needle string is found within the haystack string.
Code Example
var_dump(str_contains('Hello World', 'World'));
PHP
#2.52
Q52:
How does sprintf() work?
Ans:
sprintf() returns a formatted string according to a format specifier string containing placeholders like %s, %d, or %f.
Code Example
echo sprintf('%s is %d years old', 'Tom', 25);
PHP
#2.53
Q53:
What is the difference between sprintf() and printf()?
Ans:
sprintf() returns the formatted string, while printf() outputs the formatted string directly and returns the length of the output string.
PHP
#2.54
Q54:
How do you pad a string to a certain length?
Ans:
str_pad() pads a string on the left, right, or both sides to a specified length using a given padding string.
Code Example
echo str_pad('5', 3, '0', STR_PAD_LEFT); // '005'
PHP
#2.55
Q55:
What is heredoc and nowdoc syntax?
Ans:
Heredoc (<<
Code Example
$name='World';
echo <<<EOT
Hello $name
EOT;
PHP
#2.56
Q56:
What is a destructor in PHP?
Ans:
The __destruct() method is called automatically when an object is destroyed or the script ends, useful for cleanup tasks.
PHP
#2.57
Q57:
What are constructor property promotion in PHP 8?
Ans:
Constructor property promotion lets you declare and initialize class properties directly in the constructor's parameter list, reducing boilerplate.
Code Example
class Point {
public function __construct(
public float $x,
public float $y
) {}
}
PHP
#2.58
Q58:
What is method overriding in PHP?
Ans:
Method overriding occurs when a child class redefines a method that already exists in its parent class, replacing its behavior.
Code Example
class Animal { function sound(){ echo 'Some sound'; } }
class Cat extends Animal { function sound(){ echo 'Meow'; } }
PHP
#2.59
Q59:
What is an abstract class?
Ans:
An abstract class cannot be instantiated directly and may contain abstract methods that must be implemented by any concrete subclass.
Code Example
abstract class Shape {
abstract public function area(): float;
}
PHP
#2.60
Q60:
What is an interface in PHP?
Ans:
An interface defines a contract of method signatures that implementing classes must provide, without any implementation itself.
Code Example
interface Shape {
public function area(): float;
}
class Circle implements Shape {
public function area(): float { return 3.14 * $this->r ** 2; }
}
PHP
#2.61
Q61:
What is the difference between an abstract class and an interface?
Ans:
An abstract class can have both implemented and abstract methods along with properties and constructors, while an interface only declares method signatures (and constants) and a class can implement multiple interfaces but extend only one class.
PHP
#2.62
Q62:
Can a class implement multiple interfaces in PHP?
Ans:
Yes, a class can implement multiple interfaces separated by commas, though it can only extend a single parent class.
Code Example
class Bird implements Flyable, Swimmable {}
PHP
#2.63
Q63:
What is a trait in PHP?
Ans:
A trait is a mechanism for code reuse that allows methods to be included in multiple classes without using inheritance, addressing PHP's single inheritance limitation.
Code Example
trait Loggable {
function log($msg) { echo $msg; }
}
class Order { use Loggable; }
PHP
#2.64
Q64:
What is a static property or method?
Ans:
Static members belong to the class itself rather than any instance, accessed using the scope resolution operator (::), and shared across all instances.
Code Example
class Counter {
public static int $count = 0;
public static function increment() { self::$count++; }
}
PHP
#2.65
Q65:
What is the purpose of the final keyword?
Ans:
The final keyword prevents a class from being extended or a method from being overridden by child classes.
Code Example
final class Config {}
class Base { final function init(){} }
PHP
#2.66
Q66:
What is an abstract method?
Ans:
An abstract method is declared without a body inside an abstract class or interface, and must be implemented by any non-abstract subclass.
PHP
#2.67
Q67:
What is polymorphism in PHP OOP?
Ans:
Polymorphism allows objects of different classes to be treated through a common interface, with each class providing its own implementation of shared methods.
PHP
#2.68
Q68:
What is the __toString() magic method?
Ans:
__toString() allows an object to be converted to a string representation, automatically called when the object is used in a string context like echo.
Code Example
class Money {
function __toString(): string { return '$' . $this->amount; }
}
PHP
#2.69
Q69:
What is the difference between an object clone and assignment?
Ans:
Assigning an object variable to another copies the reference (both point to the same object), while clone creates a new, independent object with copied properties.
PHP
#2.70
Q70:
What are namespaces in PHP?
Ans:
Namespaces organize code into logical groups and prevent naming collisions between classes, functions, or constants with the same name.
Code Example
namespace App\Models;
class User {}
// usage: new \App\Models\User();
PHP
#2.71
Q71:
What is dependency injection?
Ans:
Dependency injection is a design pattern where an object's dependencies are provided externally (often through the constructor) rather than being created internally, improving testability and decoupling.
Code Example
class OrderService {
public function __construct(private PaymentGateway $gateway) {}
}
PHP
#2.72
Q72:
What is the Singleton design pattern in PHP?
Ans:
Singleton ensures a class has only one instance and provides a global access point to it, typically implemented with a private constructor and a static getInstance() method.
Code Example
class DB {
private static ?DB $instance = null;
private function __construct(){}
public static function getInstance(): DB {
return self::$instance ??= new self();
}
}
PHP
#2.73
Q73:
What are readonly properties in PHP 8.1?
Ans:
Readonly properties can be initialized only once, typically in the constructor, and throw an error if modified afterward, enforcing immutability.
Code Example
class Point {
public function __construct(public readonly int $x, public readonly int $y) {}
}
PHP
#2.74
Q74:
What are enums in PHP 8.1?
Ans:
Enums are a new type that defines a fixed set of possible values (cases) for a variable, improving type safety compared to using class constants.
Code Example
enum Status {
case Active;
case Inactive;
}
$s = Status::Active;
PHP
#2.75
Q75:
What is the difference between a pure enum and a backed enum?
Ans:
A pure enum's cases have no associated scalar value, while a backed enum assigns each case a string or int value that can be retrieved and used for serialization.
Code Example
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
}
PHP
#2.76
Q76:
What is the difference between an error and an exception in PHP?
Ans:
Errors typically represent serious problems (like fatal errors) historically not catchable, while exceptions are objects representing runtime issues that can be caught with try-catch; since PHP 7, most errors are represented by Error objects implementing Throwable, so both can be caught.
PHP
#2.77
Q77:
How do you throw a custom exception?
Ans:
You create a class extending Exception (or a subclass) and use the throw keyword to raise an instance of it.
Code Example
class InsufficientFundsException extends Exception {}
throw new InsufficientFundsException('Not enough balance');
PHP
#2.78
Q78:
What is the purpose of the finally block?
Ans:
The finally block contains code that executes after the try/catch blocks regardless of whether an exception was thrown or caught, commonly used for cleanup like closing files or connections.
PHP
#2.79
Q79:
Can you catch multiple exception types in a single catch block?
Ans:
Yes, PHP 7.1+ allows specifying multiple exception types separated by a pipe (|) in a single catch block.
Code Example
try {
// code
} catch (TypeError | ValueError $e) {
echo $e->getMessage();
}
PHP
#2.80
Q80:
What methods does the Exception class provide?
Ans:
Common methods include getMessage(), getCode(), getFile(), getLine(), getTrace(), and getTraceAsString() to inspect details about the thrown exception.
PHP
#2.81
Q81:
What is error suppression using the @ operator, and why is it discouraged?
Ans:
Prefixing an expression with @ suppresses any error messages it generates, but it is discouraged because it hides real problems and can make debugging difficult; using proper error handling is preferred.
PHP
#2.82
Q82:
How do you read a file line by line?
Ans:
You can use fgets() in a loop while the file pointer is not at the end (feof()), or use the file() function to read all lines into an array.
Code Example
$handle = fopen('data.txt', 'r');
while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);
PHP
#2.83
Q83:
How do you upload a file in PHP?
Ans:
Uploaded files are accessible via the $_FILES superglobal, and move_uploaded_file() moves the temporary uploaded file to a permanent destination.
Code Example
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/photo.jpg');
PHP
#2.84
Q84:
How do you get information about a file (size, modification time)?
Ans:
filesize() returns the file size in bytes, and filemtime() returns the last modification time as a Unix timestamp.
PHP
#2.85
Q85:
What is the difference between copy() and rename() for files?
Ans:
copy() duplicates a file to a new location while keeping the original, whereas rename() moves or renames a file, removing it from its original location.
PHP
#2.86
Q86:
What is $_REQUEST used for?
Ans:
$_REQUEST is an array containing the contents of $_GET, $_POST, and $_COOKIE combined, though its use is often discouraged due to ambiguity about the data's source.
PHP
#2.87
Q87:
How do you retrieve form data safely in PHP?
Ans:
You should validate and sanitize input using functions like filter_var(), and use htmlspecialchars() when outputting user data to prevent XSS.
Code Example
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
PHP
#2.88
Q88:
What is filter_var() used for?
Ans:
filter_var() filters or validates a variable using a specified filter, such as validating an email address, URL, or integer.
Code Example
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo 'valid'; }
PHP
#2.89
Q89:
How do you prevent Cross-Site Scripting (XSS) when displaying user input?
Ans:
You should escape output using htmlspecialchars() or htmlentities() to convert special characters into HTML entities before displaying user-supplied data.
Code Example
echo htmlspecialchars($_POST['comment']);
PHP
#2.90
Q90:
What is $GLOBALS in PHP?
Ans:
$GLOBALS is a superglobal array that provides access to all variables defined in the global scope from within any function.
Code Example
$x = 10;
function show() { echo $GLOBALS['x']; }
PHP
#2.91
Q91:
How do you access command-line arguments in a PHP script?
Ans:
The $argv array holds command-line arguments passed to the script, and $argc holds the count of arguments, available when running PHP via CLI.
PHP
#2.92
Q92:
What is $_ENV used for?
Ans:
$_ENV contains variables provided to the script via the environment, such as environment variables set on the server or in a .env configuration.
PHP
#2.93
Q93:
What is the difference between sessions and cookies?
Ans:
Sessions store data on the server and reference it via a session ID cookie on the client, making them more secure for sensitive data, while cookies store data directly on the client's browser with a size limitation.
PHP
#2.94
Q94:
What are HttpOnly and Secure cookie flags?
Ans:
The HttpOnly flag prevents client-side JavaScript from accessing the cookie, mitigating XSS-based theft, while the Secure flag ensures the cookie is only sent over HTTPS connections.
PHP
#2.95
Q95:
How can you configure session expiration and lifetime?
Ans:
You can adjust settings like session.gc_maxlifetime in php.ini or set a custom cookie lifetime via session_set_cookie_params() before starting the session.
PHP
#2.96
Q96:
What is the difference between MySQLi and PDO?
Ans:
MySQLi only supports MySQL databases and offers both procedural and object-oriented APIs, while PDO supports multiple database drivers (MySQL, PostgreSQL, SQLite, etc.) through a single consistent object-oriented API.
PHP
#2.97
Q97:
What are prepared statements and why are they important?
Ans:
Prepared statements separate SQL logic from data by using placeholders for values, which are bound and sent separately to the database, preventing SQL injection attacks.
Code Example
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
PHP
#2.98
Q98:
How do you execute a prepared statement with named parameters in PDO?
Ans:
You use named placeholders prefixed with a colon in the SQL, then pass an associative array or bindParam/bindValue calls matching those names.
Code Example
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
PHP
#2.99
Q99:
What is SQL injection and how do prepared statements prevent it?
Ans:
SQL injection occurs when untrusted input is concatenated directly into a SQL query, allowing an attacker to alter query logic; prepared statements prevent this by treating user input strictly as data, never as executable SQL code.
PHP
#2.100
Q100:
How do you handle transactions in PDO?
Ans:
You call beginTransaction(), execute multiple queries, then commit() if successful, or rollBack() if an error occurs, ensuring atomicity.
Code Example
$pdo->beginTransaction();
try {
$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}
PHP
#2.101
Q101:
How do you get the ID of the last inserted row?
Ans:
In PDO, you call lastInsertId() on the PDO object after an insert statement; in MySQLi, you access the insert_id property.
Code Example
$pdo->lastInsertId();
$conn->insert_id;
PHP
#2.102
Q102:
What is the difference between PDO::FETCH_ASSOC and PDO::FETCH_OBJ?
Ans:
PDO::FETCH_ASSOC returns each row as an associative array keyed by column name, while PDO::FETCH_OBJ returns each row as a stdClass object with column names as properties.
PHP
#2.103
Q103:
What is an ORM and does PHP have popular ones?
Ans:
An ORM (Object-Relational Mapper) maps database tables to classes and rows to objects, abstracting raw SQL; popular PHP ORMs include Eloquent (Laravel) and Doctrine.
PHP
#2.104
Q104:
How do you prevent storing plain text passwords in a database?
Ans:
You should hash passwords using password_hash() before storing them and verify login attempts using password_verify(), never storing or comparing raw passwords.
Code Example
$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($input, $hash)) { echo 'Match'; }
PHP
#2.105
Q105:
What does password_hash() use by default in PHP?
Ans:
By default, password_hash() uses the bcrypt algorithm (PASSWORD_DEFAULT), which automatically generates a secure salt and can be upgraded to stronger algorithms in future PHP versions.
PHP
#2.106
Q106:
What is Cross-Site Scripting (XSS)?
Ans:
XSS is a vulnerability where an attacker injects malicious scripts into web pages viewed by other users, often exploited when user input is rendered without proper escaping.
PHP
#2.107
Q107:
What is Cross-Site Request Forgery (CSRF) and how do you prevent it?
Ans:
CSRF tricks an authenticated user's browser into submitting unwanted requests to a site; it is mitigated by including a unique, unpredictable CSRF token in forms that is validated on submission.
PHP
#2.108
Q108:
What is SQL Injection?
Ans:
SQL Injection is an attack where malicious SQL is inserted into a query through unsanitized user input, potentially allowing data theft or manipulation; it is prevented using prepared statements.
PHP
#2.109
Q109:
How do you securely store passwords in PHP applications?
Ans:
Passwords should be hashed with password_hash() using a strong algorithm like bcrypt or Argon2, never encrypted or stored in plain text, and verified with password_verify().
PHP
#2.110
Q110:
What is the difference between htmlspecialchars() and strip_tags()?
Ans:
htmlspecialchars() encodes special characters so tags display as text rather than being rendered, while strip_tags() removes HTML and PHP tags entirely from a string.
PHP
#2.111
Q111:
What is the purpose of PHP's random_bytes() and random_int() functions?
Ans:
random_bytes() and random_int(), introduced in PHP 7, generate cryptographically secure random data suitable for security-sensitive tasks like tokens and keys, unlike rand() or mt_rand().
PHP
#2.112
Q112:
What is the principle of least privilege in the context of PHP applications?
Ans:
It means granting a database user or application component only the minimum permissions necessary to perform its function, limiting damage if that component is compromised.
PHP
#2.113
Q113:
Why should you disable display_errors in a production environment?
Ans:
Displaying detailed errors in production can expose sensitive information like file paths, database credentials, or code structure to attackers; errors should instead be logged and generic messages shown to users.
PHP
#2.114
Q114:
What is input validation versus input sanitization?
Ans:
Validation checks that input meets expected criteria (like a valid email format) and rejects it if not, while sanitization modifies or cleans the input to make it safe for use, such as stripping unwanted characters.
PHP
#2.115
Q115:
How do you use regular expressions in PHP?
Ans:
PHP uses PCRE (Perl Compatible Regular Expressions) functions like preg_match(), preg_match_all(), preg_replace(), and preg_split() to work with regex patterns.
Code Example
if (preg_match('/^[a-z]+$/', $str)) { echo 'matches'; }
PHP
#2.116
Q116:
What is the difference between preg_match() and preg_match_all()?
Ans:
preg_match() finds only the first match of a pattern in a string, while preg_match_all() finds all matches and returns them in an array.
PHP
#2.117
Q117:
How do you replace text using a regular expression?
Ans:
preg_replace() searches a string for a pattern match and replaces it with a replacement string, supporting backreferences to captured groups.
Code Example
echo preg_replace('/\d+/', '#', 'Order 123 shipped'); // 'Order # shipped'
PHP
#2.118
Q118:
How do you split a string using a regular expression?
Ans:
preg_split() splits a string into an array using a regular expression as the delimiter, offering more flexibility than explode().
Code Example
print_r(preg_split('/[\s,]+/', 'a, b c'));
PHP
#2.119
Q119:
What are capturing groups in regex?
Ans:
Capturing groups, defined with parentheses (), allow you to extract specific portions of a matched pattern for later use or reference.
Code Example
preg_match('/(\d{3})-(\d{4})/', '555-1234', $matches);
// $matches[1] = '555', $matches[2] = '1234'
PHP
#2.120
Q120:
What is the DateTime class used for?
Ans:
DateTime is an object-oriented way to represent, manipulate, and format dates and times, offering more functionality than the procedural date() function.
Code Example
$date = new DateTime('2024-01-15');
echo $date->format('d/m/Y');
PHP
#2.121
Q121:
How do you calculate the difference between two dates?
Ans:
You can use the diff() method on two DateTime objects, which returns a DateInterval object describing the difference in years, months, days, etc.
Code Example
$d1 = new DateTime('2024-01-01');
$d2 = new DateTime('2024-03-15');
$diff = $d1->diff($d2);
echo $diff->days;
PHP
#2.122
Q122:
How do you add or subtract time from a date?
Ans:
You can use the modify() method with a relative format string, or the add()/sub() methods with a DateInterval object.
Code Example
$date = new DateTime('2024-01-01');
$date->modify('+1 month');
PHP
#2.123
Q123:
How do you handle time zones in PHP?
Ans:
You can set the default timezone with date_default_timezone_set(), or specify a DateTimeZone object when creating DateTime instances to work with specific zones.
Code Example
$date = new DateTime('now', new DateTimeZone('America/New_York'));
PHP
#2.124
Q124:
What problem do namespaces solve in PHP?
Ans:
Namespaces prevent naming collisions between classes, functions, and constants from different libraries or parts of an application that might otherwise share the same name.
PHP
#2.125
Q125:
How do you import a namespaced class for use in your code?
Ans:
You use the 'use' keyword to import a fully qualified class name, optionally with an alias, so it can be referenced by its short name.
Code Example
use App\Models\User as UserModel;
PHP
#2.126
Q126:
What is autoloading in PHP and how does Composer handle it?
Ans:
Autoloading automatically loads class files when needed instead of manually requiring each one; Composer generates an autoloader (often PSR-4 based) that maps namespaces to directory structures.
Code Example
require 'vendor/autoload.php';
PHP
#2.127
Q127:
What is PSR-4 in the context of PHP?
Ans:
PSR-4 is a PHP-FIG standard defining how namespaces and class names should map to file paths for autoloading purposes.
PHP
#2.128
Q128:
What are union types in PHP 8?
Ans:
Union types allow a parameter, return value, or property to accept more than one specified type, separated by a pipe (|).
Code Example
function process(int|string $id): void {}
PHP
#2.129
Q129:
What is the mixed type in PHP 8?
Ans:
mixed is a pseudo-type indicating a parameter or return value can be of any type, equivalent to having no type restriction while still being explicit.
PHP
#2.130
Q130:
What is the nullsafe operator in PHP 8?
Ans:
The nullsafe operator (?->) allows chaining method or property access on a potentially null object, short-circuiting to null instead of throwing an error if any part of the chain is null.
Code Example
$country = $user?->getAddress()?->getCountry();
PHP
#2.131
Q131:
What is opcode caching and why does it matter for PHP performance?
Ans:
Opcode caching (like OPcache) stores precompiled script bytecode in memory, avoiding the need to parse and compile PHP files on every request, significantly improving performance.
PHP
#2.132
Q132:
What is the difference between require_once and a namespace-based autoloader?
Ans:
require_once manually and explicitly loads a specific file each time it's needed, while an autoloader automatically loads class files on demand based on naming conventions, reducing manual include statements.
PHP
#2.133
Q133:
What is the difference between static and instance methods regarding $this?
Ans:
Instance methods have access to $this referring to the current object, while static methods do not have an object context and cannot use $this.
PHP
#2.134
Q134:
What is object destructuring with list() and named keys?
Ans:
PHP 7.1+ allows list() and short array syntax to destructure associative arrays using key => variable pairs, extracting values into variables by key rather than position.
Code Example
['name' => $name, 'age' => $age] = $user;
PHP
#2.135
Q135:
What is the difference between == null and === null checks?
Ans:
== null is true for many falsy values in older PHP behavior contexts depending on type juggling rules, while === null strictly checks that the value's type is exactly NULL; using is_null() or === null is safer and clearer.
PHP
#2.136
Q136:
How do you check the number of days in a given month using PHP?
Ans:
You can use cal_days_in_month() or format a DateTime object with 't' to get the number of days in that month.
Code Example
echo date('t', strtotime('2024-02-01')); // 29
PHP
#2.137
Q137:
What is the difference between require and autoloading for including classes?
Ans:
require directly and immediately loads a specified file regardless of whether the class is used, while autoloading defers loading until the class is actually referenced, improving efficiency in large codebases.
PHP
#2.138
Q138:
How do you check whether a class implements a specific interface?
Ans:
You can use the instanceof operator on an object, or class_implements() to get an array of interfaces implemented by a class.
Code Example
print_r(class_implements('Circle'));
PHP
#2.139
Q139:
What is the difference between array_key_first() and array_key_last()?
Ans:
array_key_first() returns the key of the first element in an array, and array_key_last() returns the key of the last element, both without modifying the array's internal pointer.
PHP
#2.140
Q140:
How do you compare two arrays for equality in PHP?
Ans:
Using == checks if arrays have the same key-value pairs regardless of order, while === checks that they have the same key-value pairs in the same order and same types.
PHP
#2.141
Q141:
What is the difference between compact() and extract()?
Ans:
compact() creates an array from variable names and their values, while extract() does the reverse, importing array keys into variables in the current scope.
Code Example
$name='Tom'; $age=25;
$data = compact('name', 'age'); // ['name'=>'Tom','age'=>25]
extract($data);
PHP
#2.142
Q142:
What is the purpose of the __LINE__, __FILE__, and __FUNCTION__ magic constants?
Ans:
These are predefined constants that resolve to the current line number, current file path, and current function name respectively, useful for debugging and logging.
PHP
#2.143
Q143:
What does the array_diff() function do?
Ans:
array_diff() returns the values in the first array that are not present in any of the other given arrays, comparing values as strings.
Code Example
print_r(array_diff([1,2,3], [2,3])); // [0 => 1]
PHP
#2.144
Q144:
What does the array_intersect() function do?
Ans:
array_intersect() returns the values that are present in all of the given arrays, preserving the keys from the first array.
Code Example
print_r(array_intersect([1,2,3], [2,3,4])); // [1=>2, 2=>3]
PHP
#2.145
Q145:
What is the difference between require and require_once regarding performance?
Ans:
require_once has slightly more overhead because it checks a list of already-included files before including, while require always includes the file; for files that should load once (like class definitions), require_once prevents redeclaration errors.
PHP
#2.146
Q146:
What is method chaining and how do you implement it?
Ans:
Method chaining allows calling multiple methods sequentially on the same object in one statement by having each method return $this.
Code Example
class Query {
function where($cond){ $this->conditions[]=$cond; return $this; }
function orderBy($col){ $this->order=$col; return $this; }
}
$q = (new Query())->where('age > 18')->orderBy('name');
JAVA
#2.147
Q147:
Why must the main method be static?
Ans:
It must be static so the JVM can invoke it directly using the class name without first creating an instance of the class.
JAVA
#2.148
Q148:
What is autoboxing and unboxing in Java?
Ans:
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class (e.g., int to Integer), and unboxing is the reverse conversion, both handled automatically by the compiler.
Code Example
Integer boxed = 10; // autoboxing
int unboxed = boxed; // unboxing
JAVA
#2.149
Q149:
What is type casting in Java and what are its two kinds?
Ans:
Type casting converts a value from one type to another; widening (implicit) casting converts a smaller type to a larger one automatically, while narrowing (explicit) casting requires an explicit cast and may lose data.
Code Example
int i = 100;
long l = i; // widening
int j = (int) 3.99; // narrowing, j = 3
JAVA
#2.150
Q150:
What is the String pool in Java?
Ans:
The String pool (or intern pool) is a special memory area in the heap where the JVM stores unique String literals, allowing multiple references to the same literal to share one object and save memory.
JAVA
#2.151
Q151:
Why are Strings immutable in Java?
Ans:
Strings are immutable for security, thread-safety, and to support the String pool's caching mechanism; once created, a String object's content cannot change, and operations like concatenation return new String objects.
JAVA
#2.152
Q152:
What is the difference between String, StringBuilder, and StringBuffer?
Ans:
String is immutable, StringBuilder is mutable and not synchronized (faster in single-threaded contexts), and StringBuffer is mutable and synchronized, making it thread-safe but slightly slower.
Code Example
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World");
JAVA
#2.153
Q153:
What is the difference between var and explicit type declaration in Java 10+?
Ans:
var lets the compiler infer the variable's type from the assigned value at compile time, reducing verbosity, while the actual type remains static and fixed just as if explicitly declared.
Code Example
var list = new ArrayList<String>(); // inferred as ArrayList<String>
JAVA
#2.154
Q154:
Can a static method access instance variables directly?
Ans:
No, a static method cannot directly access instance variables or instance methods because it has no reference to any specific object (no 'this').
JAVA
#2.155
Q155:
What is the difference between & and && in Java?
Ans:
& is a bitwise/logical AND that always evaluates both operands, while && is a short-circuit logical AND that skips evaluating the right operand if the left is already false.
JAVA
#2.156
Q156:
What are switch expressions introduced in Java 14?
Ans:
Switch expressions allow switch to be used as an expression that returns a value, support the arrow (->) syntax without fall-through, and can use yield to return a value from a block.
Code Example
int numLetters = switch (day) {
case MONDAY, FRIDAY -> 6;
case TUESDAY -> 7;
default -> 0;
};
JAVA
#2.157
Q157:
Can you use a labeled break in Java?
Ans:
Yes, a labeled break allows breaking out of an outer loop from within a nested loop by specifying the label of the loop to exit.
Code Example
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break outer;
}
}
JAVA
#2.158
Q158:
Why doesn't Java support multiple inheritance of classes?
Ans:
Java disallows multiple class inheritance to avoid the 'diamond problem', where ambiguity arises if two parent classes define the same method; instead, Java allows implementing multiple interfaces to achieve similar flexibility.
JAVA
#2.159
Q159:
What is the difference between method overloading and overriding?
Ans:
Overloading involves multiple methods with the same name but different parameters within the same class (compile-time), while overriding involves a subclass redefining a parent method with an identical signature (runtime polymorphism).
JAVA
#2.160
Q160:
What is polymorphism in Java?
Ans:
Polymorphism allows objects of different classes to be treated as instances of a common superclass or interface, enabling the same method call to behave differently depending on the actual object type.
Code Example
Animal a = new Dog();
a.sound(); // calls Dog's overridden method
JAVA
#2.161
Q161:
What is an abstract class in Java?
Ans:
An abstract class cannot be instantiated and may contain both abstract methods (without a body) and concrete methods, serving as a partial blueprint for subclasses.
Code Example
abstract class Shape {
abstract double area();
void describe() { System.out.println("A shape"); }
}
JAVA
#2.162
Q162:
What is an interface in Java?
Ans:
An interface defines a contract of abstract methods (and optionally default/static methods) that implementing classes must fulfill, without providing state, traditionally supporting multiple inheritance of type.
Code Example
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("Drawing circle"); }
}
JAVA
#2.163
Q163:
What is the difference between an abstract class and an interface?
Ans:
An abstract class can have constructors, instance fields, and a mix of abstract and concrete methods, and a class can extend only one; an interface traditionally only declares method signatures (plus default/static methods since Java 8) and a class can implement multiple interfaces.
JAVA
#2.164
Q164:
Can an interface have method implementations?
Ans:
Since Java 8, interfaces can include default methods (with a body, using the default keyword) and static methods, though they still cannot have instance state.
Code Example
interface Vehicle {
default void honk() { System.out.println("Beep"); }
}
JAVA
#2.165
Q165:
What is a functional interface in Java?
Ans:
A functional interface is an interface with exactly one abstract method, optionally annotated with @FunctionalInterface, intended to be implemented using a lambda expression or method reference.
Code Example
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}
JAVA
#2.166
Q166:
Can constructors be inherited in Java?
Ans:
No, constructors are not inherited by subclasses, but a subclass constructor can invoke a superclass constructor explicitly using super().
JAVA
#2.167
Q167:
What is the purpose of the final keyword in Java?
Ans:
final can be applied to variables (making them constants), methods (preventing overriding), and classes (preventing extension/inheritance).
Code Example
final class Utility {}
class Base { final void init() {} }
final int MAX = 100;
JAVA
#2.168
Q168:
What is a marker interface?
Ans:
A marker interface has no methods or fields and is used to signal metadata about a class to the JVM or a framework, such as Serializable or Cloneable.
JAVA
#2.169
Q169:
What is the Object class in Java?
Ans:
Object is the root superclass of all Java classes; every class implicitly extends Object and inherits its methods like equals(), hashCode(), toString(), and getClass().
JAVA
#2.170
Q170:
Why should you override equals() and hashCode() together?
Ans:
The general contract requires that equal objects must have equal hash codes; overriding only equals() without hashCode() can break the behavior of hash-based collections like HashMap and HashSet.
JAVA
#2.171
Q171:
What is composition in OOP and how does it differ from inheritance?
Ans:
Composition involves building a class using instances of other classes as fields (a 'has-a' relationship) rather than extending them (an 'is-a' relationship), often preferred for flexibility and avoiding tight coupling.
Code Example
class Engine {}
class Car {
private Engine engine = new Engine(); // composition
}
JAVA
#2.172
Q172:
What is a nested class in Java?
Ans:
A nested class is a class defined within another class; it can be static (not tied to an instance of the outer class) or non-static/inner (tied to and holding an implicit reference to an outer instance).
Code Example
class Outer {
static class StaticNested {}
class Inner {}
}
JAVA
#2.173
Q173:
What is an anonymous inner class?
Ans:
An anonymous inner class is a class without a name, defined and instantiated in a single expression, typically used to provide a one-off implementation of an interface or abstract class.
Code Example
Runnable r = new Runnable() {
public void run() { System.out.println("Running"); }
};
JAVA
#2.174
Q174:
Can an abstract class have a constructor?
Ans:
Yes, an abstract class can have a constructor, which is called when a subclass instance is created via super(), even though the abstract class itself cannot be instantiated directly.
JAVA
#2.175
Q175:
What is the difference between checked and unchecked exceptions?
Ans:
Checked exceptions (like IOException) must be declared or handled at compile time, while unchecked exceptions (RuntimeException and its subclasses like NullPointerException) are not required to be declared or caught.
JAVA
#2.176
Q176:
What is the difference between Error and Exception in Java?
Ans:
Error represents serious problems that applications typically should not try to catch (like OutOfMemoryError), while Exception represents conditions an application might want to catch and handle.
JAVA
#2.177
Q177:
What is the purpose of the finally block?
Ans:
The finally block contains code that always executes after try/catch, regardless of whether an exception occurred, typically used to release resources like closing files or connections.
JAVA
#2.178
Q178:
What is try-with-resources in Java?
Ans:
Introduced in Java 7, try-with-resources automatically closes resources (implementing AutoCloseable) declared in the try statement's parentheses at the end of the block, eliminating the need for manual finally cleanup.
Code Example
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
}
JAVA
#2.179
Q179:
How do you create a custom exception in Java?
Ans:
You create a class extending Exception (for checked) or RuntimeException (for unchecked), typically with constructors that pass a message to the superclass.
Code Example
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) { super(message); }
}
JAVA
#2.180
Q180:
What is the difference between throw and throws?
Ans:
throw is used to explicitly raise an exception instance within a method body, while throws is used in a method signature to declare that the method might propagate a checked exception to its caller.
Code Example
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance) throw new InsufficientFundsException("Not enough");
}
JAVA
#2.181
Q181:
Can you have multiple catch blocks for a single try?
Ans:
Yes, you can have multiple catch blocks to handle different exception types, and Java also supports multi-catch syntax to handle several exception types in a single block using a pipe (|).
Code Example
try {
// risky code
} catch (IOException | SQLException e) {
e.printStackTrace();
}
JAVA
#2.182
Q182:
What happens if an exception is not caught?
Ans:
If an exception propagates up through all method calls without being caught, it reaches the JVM's default handler, which prints a stack trace and terminates the thread (or the program if it's the main thread).
JAVA
#2.183
Q183:
Is it a good practice to catch generic Exception or Throwable?
Ans:
Generally no; catching overly broad exception types can mask specific errors and make debugging harder, so it's better to catch the most specific exception types applicable to the situation.
JAVA
#2.184
Q184:
What is the difference between NullPointerException and ClassCastException?
Ans:
NullPointerException occurs when trying to use a reference variable that points to null, while ClassCastException occurs when attempting an invalid cast between incompatible object types.
JAVA
#2.185
Q185:
What is the difference between ArrayList and LinkedList?
Ans:
ArrayList is backed by a dynamic array offering fast random access (O(1)) but slower insertions/deletions in the middle (O(n)), while LinkedList is backed by a doubly linked list offering fast insertions/deletions but slower random access.
JAVA
#2.186
Q186:
What is the difference between ArrayList and Vector?
Ans:
ArrayList is not synchronized and generally faster, while Vector is synchronized (thread-safe) but has more overhead; Vector is considered a legacy class largely superseded by ArrayList with external synchronization when needed.
JAVA
#2.187
Q187:
What is the difference between HashMap and TreeMap?
Ans:
HashMap stores key-value pairs with no guaranteed order and offers average O(1) access, while TreeMap stores entries sorted by key (natural ordering or a Comparator) and offers O(log n) access via a red-black tree.
JAVA
#2.188
Q188:
What is the difference between HashMap and LinkedHashMap?
Ans:
HashMap does not guarantee any order of iteration, while LinkedHashMap maintains insertion order (or optionally access order) by using a linked list alongside the hash table.
JAVA
#2.189
Q189:
What is the difference between HashMap and Hashtable?
Ans:
HashMap is not synchronized and allows one null key and multiple null values, while Hashtable is synchronized (thread-safe legacy class) and does not allow null keys or values.
JAVA
#2.190
Q190:
What is the difference between HashSet and TreeSet?
Ans:
HashSet stores unique elements with no guaranteed order backed by a HashMap, while TreeSet stores unique elements in sorted order backed by a TreeMap (red-black tree).
JAVA
#2.191
Q191:
What is the difference between Comparable and Comparator?
Ans:
Comparable is implemented by a class itself to define its natural ordering via compareTo(), while Comparator is a separate class defining custom ordering logic via compare(), allowing multiple different sort orders for the same type.
Code Example
class Person implements Comparable<Person> {
public int compareTo(Person p) { return this.age - p.age; }
}
Comparator<Person> byName = (p1, p2) -> p1.name.compareTo(p2.name);
JAVA
#2.192
Q192:
What is an Iterator in Java?
Ans:
An Iterator is an object that allows traversing a collection sequentially, providing hasNext(), next(), and remove() methods, and is the standard way to safely remove elements while iterating.
Code Example
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.isEmpty()) it.remove();
}
JAVA
#2.193
Q193:
What is the difference between Iterator and ListIterator?
Ans:
Iterator allows forward-only traversal and element removal, while ListIterator (available only for List implementations) additionally supports backward traversal, element replacement, and insertion.
JAVA
#2.194
Q194:
What is the Queue interface used for?
Ans:
Queue represents a collection designed for holding elements prior to processing, typically in FIFO order, with implementations like LinkedList and PriorityQueue.
JAVA
#2.195
Q195:
What is a Deque in Java?
Ans:
Deque (double-ended queue) supports insertion and removal of elements from both ends, and can be used to implement both stacks and queues; ArrayDeque is a common implementation.
JAVA
#2.196
Q196:
What is the difference between poll() and remove() in a Queue?
Ans:
Both remove and return the head of the queue, but poll() returns null if the queue is empty, while remove() throws a NoSuchElementException.
JAVA
#2.197
Q197:
What is the difference between Collection and Collections in Java?
Ans:
Collection is a root interface representing a group of objects, while Collections is a utility class providing static methods to operate on collections, like sorting, searching, and creating immutable collections.
JAVA
#2.198
Q198:
How do you make a collection immutable in Java?
Ans:
You can use Collections.unmodifiableList()/Map()/Set() to wrap an existing collection, or since Java 9, use List.of(), Set.of(), and Map.of() to create truly immutable collections directly.
Code Example
List<String> immutable = List.of("a", "b", "c");
JAVA
#2.199
Q199:
What is the PriorityQueue used for?
Ans:
PriorityQueue is a queue implementation where elements are ordered according to their natural ordering or a provided Comparator, always retrieving the smallest (or highest priority) element first.
JAVA
#2.200
Q200:
What are generics in Java?
Ans:
Generics allow classes, interfaces, and methods to operate on typed parameters, providing compile-time type safety and eliminating the need for explicit casting.
Code Example
List<String> names = new ArrayList<>();
names.add("Alice"); // compile-time type checked
JAVA
#2.201
Q201:
What is a bounded type parameter in generics?
Ans:
A bounded type parameter restricts the types that can be used as a type argument using the extends keyword, such as , allowing calls to methods defined on that bound.
Code Example
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
JAVA
#2.202
Q202:
What is a generic method in Java?
Ans:
A generic method declares its own type parameter(s), independent of the class's generics, placed before the return type in the method signature.
Code Example
public static <T> void printArray(T[] array) {
for (T item : array) System.out.println(item);
}
JAVA
#2.203
Q203:
How do you concatenate strings efficiently in a loop?
Ans:
You should use StringBuilder inside loops instead of the + operator, since repeated String concatenation creates many intermediate immutable String objects, hurting performance.
Code Example
StringBuilder sb = new StringBuilder();
for (String s : items) sb.append(s);
JAVA
#2.204
Q204:
How do you copy an array in Java?
Ans:
You can use Arrays.copyOf(), System.arraycopy(), or clone(), each copying elements to a new array (shallow copy for object arrays).
Code Example
int[] copy = Arrays.copyOf(original, original.length);
JAVA
#2.205
Q205:
What is the difference between a shallow copy and a deep copy?
Ans:
A shallow copy duplicates the top-level structure but copies references to nested objects (so both copies share the same nested objects), while a deep copy recursively duplicates nested objects as well, creating fully independent copies.
JAVA
#2.206
Q206:
How do you search for an element in a sorted array?
Ans:
Arrays.binarySearch() performs a binary search on a sorted array and returns the index of the found element, or a negative value if not found.
JAVA
#2.207
Q207:
What is the String.format() method used for?
Ans:
String.format() creates a formatted string using a format string and arguments, similar to printf, useful for constructing strings with specific number or text formatting.
Code Example
String s = String.format("%s is %d years old", "Tom", 25);
JAVA
#2.208
Q208:
What is the difference between extending Thread and implementing Runnable?
Ans:
Implementing Runnable is generally preferred since Java doesn't support multiple inheritance of classes, so a class implementing Runnable can still extend another class, whereas extending Thread uses up the single inheritance slot.
JAVA
#2.209
Q209:
What is the difference between start() and run() on a Thread?
Ans:
Calling start() creates a new call stack and executes run() in a separate thread of execution, while calling run() directly executes the code synchronously in the current thread without creating a new one.
JAVA
#2.210
Q210:
What is synchronization in Java?
Ans:
Synchronization controls access to shared resources by multiple threads using the synchronized keyword, ensuring only one thread can execute a synchronized block or method on a given object at a time, preventing race conditions.
Code Example
public synchronized void increment() { count++; }
JAVA
#2.211
Q211:
What is a race condition?
Ans:
A race condition occurs when multiple threads access and modify shared data concurrently without proper synchronization, causing the outcome to depend unpredictably on the timing of thread execution.
JAVA
#2.212
Q212:
What is a deadlock?
Ans:
A deadlock occurs when two or more threads are blocked forever, each waiting for a resource held by another thread in the group, forming a circular dependency.
JAVA
#2.213
Q213:
What is the Executor framework in Java?
Ans:
The Executor framework (java.util.concurrent) provides a higher-level API for managing thread pools and asynchronous task execution, decoupling task submission from the details of thread creation and scheduling.
Code Example
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task running"));
executor.shutdown();
JAVA
#2.214
Q214:
What is a thread pool and why is it useful?
Ans:
A thread pool maintains a set of reusable worker threads to execute submitted tasks, avoiding the overhead of creating and destroying threads repeatedly and controlling the level of concurrency.
JAVA
#2.215
Q215:
What is the difference between Callable and Runnable?
Ans:
Runnable's run() method returns no value and cannot throw checked exceptions, while Callable's call() method returns a value (via Future) and can throw checked exceptions.
Code Example
Callable<Integer> task = () -> 42;
Future<Integer> future = executor.submit(task);
JAVA
#2.216
Q216:
What is a Future in Java concurrency?
Ans:
A Future represents the result of an asynchronous computation, providing methods like get() to retrieve the result (blocking until available), and isDone() to check completion status.
JAVA
#2.217
Q217:
What is the difference between InputStream/OutputStream and Reader/Writer?
Ans:
InputStream and OutputStream handle raw binary data (bytes), while Reader and Writer are designed for handling character/text data with proper encoding support.
JAVA
#2.218
Q218:
How do you read a text file in Java?
Ans:
You can use classes like BufferedReader with FileReader, or the modern Files.readAllLines() / Files.lines() from java.nio.file for simpler file reading.
Code Example
List<String> lines = Files.readAllLines(Paths.get("data.txt"));
JAVA
#2.219
Q219:
How do you write to a file in Java?
Ans:
You can use FileWriter/BufferedWriter, or Files.write() from java.nio.file to write strings or byte data to a file.
Code Example
Files.write(Paths.get("out.txt"), "Hello".getBytes());
JAVA
#2.220
Q220:
What is serialization in Java?
Ans:
Serialization is the process of converting an object into a byte stream for storage or transmission, and deserialization reverses this process to reconstruct the object; classes must implement the Serializable marker interface.
Code Example
class User implements Serializable {
private String name;
}
JAVA
#2.221
Q221:
What is the transient keyword used for?
Ans:
transient marks a field to be excluded from the default serialization process, so its value is not saved when the object is serialized.
Code Example
private transient String password;
JAVA
#2.222
Q222:
What is try-with-resources and how does it relate to file handling?
Ans:
try-with-resources automatically closes resources like file streams that implement AutoCloseable at the end of the block, preventing resource leaks without needing explicit finally blocks.
Code Example
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("log.txt"))) {
writer.write("Log entry");
}
JAVA
#2.223
Q223:
What is a lambda expression in Java?
Ans:
A lambda expression is a concise way to represent an anonymous function, implementing a functional interface's single abstract method, introduced in Java 8.
Code Example
Runnable r = () -> System.out.println("Hello");
Comparator<Integer> cmp = (a, b) -> a - b;
JAVA
#2.224
Q224:
What is the Stream API in Java?
Ans:
The Stream API, introduced in Java 8, provides a functional-style approach to process sequences of elements (from collections, arrays, etc.) using operations like filter, map, and reduce, often in a pipeline.
Code Example
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
JAVA
#2.225
Q225:
What is the difference between intermediate and terminal operations in streams?
Ans:
Intermediate operations (like filter, map) are lazy and return a new stream, allowing chaining, while terminal operations (like collect, forEach, reduce) trigger the actual processing and produce a result or side-effect, ending the stream pipeline.
JAVA
#2.226
Q226:
What is the Optional class used for?
Ans:
Optional is a container object that may or may not hold a non-null value, used to explicitly represent the potential absence of a value and reduce NullPointerException risks.
Code Example
Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);
JAVA
#2.227
Q227:
What is a method reference in Java?
Ans:
A method reference (using ::) is shorthand syntax for a lambda expression that simply calls an existing method, improving readability when the lambda body does nothing more than invoke a method.
Code Example
list.forEach(System.out::println);
list.sort(String::compareTo);
JAVA
#2.228
Q228:
What is the Collectors class used for in the Stream API?
Ans:
Collectors provides implementations for common reduction operations like collecting stream elements into a List, Set, Map, or joining strings, typically used with the collect() terminal operation.
Code Example
String joined = names.stream().collect(Collectors.joining(", "));
JAVA
#2.229
Q229:
What is the default method feature in interfaces used for?
Ans:
Default methods allow interfaces to provide a method implementation, enabling new methods to be added to interfaces without breaking existing implementing classes.
JAVA
#2.230
Q230:
What is a Supplier, Consumer, Function, and Predicate in java.util.function?
Ans:
Supplier takes no input and returns a value, Consumer takes an input and returns nothing, Function takes an input and returns a transformed result, and Predicate takes an input and returns a boolean.
Code Example
Supplier<String> sup = () -> "Hello";
Consumer<String> con = System.out::println;
Function<Integer,Integer> square = n -> n * n;
Predicate<Integer> isEven = n -> n % 2 == 0;
JAVA
#2.231
Q231:
What are records in Java 16?
Ans:
Records are a concise way to declare immutable data-carrying classes, automatically generating a constructor, accessors, equals(), hashCode(), and toString() based on the declared components.
Code Example
public record Point(int x, int y) {}
JAVA
#2.232
Q232:
What is pattern matching for instanceof in Java 16?
Ans:
It allows combining an instanceof check and a cast into a single expression, automatically binding the cast result to a new variable if the check succeeds.
Code Example
if (obj instanceof String s) {
System.out.println(s.length());
}
JAVA
#2.233
Q233:
What are text blocks in Java 15?
Ans:
Text blocks, delimited by triple double-quotes ("""), allow multi-line string literals without needing explicit escape sequences for newlines or most quotes.
Code Example
String html = """
<html>
<body>Hello</body>
</html>
""";
JAVA
#2.234
Q234:
What is the difference between stack and heap memory in Java?
Ans:
The stack stores method call frames, local variables, and references, following LIFO order and being thread-specific, while the heap stores all objects and is shared across threads, managed by the garbage collector.
JAVA
#2.235
Q235:
Can you force garbage collection in Java?
Ans:
You can call System.gc() to suggest that the JVM run garbage collection, but this is only a hint, not a guarantee, and the JVM may choose to ignore or delay it.
JAVA
#2.236
Q236:
What is the difference between StackOverflowError and OutOfMemoryError?
Ans:
StackOverflowError occurs when a thread's call stack exceeds its allocated size, typically due to excessive or infinite recursion, while OutOfMemoryError occurs when the JVM cannot allocate more objects because the heap is exhausted.
JAVA
#2.237
Q237:
What is the Singleton design pattern and how do you implement it in Java?
Ans:
Singleton ensures a class has only one instance and provides a global access point to it, commonly implemented with a private constructor, a static instance field, and a public static method to retrieve or lazily create that instance.
Code Example
public class Config {
private static Config instance;
private Config() {}
public static synchronized Config getInstance() {
if (instance == null) instance = new Config();
return instance;
}
}
JAVA
#2.238
Q238:
What is dependency injection?
Ans:
Dependency injection is a design pattern where an object's dependencies are supplied externally (via constructor, setter, or field) rather than created internally, promoting loose coupling and easier testing.
JAVA
#2.239
Q239:
What is the difference between composition and inheritance in terms of design?
Ans:
Composition ('has-a') favors flexibility by delegating behavior to contained objects and is generally preferred, while inheritance ('is-a') creates tighter coupling between parent and child classes and can lead to fragile hierarchies if overused.
JAVA
#2.240
Q240:
What is the Builder design pattern?
Ans:
The Builder pattern constructs complex objects step-by-step using a fluent interface, separating the construction process from the final representation, often useful for objects with many optional parameters.
Code Example
Pizza pizza = new Pizza.Builder().size(12).addTopping("cheese").build();
JAVA
#2.241
Q241:
What are annotations in Java?
Ans:
Annotations provide metadata about code (classes, methods, fields) that can be processed by the compiler or at runtime via reflection, commonly used for configuration, validation, and framework behavior like @Override or @Deprecated.
Code Example
@Override
public String toString() { return "Custom"; }
JAVA
#2.242
Q242:
What is the @FunctionalInterface annotation used for?
Ans:
@FunctionalInterface documents and enforces at compile time that an interface has exactly one abstract method, making it eligible for lambda expressions.
JAVA
#2.243
Q243:
What is the difference between an interface's static and default methods?
Ans:
Static methods belong to the interface itself and are called using the interface name, not inherited by implementing classes, while default methods provide inheritable behavior that implementing classes can use as-is or override.
JAVA
#2.244
Q244:
What is the purpose of the enum type in Java?
Ans:
enum defines a fixed set of named constants, is type-safe, can have fields, constructors, and methods, and implicitly extends java.lang.Enum.
Code Example
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day today = Day.MONDAY;
JAVA
#2.245
Q245:
Can an enum implement an interface in Java?
Ans:
Yes, an enum can implement one or more interfaces, and each enum constant can even provide its own implementation of an interface method.
JAVA
#2.246
Q246:
What is the difference between an abstract method and a default method in an interface?
Ans:
An abstract method has no body and must be implemented by any concrete implementing class, while a default method provides a concrete implementation that implementing classes can inherit as-is or choose to override.
JAVA
#2.247
Q247:
What is a varargs parameter in Java?
Ans:
Varargs (denoted by ...) allows a method to accept a variable number of arguments of a specified type, which are treated as an array within the method.
Code Example
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
JAVA
#2.248
Q248:
What is the difference between a checked exception and RuntimeException in terms of method signatures?
Ans:
Methods that may throw a checked exception must declare it in a throws clause or handle it in a try-catch, while RuntimeException (and its subclasses) do not need to be declared, since they represent programming errors rather than recoverable conditions.
JAVA
#2.249
Q249:
What is the difference between shallow cloning and deep cloning?
Ans:
Shallow cloning copies an object's primitive fields and references to other objects (so nested objects are shared), while deep cloning recursively duplicates nested objects as well, producing a fully independent copy.
JAVA
#2.250
Q250:
What is the purpose of the java.util.Objects class?
Ans:
Objects provides static utility methods like equals(), hashCode(), requireNonNull(), and isNull() that safely handle null values, simplifying common null-checking and object comparison logic.
Code Example
Objects.requireNonNull(name, "Name must not be null");
JAVA
#2.251
Q251:
What is JavaBeans convention?
Ans:
The JavaBeans convention specifies that classes should have a no-argument constructor, private fields with public getter/setter methods following a naming pattern (getX/setX), and implement Serializable, enabling frameworks to introspect and manipulate objects generically.
JAVA
#2.252
Q252:
What are the main steps to connect to a database using JDBC?
Ans:
The typical steps are: load the driver (often automatic since JDBC 4.0), establish a connection using DriverManager.getConnection(), create a Statement or PreparedStatement, execute the query, process the ResultSet, and close the resources.
Code Example
try (Connection conn = DriverManager.getConnection(url, user, pass);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
stmt.setInt(1, 5);
ResultSet rs = stmt.executeQuery();
}
JAVA
#2.253
Q253:
What is the difference between Statement and PreparedStatement?
Ans:
Statement executes static SQL without parameters and is more vulnerable to SQL injection, while PreparedStatement precompiles SQL with placeholders for parameters, improving performance for repeated execution and preventing SQL injection.
JAVA
#2.254
Q254:
How do you prevent SQL injection in JDBC?
Ans:
You should use PreparedStatement with parameterized queries instead of concatenating user input directly into SQL strings, ensuring input is always treated as data, not executable SQL.
Code Example
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
stmt.setString(1, email);
JAVA
#2.255
Q255:
What is a ResultSet in JDBC?
Ans:
A ResultSet represents the table of data returned by executing a SQL query, providing methods to navigate rows (like next()) and retrieve column values by index or name.
JAVA
#2.256
Q256:
How do you handle transactions in JDBC?
Ans:
You disable auto-commit mode with setAutoCommit(false), execute multiple statements, then call commit() if successful or rollback() if an error occurs, ensuring atomicity across multiple operations.
Code Example
conn.setAutoCommit(false);
try {
// multiple statements
conn.commit();
} catch (SQLException e) {
conn.rollback();
}
JAVA
#2.257
Q257:
What is connection pooling and why is it used?
Ans:
Connection pooling maintains a cache of reusable database connections rather than creating a new connection for every request, reducing the overhead of connection setup/teardown and improving application performance and scalability.
JAVA
#2.258
Q258:
What is an ORM framework and name a popular one used with Java?
Ans:
An ORM (Object-Relational Mapping) framework maps database tables to Java classes and rows to objects, abstracting raw SQL; Hibernate and JPA (Java Persistence API) implementations are widely used in the Java ecosystem.
JAVA
#2.259
Q259:
What is the difference between Collections.sort() and Stream.sorted()?
Ans:
Collections.sort() sorts a List in place and returns void, while Stream.sorted() is a lazy intermediate operation returning a new sorted stream without modifying the original source collection.
JAVA
#2.260
Q260:
What is the difference between Collection.stream() and Collection.parallelStream()?
Ans:
stream() processes elements sequentially in a single thread, while parallelStream() splits the workload across multiple threads using the common ForkJoinPool for potentially faster processing of large datasets.
JAVA
#2.261
Q261:
How do you remove duplicate elements from a List?
Ans:
You can convert the List to a Set (like a LinkedHashSet to preserve order) and back to a List, or use stream().distinct().collect(Collectors.toList()).
Code Example
List<Integer> unique = list.stream().distinct().collect(Collectors.toList());
JAVA
#2.262
Q262:
What is the difference between Comparator.comparing() and a custom compare() implementation?
Ans:
Comparator.comparing() is a static factory method providing a concise, readable way to build a Comparator from a key extractor function, while a custom compare() implementation requires manually writing the full comparison logic.
Code Example
list.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
JAVA
#2.263
Q263:
What are the SOLID principles?
Ans:
SOLID stands for Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — five object-oriented design principles intended to make software more maintainable and extensible.
JAVA
#2.264
Q264:
What is immutability and why is it useful in Java?
Ans:
An immutable object's state cannot change after construction; immutability simplifies reasoning about code, makes objects inherently thread-safe, and is used extensively in classes like String and the java.time API.
JAVA
#2.265
Q265:
How do you create an immutable class in Java?
Ans:
Declare the class final, make all fields private and final, provide no setters, initialize all fields via the constructor, and ensure mutable fields (like arrays or collections) are defensively copied on input/output.
Code Example
public final class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
}
JAVA
#2.266
Q266:
What is the difference between String.equals() and Objects.equals()?
Ans:
String.equals() throws a NullPointerException if called on a null reference, while Objects.equals() safely handles null by checking both arguments for null before delegating to equals(), returning true if both are null.
JAVA
#2.267
Q267:
What is the difference between Integer.parseInt() and Integer.valueOf()?
Ans:
Integer.parseInt() returns a primitive int, while Integer.valueOf() returns an Integer object, potentially using the internal cache for small values between -128 and 127.
JAVA
#2.268
Q268:
What is a static nested class used for and how do you instantiate one?
Ans:
A static nested class behaves like a regular top-level class but is namespaced within the outer class, and does not require an instance of the outer class to be instantiated.
Code Example
class Outer {
static class Nested {}
}
Outer.Nested obj = new Outer.Nested();
JAVA
#2.269
Q269:
What is the difference between this() and super() constructor calls?
Ans:
this() calls another constructor within the same class (constructor chaining), while super() calls a constructor of the immediate parent class; both must be the first statement in a constructor and cannot be used together.
JAVA
#2.270
Q270:
What is the difference between an interface reference and a concrete class reference?
Ans:
An interface reference variable can point to any object implementing that interface, enabling polymorphism and decoupling code from specific implementations, whereas a concrete class reference is tied to that specific class and its subclasses.
JAVA
#2.271
Q271:
What is the difference between throw new Exception() and throw new RuntimeException()?
Ans:
Throwing a plain Exception (checked) requires callers to handle or declare it, while throwing a RuntimeException (unchecked) does not require explicit handling, representing a programming error rather than an expected recoverable condition.
JAVA
#2.272
Q272:
What is the difference between a HashMap's keySet(), values(), and entrySet() methods?
Ans:
keySet() returns a view of all the keys, values() returns a view of all the values, and entrySet() returns a view of key-value pairs as Map.Entry objects, useful for iterating over both keys and values together.
Code Example
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
JAVA
#2.273
Q273:
What is the difference between compile-time polymorphism and runtime polymorphism?
Ans:
Compile-time (static) polymorphism is achieved through method overloading, resolved by the compiler based on method signatures, while runtime (dynamic) polymorphism is achieved through method overriding, resolved by the JVM based on the actual object type at runtime.
PYTHON
#2.274
Q274:
What is the difference between mutable and immutable objects in Python?
Ans:
Mutable objects (like lists, dicts, sets) can be changed after creation without changing their identity, while immutable objects (like int, str, tuple, frozenset) cannot be modified in place; any 'change' creates a new object.
PYTHON
#2.275
Q275:
What is the difference between type() and isinstance()?
Ans:
type() returns the exact type of an object and doesn't account for inheritance, while isinstance() checks whether an object is an instance of a class or any of its subclasses, making it preferred for type checks involving inheritance.
PYTHON
#2.276
Q276:
What is the difference between Python 2 and Python 3?
Ans:
Python 3 introduced print as a function (not a statement), true division by default with /, unicode strings by default, and removed several Python 2-only constructs; Python 2 reached end-of-life in January 2020 and is no longer maintained.
PYTHON
#2.277
Q277:
What is the purpose of the if __name__ == '__main__': idiom?
Ans:
This checks whether a script is being run directly (in which case __name__ equals '__main__') versus being imported as a module, allowing code to execute only when the file is run directly.
Code Example
if __name__ == '__main__':
main()
PYTHON
#2.278
Q278:
What is the walrus operator in Python?
Ans:
The walrus operator (:=), introduced in Python 3.8, allows assignment of a value to a variable as part of a larger expression, useful for reducing repeated computation in conditions and loops.
Code Example
if (n := len(data)) > 10:
print(f'List is too long: {n} elements')
PYTHON
#2.279
Q279:
What is type hinting in Python?
Ans:
Type hints, introduced in PEP 484, allow optionally annotating variables, function parameters, and return values with expected types, improving readability and enabling static type checking tools like mypy, without enforcing types at runtime.
Code Example
def greet(name: str) -> str:
return f'Hello, {name}'
PYTHON
#2.280
Q280:
Does Python enforce type hints at runtime?
Ans:
No, type hints are not enforced by the Python interpreter at runtime; they serve as documentation and are checked by external static analysis tools like mypy or IDEs.
PYTHON
#2.281
Q281:
What is the difference between 'and'/'or' and '&'/'|' in Python?
Ans:
'and'/'or' are logical operators that short-circuit and work with any truthy/falsy values, while '&'/'|' are bitwise operators performing bit-level operations (and are also overloaded for set operations).
PYTHON
#2.282
Q282:
Does Python support a do-while loop?
Ans:
Python has no built-in do-while construct; the equivalent behavior can be simulated using a while True loop with a break condition at the end.
Code Example
while True:
process()
if not condition:
break
PYTHON
#2.283
Q283:
What are *args and **kwargs used for?
Ans:
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary, allowing functions to accept a variable number of arguments.
Code Example
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, name='Tom')
PYTHON
#2.284
Q284:
What is the difference between a lambda function and a regular function?
Ans:
A lambda function is restricted to a single expression and has no name (unless assigned to a variable), while a regular function defined with def can contain multiple statements, have a docstring, and supports more complex logic.
PYTHON
#2.285
Q285:
What is variable scope in Python (LEGB rule)?
Ans:
Python resolves variable names using the LEGB rule: Local (current function), Enclosing (any enclosing function), Global (module level), and Built-in (Python's built-in namespace), searched in that order.
PYTHON
#2.286
Q286:
What is the global keyword used for?
Ans:
The global keyword inside a function declares that an assignment to a variable should modify the variable in the global (module-level) scope rather than creating a new local variable.
Code Example
counter = 0
def increment():
global counter
counter += 1
PYTHON
#2.287
Q287:
What is the nonlocal keyword used for?
Ans:
nonlocal, introduced in Python 3, allows a nested function to modify a variable defined in its nearest enclosing (non-global) scope rather than creating a new local variable.
Code Example
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
return count
PYTHON
#2.288
Q288:
What is a closure in Python?
Ans:
A closure is a nested function that captures and remembers the values of variables from its enclosing scope, even after the outer function has finished executing.
Code Example
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
times3 = make_multiplier(3)
print(times3(5)) # 15
PYTHON
#2.289
Q289:
What is a decorator in Python?
Ans:
A decorator is a function that takes another function (or class) as input and extends or modifies its behavior without permanently changing its source code, applied using the @decorator syntax.
Code Example
def logger(func):
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@logger
def greet():
print('Hello')
PYTHON
#2.290
Q290:
What is a recursive function in Python?
Ans:
A recursive function calls itself to solve smaller instances of a problem, requiring a base case to terminate the recursion and avoid infinite calls.
Code Example
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
PYTHON
#2.291
Q291:
What are type hints for function parameters and return values?
Ans:
Type hints annotate expected parameter and return types using a colon after parameters and an arrow (->) before the return type, aiding readability and static analysis without runtime enforcement.
Code Example
def add(a: int, b: int) -> int:
return a + b
PYTHON
#2.292
Q292:
What is the difference between str.find() and str.index()?
Ans:
Both search for a substring's position, but find() returns -1 if not found, while index() raises a ValueError if the substring is not present.
PYTHON
#2.293
Q293:
What is the difference between str.replace() and regular expression substitution?
Ans:
str.replace() performs simple literal substring replacement, while re.sub() uses regular expression patterns, allowing more complex and flexible matching and replacement rules.
PYTHON
#2.294
Q294:
How do you format strings using the .format() method?
Ans:
The .format() method substitutes placeholders {} in a string with provided arguments, supporting positional and keyword references.
Code Example
'{} is {} years old'.format('Tom', 25)
PYTHON
#2.295
Q295:
What is the difference between f-strings, .format(), and % formatting?
Ans:
% formatting is the oldest, printf-style approach; .format() is more flexible and readable with named/positional placeholders; f-strings (Python 3.6+) are the most modern, concise, and generally fastest, embedding expressions directly.
PYTHON
#2.296
Q296:
Are strings mutable in Python?
Ans:
No, strings in Python are immutable; any operation that appears to modify a string actually creates and returns a new string object.
PYTHON
#2.297
Q297:
How do you check if a string is numeric?
Ans:
str.isdigit(), str.isnumeric(), or str.isdecimal() check whether a string consists only of digit characters, with subtle differences in which Unicode characters they accept.
PYTHON
#2.298
Q298:
What is a list comprehension in Python?
Ans:
A list comprehension provides a concise syntax to create a new list by applying an expression to each item of an iterable, optionally with a filtering condition.
Code Example
squares = [x**2 for x in range(10) if x % 2 == 0]
PYTHON
#2.299
Q299:
What is a dictionary comprehension?
Ans:
Similar to a list comprehension, it constructs a dictionary by applying key and value expressions to items from an iterable, using curly brace syntax.
Code Example
squares = {x: x**2 for x in range(5)}
PYTHON
#2.300
Q300:
What is a set comprehension?
Ans:
It builds a set using an expression applied to items in an iterable, enclosed in curly braces, automatically removing duplicate results.
Code Example
unique_lengths = {len(word) for word in ['cat', 'dog', 'ox']}
PYTHON
#2.301
Q301:
What is a generator expression?
Ans:
A generator expression uses syntax similar to a list comprehension but with parentheses, producing values lazily one at a time instead of building the entire list in memory at once.
Code Example
gen = (x**2 for x in range(1000000)) # lazy, memory-efficient
PYTHON
#2.302
Q302:
What is the difference between a list comprehension and a generator expression?
Ans:
A list comprehension eagerly builds and stores the entire list in memory, while a generator expression produces items lazily on demand, using significantly less memory for large or infinite sequences.
PYTHON
#2.303
Q303:
What is a frozenset?
Ans:
A frozenset is an immutable version of a set; once created, its elements cannot be added or removed, and it can be used as a dictionary key or set element since it's hashable.
PYTHON
#2.304
Q304:
How do you remove duplicates from a list?
Ans:
Converting the list to a set and back to a list removes duplicates, though this does not preserve order; using dict.fromkeys(list) preserves insertion order in Python 3.7+.
Code Example
unique = list(dict.fromkeys([3, 1, 2, 1, 3])) # [3, 1, 2]
PYTHON
#2.305
Q305:
What is the setdefault() method used for in a dictionary?
Ans:
dict.setdefault(key, default) returns the value for a key if it exists; otherwise, it inserts the key with the given default value and then returns that default.
Code Example
counts = {}
counts.setdefault('a', 0)
counts['a'] += 1
PYTHON
#2.306
Q306:
What is collections.defaultdict used for?
Ans:
defaultdict from the collections module automatically creates a default value for a missing key using a factory function, avoiding manual key-existence checks.
Code Example
from collections import defaultdict
counts = defaultdict(int)
counts['apple'] += 1 # no KeyError
PYTHON
#2.307
Q307:
What is collections.Counter used for?
Ans:
Counter is a dict subclass specialized for counting hashable items, automatically tallying occurrences and providing methods like most_common().
Code Example
from collections import Counter
c = Counter(['a', 'b', 'a', 'c', 'a'])
print(c.most_common(1)) # [('a', 3)]
PYTHON
#2.308
Q308:
What is collections.namedtuple used for?
Ans:
namedtuple creates lightweight, immutable tuple subclasses with named fields, allowing access to elements by name rather than only by index, improving code readability.
Code Example
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
PYTHON
#2.309
Q309:
What is the difference between a shallow copy and a deep copy in Python?
Ans:
A shallow copy (via copy.copy() or slicing) creates a new outer object but shares references to any nested objects, while a deep copy (via copy.deepcopy()) recursively copies nested objects as well, producing a fully independent structure.
Code Example
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
PYTHON
#2.310
Q310:
How do you sort a list of dictionaries by a specific key?
Ans:
You use sorted() or list.sort() with a key function, often a lambda that extracts the desired field from each dictionary.
Code Example
people = [{'name': 'Bob', 'age': 25}, {'name': 'Amy', 'age': 22}]
people.sort(key=lambda p: p['age'])
PYTHON
#2.311
Q311:
What is tuple unpacking in Python?
Ans:
Tuple unpacking assigns each element of a tuple (or any iterable) to separate variables in a single statement, and can use a starred expression to capture remaining elements.
Code Example
a, b, c = (1, 2, 3)
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
PYTHON
#2.312
Q312:
Why are tuples generally faster than lists for fixed collections of data?
Ans:
Tuples are immutable, allowing Python to allocate a fixed amount of memory and perform certain optimizations, and their hashability (when containing only hashable elements) allows use as dictionary keys, unlike lists.
PYTHON
#2.313
Q313:
How do you merge two dictionaries in Python?
Ans:
You can use the {**dict1, **dict2} unpacking syntax, the dict1.update(dict2) method, or the | merge operator introduced in Python 3.9.
Code Example
merged = {**dict1, **dict2}
merged2 = dict1 | dict2 # Python 3.9+
PYTHON
#2.314
Q314:
How do you check if all or any elements of an iterable satisfy a condition?
Ans:
all() returns True if every element is truthy (or satisfies a condition when combined with a generator expression), and any() returns True if at least one element is truthy.
Code Example
print(all(x > 0 for x in [1, 2, 3])) # True
print(any(x < 0 for x in [1, 2, -3])) # True
PYTHON
#2.315
Q315:
What does the zip() function do?
Ans:
zip() combines multiple iterables element-wise into tuples, stopping at the shortest input iterable, and is often used to iterate over parallel sequences together.
Code Example
names = ['Alice', 'Bob']
ages = [30, 25]
for name, age in zip(names, ages):
print(name, age)
PYTHON
#2.316
Q316:
What is the difference between map(), filter(), and a list comprehension?
Ans:
map() applies a function to every item of an iterable, filter() selects items matching a predicate, and both return iterators requiring conversion to a list; a list comprehension often achieves the same result more readably in a single expression.
Code Example
squares = list(map(lambda x: x**2, [1,2,3]))
evens = list(filter(lambda x: x % 2 == 0, [1,2,3,4]))
PYTHON
#2.317
Q317:
What does the functools.reduce() function do?
Ans:
reduce(), found in the functools module, applies a function cumulatively to the items of an iterable, reducing it to a single accumulated value.
Code Example
from functools import reduce
total = reduce(lambda a, b: a + b, [1, 2, 3, 4]) # 10
PYTHON
#2.318
Q318:
What is the difference between an instance attribute and a class attribute?
Ans:
An instance attribute belongs to a specific object and is usually set in __init__ via self, while a class attribute is shared across all instances of the class and is defined directly in the class body.
Code Example
class Dog:
species = 'Canine' # class attribute
def __init__(self, name):
self.name = name # instance attribute
PYTHON
#2.319
Q319:
How do you call a parent class's method from a subclass?
Ans:
The super() function returns a proxy object that allows calling methods of the parent class, commonly used to extend __init__ or override behavior while still invoking the parent's implementation.
Code Example
class Dog(Animal):
def __init__(self, name):
super().__init__()
self.name = name
PYTHON
#2.320
Q320:
Does Python support multiple inheritance?
Ans:
Yes, a Python class can inherit from multiple parent classes by listing them in parentheses, separated by commas, with method resolution order (MRO) determining which parent's method is used in case of conflicts.
Code Example
class Flying:
def move(self): print('Fly')
class Swimming:
def move(self): print('Swim')
class Duck(Flying, Swimming):
pass
PYTHON
#2.321
Q321:
Does Python support method overloading like Java or C++?
Ans:
Python does not support traditional method overloading with multiple same-named methods differing by parameter types; instead, default arguments, *args/**kwargs, or the functools.singledispatch decorator are used to achieve similar flexibility.
PYTHON
#2.322
Q322:
What are dunder (magic) methods in Python?
Ans:
Dunder methods, named with leading and trailing double underscores (like __init__, __str__, __len__), allow classes to define custom behavior for built-in operations such as printing, indexing, or arithmetic.
PYTHON
#2.323
Q323:
What is the difference between __str__ and __repr__?
Ans:
__str__ returns a readable, user-friendly string representation of an object (used by print() and str()), while __repr__ returns an unambiguous, developer-oriented representation (used by repr() and the interactive shell), ideally one that could recreate the object.
Code Example
class Point:
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __str__(self):
return f'({self.x}, {self.y})'
PYTHON
#2.324
Q324:
What is the __eq__ method used for?
Ans:
__eq__ defines custom behavior for the == operator, allowing objects to be compared based on their attribute values rather than default identity comparison.
Code Example
class Point:
def __eq__(self, other):
return self.x == other.x and self.y == other.y
PYTHON
#2.325
Q325:
What is a property in Python and how do you use the @property decorator?
Ans:
@property allows a method to be accessed like an attribute, enabling computed attributes and validation logic while still allowing get/set access with a natural attribute syntax.
Code Example
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14159 * self._radius ** 2
PYTHON
#2.326
Q326:
How do you create a read-only property with a corresponding setter?
Ans:
You define a method decorated with @property for the getter, and another method with the same name decorated with @propertyname.setter to allow controlled assignment.
Code Example
class Circle:
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError('Radius cannot be negative')
self._radius = value
PYTHON
#2.327
Q327:
What is the difference between a class method and a static method?
Ans:
A class method (decorated with @classmethod) receives the class itself as its first argument (cls) and can access/modify class state, while a static method (decorated with @staticmethod) receives neither self nor cls and behaves like a plain function namespaced within the class.
Code Example
class MyClass:
@classmethod
def create(cls):
return cls()
@staticmethod
def helper():
return 'helper'
PYTHON
#2.328
Q328:
What is an abstract base class (ABC) in Python?
Ans:
An abstract base class, defined using the abc module, cannot be instantiated directly and can declare abstract methods (via @abstractmethod) that subclasses must implement, enforcing a contract similar to interfaces.
Code Example
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
PYTHON
#2.329
Q329:
What is duck typing in Python?
Ans:
Duck typing means an object's suitability for use is determined by whether it has the required methods and properties, rather than its explicit type or inheritance ('if it walks like a duck and quacks like a duck...').
PYTHON
#2.330
Q330:
What is encapsulation in Python, given it has no true private keyword?
Ans:
Python uses naming conventions to indicate intended visibility: a single leading underscore (_var) signals 'protected'/internal use, and a double leading underscore (__var) triggers name mangling to make accidental external access harder, though nothing is truly enforced by the language.
PYTHON
#2.331
Q331:
What is operator overloading in Python?
Ans:
Operator overloading allows custom classes to define behavior for built-in operators (+, -, ==, etc.) by implementing the corresponding dunder methods like __add__ or __sub__.
Code Example
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
PYTHON
#2.332
Q332:
What is composition versus inheritance in Python OOP design?
Ans:
Composition builds objects by combining other objects as attributes (a 'has-a' relationship), offering more flexibility and less coupling, while inheritance establishes an 'is-a' relationship that can create rigid, tightly coupled hierarchies if overused.
PYTHON
#2.333
Q333:
What are data classes in Python?
Ans:
Introduced in Python 3.7, the dataclasses module's @dataclass decorator automatically generates __init__, __repr__, and __eq__ methods for classes primarily used to store data, reducing boilerplate code.
Code Example
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
PYTHON
#2.334
Q334:
What is the difference between except Exception and a bare except:?
Ans:
except Exception catches most built-in exceptions but not system-exiting ones like SystemExit or KeyboardInterrupt, while a bare except: catches literally everything including those, which is generally discouraged as it can hide critical signals like Ctrl+C.
PYTHON
#2.335
Q335:
How do you raise a custom exception in Python?
Ans:
You define a class inheriting from Exception (or a more specific built-in exception), and use the raise statement to throw an instance of it.
Code Example
class InsufficientFundsError(Exception):
pass
raise InsufficientFundsError('Not enough balance')
PYTHON
#2.336
Q336:
What is the purpose of the finally block?
Ans:
The finally block contains code that always executes after the try/except blocks, regardless of whether an exception occurred, commonly used for cleanup like closing files or releasing resources.
PYTHON
#2.337
Q337:
What is the difference between an exception and an error in Python?
Ans:
In Python, virtually all runtime errors are represented as exceptions (instances of classes derived from BaseException); there isn't a strict separate 'Error' category as in some other languages, though names like TypeError and ValueError describe specific kinds of exceptions.
PYTHON
#2.338
Q338:
What is the else clause in a try statement used for?
Ans:
The else block executes only if the try block completes without raising an exception, useful for code that should run only on success but shouldn't be wrapped in the try (to avoid catching unrelated exceptions).
Code Example
try:
value = int(user_input)
except ValueError:
print('Invalid input')
else:
print(f'You entered {value}')
PYTHON
#2.339
Q339:
How do you catch multiple exception types in one except block?
Ans:
You specify a tuple of exception types in a single except clause, catching any exception matching one of those types.
Code Example
try:
risky_operation()
except (ValueError, TypeError) as e:
print(f'Error: {e}')
PYTHON
#2.340
Q340:
What is the base class for all built-in exceptions in Python?
Ans:
BaseException is the root class for all exceptions, with Exception being a subclass covering most standard, catchable exceptions (excluding things like SystemExit and KeyboardInterrupt).
PYTHON
#2.341
Q341:
What is a context manager in Python and what does the with statement do?
Ans:
A context manager defines __enter__ and __exit__ methods to manage setup and teardown of a resource; the with statement uses it to ensure the resource is properly cleaned up (like closing a file) even if an exception occurs.
Code Example
with open('file.txt') as f:
data = f.read()
# file automatically closed here
PYTHON
#2.342
Q342:
What is the difference between assert and raising an exception?
Ans:
assert is primarily intended for internal self-checks and debugging, raising an AssertionError if the condition is false, and can be globally disabled with the -O optimization flag; explicit exceptions should be used for expected error conditions in production logic.
Code Example
assert age >= 0, 'Age cannot be negative'
PYTHON
#2.343
Q343:
What is an iterable in Python?
Ans:
An iterable is any object capable of returning its elements one at a time, implementing the __iter__ method (which returns an iterator), such as lists, tuples, strings, and dictionaries.
PYTHON
#2.344
Q344:
What is an iterator in Python?
Ans:
An iterator is an object implementing both __iter__ (returning itself) and __next__ (returning the next value or raising StopIteration when exhausted), produced by calling iter() on an iterable.
Code Example
it = iter([1, 2, 3])
print(next(it)) # 1
print(next(it)) # 2
PYTHON
#2.345
Q345:
What is the difference between an iterable and an iterator?
Ans:
An iterable can produce an iterator (via __iter__) but doesn't track iteration state itself, while an iterator maintains internal state and produces the next value each time __next__ is called, eventually raising StopIteration.
PYTHON
#2.346
Q346:
What is a generator function in Python?
Ans:
A generator function uses the yield keyword instead of return to produce a sequence of values lazily, pausing its state between each yielded value and resuming on the next call to next().
Code Example
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up(5):
print(num)
PYTHON
#2.347
Q347:
What is the difference between yield and return in a generator?
Ans:
return exits a function immediately and (in a generator) raises StopIteration, while yield pauses the function, returns a value to the caller, and preserves the function's state to resume execution on the next call.
PYTHON
#2.348
Q348:
What are the benefits of using generators over lists?
Ans:
Generators produce values lazily on demand, using constant memory regardless of sequence size, making them ideal for large or infinite sequences and streaming data processing.
PYTHON
#2.349
Q349:
What is the itertools module used for?
Ans:
itertools provides a collection of fast, memory-efficient tools for creating and working with iterators, including functions like chain(), combinations(), permutations(), cycle(), and groupby().
Code Example
from itertools import chain
combined = list(chain([1,2], [3,4])) # [1,2,3,4]
PYTHON
#2.350
Q350:
What is the purpose of __init__.py?
Ans:
__init__.py marks a directory as a regular Python package, and can contain initialization code or define what's exposed when the package is imported, though it's optional for implicit namespace packages since Python 3.3.
PYTHON
#2.351
Q351:
What is the difference between an absolute import and a relative import?
Ans:
An absolute import specifies the full path from the project's root package (e.g., from mypackage.module import func), while a relative import uses dots to reference modules relative to the current package (e.g., from .module import func).
PYTHON
#2.352
Q352:
What is the sys.path variable used for?
Ans:
sys.path is a list of directory paths that Python searches when importing modules, including the script's directory, installed site-packages, and any paths added via PYTHONPATH.
PYTHON
#2.353
Q353:
What is the pathlib module used for?
Ans:
pathlib provides an object-oriented interface for handling filesystem paths, offering a more readable and cross-platform alternative to the older os.path functions.
Code Example
from pathlib import Path
p = Path('data') / 'file.txt'
print(p.suffix, p.parent)
PYTHON
#2.354
Q354:
How do you read a CSV file in Python?
Ans:
The built-in csv module provides csv.reader() and csv.DictReader() to parse CSV files, or the pandas library's read_csv() function for more advanced data analysis needs.
Code Example
import csv
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
PYTHON
#2.355
Q355:
How do you serialize and deserialize Python objects using pickle?
Ans:
The pickle module's dump()/dumps() functions serialize Python objects into a byte stream, and load()/loads() deserialize them back, though pickle should not be used with untrusted data due to security risks.
Code Example
import pickle
with open('data.pkl', 'wb') as f:
pickle.dump(my_object, f)
PYTHON
#2.356
Q356:
How do you create and start a thread in Python?
Ans:
You can use the threading module's Thread class, passing a target function, and call start() to begin execution and join() to wait for it to finish.
Code Example
import threading
def worker():
print('Working')
t = threading.Thread(target=worker)
t.start()
t.join()
PYTHON
#2.357
Q357:
How do you create a new process in Python using multiprocessing?
Ans:
You use the multiprocessing module's Process class similarly to threading.Thread, but each process runs in its own memory space and Python interpreter instance.
Code Example
from multiprocessing import Process
def worker():
print('Working')
p = Process(target=worker)
p.start()
p.join()
PYTHON
#2.358
Q358:
What is asyncio in Python?
Ans:
asyncio is a standard library module for writing concurrent code using the async/await syntax, based on an event loop that manages cooperative multitasking for I/O-bound operations without using multiple threads.
Code Example
import asyncio
async def main():
await asyncio.sleep(1)
print('Done')
asyncio.run(main())
PYTHON
#2.359
Q359:
What does the await keyword do in Python?
Ans:
await pauses execution of an async function until the awaited coroutine or future completes, yielding control back to the event loop so other tasks can run in the meantime.
PYTHON
#2.360
Q360:
What is the concurrent.futures module used for?
Ans:
concurrent.futures provides a high-level interface (ThreadPoolExecutor and ProcessPoolExecutor) for asynchronously executing callables using pools of threads or processes, simplifying common concurrency patterns.
Code Example
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_item, items))
PYTHON
#2.361
Q361:
How do you use regular expressions in Python?
Ans:
The re module provides functions like re.match(), re.search(), re.findall(), and re.sub() to work with regular expression patterns against strings.
Code Example
import re
if re.search(r'\d+', 'Order 123'):
print('Contains a number')
PYTHON
#2.362
Q362:
What is the difference between re.match() and re.search()?
Ans:
re.match() only checks for a match at the beginning of the string, while re.search() scans through the entire string looking for a match anywhere within it.
PYTHON
#2.363
Q363:
What does re.findall() return?
Ans:
re.findall() returns a list of all non-overlapping matches of a pattern in a string, or tuples of groups if the pattern contains multiple capturing groups.
Code Example
re.findall(r'\d+', 'a1 b22 c333') # ['1', '22', '333']
PYTHON
#2.364
Q364:
How do you replace text using a regular expression in Python?
Ans:
re.sub(pattern, replacement, string) replaces all occurrences of a pattern match with a replacement string, supporting backreferences to captured groups.
Code Example
re.sub(r'\d+', '#', 'Order 123 shipped') # 'Order # shipped'
PYTHON
#2.365
Q365:
What are capturing groups in a regex pattern?
Ans:
Capturing groups, defined using parentheses (), allow extracting specific portions of a match, accessible via group() on a Match object or as tuples from findall().
Code Example
m = re.search(r'(\d{3})-(\d{4})', '555-1234')
print(m.group(1), m.group(2)) # '555' '4234' style access
PYTHON
#2.366
Q366:
What is a raw string in Python and why is it used with regex?
Ans:
A raw string, prefixed with r, treats backslashes as literal characters rather than escape sequences, which is useful for regex patterns that heavily use backslashes (like \d or \s) to avoid double-escaping.
Code Example
pattern = r'\d+\s\w+'
PYTHON
#2.367
Q367:
What does the re.compile() function do?
Ans:
re.compile() precompiles a regex pattern into a Pattern object, which can be reused efficiently for multiple match operations without recompiling the pattern each time.
Code Example
pattern = re.compile(r'\d+')
pattern.findall('a1 b2')
PYTHON
#2.368
Q368:
What is unittest in Python?
Ans:
unittest is Python's built-in testing framework, providing a TestCase class with assertion methods (assertEqual, assertTrue, etc.) to structure and run automated tests.
Code Example
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
unittest.main()
PYTHON
#2.369
Q369:
What is pytest and how does it differ from unittest?
Ans:
pytest is a popular third-party testing framework that allows writing simpler test functions (without needing a TestCase class), uses plain assert statements, and offers powerful fixtures and plugins, generally considered more concise than unittest.
Code Example
def test_add():
assert 1 + 1 == 2
PYTHON
#2.370
Q370:
What is a fixture in pytest?
Ans:
A fixture is a function decorated with @pytest.fixture that provides reusable setup (and optional teardown) code for tests, injected as a parameter into test functions that need it.
Code Example
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
PYTHON
#2.371
Q371:
What is mocking in unit testing and what module provides it in Python?
Ans:
Mocking replaces real objects or functions with fake substitutes during testing to isolate the code under test from external dependencies; Python's unittest.mock module provides Mock and patch utilities for this purpose.
Code Example
from unittest.mock import patch
with patch('module.some_function', return_value=42):
result = module.some_function()
PYTHON
#2.372
Q372:
How do you debug a Python script interactively?
Ans:
You can insert breakpoint() (or import pdb; pdb.set_trace() in older versions) to pause execution and enter an interactive debugger, allowing you to inspect variables and step through code.
Code Example
def process(data):
breakpoint()
return data * 2
PYTHON
#2.373
Q373:
What is the purpose of logging in Python and how does it differ from using print()?
Ans:
The logging module provides configurable log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), timestamps, and output destinations (file, console, remote), making it far more suitable than print() for production diagnostics and long-term maintainability.
Code Example
import logging
logging.basicConfig(level=logging.INFO)
logging.info('Application started')
PYTHON
#2.374
Q374:
How does Python manage memory?
Ans:
Python uses automatic memory management via reference counting (tracking how many references point to an object) combined with a cyclic garbage collector to detect and clean up reference cycles that reference counting alone can't handle.
PYTHON
#2.375
Q375:
What is reference counting in Python?
Ans:
Reference counting tracks the number of references pointing to an object; when this count drops to zero, the object's memory is immediately deallocated.
PYTHON
#2.376
Q376:
What is the difference between deep copy and shallow copy in terms of memory?
Ans:
A shallow copy creates a new container object but still shares references to the same nested objects as the original, while a deep copy recursively duplicates all nested objects, using more memory but ensuring full independence.
PYTHON
#2.377
Q377:
What is the difference between is and == in terms of performance and correctness?
Ans:
'is' checks object identity (memory address) and is a very fast, simple pointer comparison, while '==' checks value equality and may invoke a custom __eq__ method, potentially being slower but more semantically correct for comparing values.
PYTHON
#2.378
Q378:
How can you profile the performance of Python code?
Ans:
You can use the built-in cProfile module to measure function call counts and execution time, or the timeit module to benchmark small code snippets precisely.
Code Example
import timeit
print(timeit.timeit('sum(range(100))', number=10000))
PYTHON
#2.379
Q379:
What is functools.lru_cache used for?
Ans:
lru_cache is a decorator that caches a function's return values based on its arguments, avoiding redundant computation for repeated calls with the same inputs, useful for optimizing expensive or recursive functions.
Code Example
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
PYTHON
#2.380
Q380:
What does functools.partial do?
Ans:
functools.partial creates a new callable with some arguments of the original function pre-filled, useful for adapting a general function into a more specific one.
Code Example
from functools import partial
square = partial(pow, exp=2)
# or: cube = partial(pow, 2, 3)
PYTHON
#2.381
Q381:
What is the difference between a shallow function (pure function) and one with side effects?
Ans:
A pure function's output depends only on its input arguments and it produces no observable side effects (like modifying global state or printing), making it easier to test and reason about, unlike functions that mutate external state.
PYTHON
#2.382
Q382:
What does the * unpacking operator do when calling a function?
Ans:
Prefixing an iterable with * when calling a function unpacks its elements as separate positional arguments, and ** does the same for a dictionary's items as keyword arguments.
Code Example
def add(a, b, c):
return a + b + c
args = [1, 2, 3]
print(add(*args))
PYTHON
#2.383
Q383:
What is the difference between shallow equality and deep equality for nested data structures?
Ans:
Shallow equality compares only the immediate elements (often by identity for containers), while deep equality (Python's default == for lists/dicts) recursively compares all nested elements' values for equality.
PYTHON
#2.384
Q384:
What is the difference between a shallow module-level variable and a class attribute in terms of scope?
Ans:
A module-level variable is accessible throughout the module (and importable elsewhere), while a class attribute is scoped to the class and its instances, accessed via the class name or an instance.
PYTHON
#2.385
Q385:
What is the Singleton design pattern and how can it be implemented in Python?
Ans:
Singleton ensures a class has only one instance; in Python it can be implemented by overriding __new__ to return a cached instance, using a module (which is naturally a singleton), or using a decorator/metaclass.
PYTHON
#2.386
Q386:
What is the difference between == overloading via __eq__ and default object comparison?
Ans:
By default, objects are compared by identity (memory address) unless __eq__ is overridden to define custom value-based equality logic, such as comparing specific attributes.
PYTHON
#2.387
Q387:
What is the difference between a module-level '__all__' variable's purpose?
Ans:
__all__ is a list of strings defining which names are exported when a module is imported using 'from module import *', controlling the public API surface exposed via wildcard imports.
Code Example
__all__ = ['public_function', 'PublicClass']
PYTHON
#2.388
Q388:
What is the difference between shallow argument unpacking with * in function definitions versus function calls?
Ans:
In a function definition, *args collects extra positional arguments into a tuple; in a function call, *iterable unpacks an iterable's elements as separate positional arguments being passed in.
PYTHON
#2.389
Q389:
What does the built-in id() function return?
Ans:
id() returns a unique integer identifier for an object, representing its memory address in CPython, which remains constant during the object's lifetime.
PYTHON
#2.390
Q390:
What is the difference between shallow copying a dictionary using dict(d) versus d.copy()?
Ans:
Both dict(d) and d.copy() produce a shallow copy of the dictionary with the same top-level key-value pairs but shared references to any nested mutable objects; they are functionally equivalent for this purpose.
PYTHON
#2.391
Q391:
What is the difference between os.system() and subprocess.run() for running shell commands?
Ans:
subprocess.run() is the modern, more flexible and secure way to execute external commands, providing better control over input/output/error streams and avoiding some shell injection risks compared to the older, more limited os.system().
Code Example
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
PYTHON
#2.392
Q392:
What is the difference between shallow slicing and using the copy module for lists?
Ans:
Slicing an entire list (my_list[:]) creates a shallow copy similar to copy.copy(), sharing references to nested objects, while copy.deepcopy() is needed if you require independent nested objects as well.
NODE.JS
#2.393
Q393:
Is Node.js single-threaded or multi-threaded?
Ans:
Node.js runs JavaScript code on a single main thread, but uses a libuv thread pool internally for certain operations (like file I/O and some crypto functions), and can leverage multiple processes/threads via clustering or worker_threads.
NODE.JS
#2.394
Q394:
What is the difference between npm and npx?
Ans:
npm installs and manages packages, while npx executes a package's binary directly, optionally downloading it temporarily without a permanent install, useful for running one-off CLI tools.
Code Example
npx create-react-app my-app
NODE.JS
#2.395
Q395:
What is package-lock.json used for?
Ans:
package-lock.json records the exact dependency tree and resolved versions installed, ensuring consistent installs across different machines and environments.
NODE.JS
#2.396
Q396:
What is semantic versioning (semver) and how does npm use it?
Ans:
Semantic versioning uses a MAJOR.MINOR.PATCH format; npm uses prefixes like ^ (compatible with minor/patch updates) and ~ (compatible with patch updates only) in package.json to control how dependencies are updated.
NODE.JS
#2.397
Q397:
What is the difference between CommonJS and ES Modules in Node.js?
Ans:
CommonJS uses require()/module.exports and loads modules synchronously, while ES Modules use import/export syntax, support static analysis and tree-shaking, and are loaded asynchronously; Node.js supports both, with ESM requiring a .mjs extension or type module in package.json.
Code Example
// CommonJS
module.exports = myFunction;
// ES Modules
export default myFunction;
NODE.JS
#2.398
Q398:
What is the difference between module.exports and exports?
Ans:
Both initially reference the same object, but reassigning exports to a new object breaks its link to module.exports; only the object referenced by module.exports at the end is actually exported, so exports should only be used to add properties, not reassigned.
NODE.JS
#2.399
Q399:
What is the global object in Node.js?
Ans:
In Node.js, the global object provides variables and functions available everywhere without needing to require them, such as process, console, setTimeout, and __dirname/__filename (module-scoped, not truly global).
NODE.JS
#2.400
Q400:
What is the process object in Node.js?
Ans:
process is a global object providing information about and control over the current Node.js process, including process.argv (command-line arguments), process.env (environment variables), and process.exit().
Code Example
console.log(process.env.NODE_ENV);
console.log(process.argv);
NODE.JS
#2.401
Q401:
What is the difference between Node.js and Deno?
Ans:
Deno is a newer JavaScript/TypeScript runtime created by Node.js's original author, offering built-in TypeScript support, secure-by-default permissions, and ES module imports via URLs, whereas Node.js uses npm and CommonJS/ESM with a more mature ecosystem.
NODE.JS
#2.402
Q402:
What is the event loop in Node.js?
Ans:
The event loop is the core mechanism that allows Node.js to perform non-blocking I/O operations by offloading tasks to the system and executing callbacks once those tasks complete, despite JavaScript being single-threaded.
NODE.JS
#2.403
Q403:
What is callback hell and how can it be avoided?
Ans:
Callback hell refers to deeply nested callbacks that make code hard to read and maintain, typically arising from chaining multiple asynchronous operations; it can be avoided using Promises, async/await, or named functions instead of nested anonymous callbacks.
NODE.JS
#2.404
Q404:
What is a Promise in JavaScript/Node.js?
Ans:
A Promise represents the eventual result (or failure) of an asynchronous operation, existing in one of three states: pending, fulfilled, or rejected, and providing .then()/.catch()/.finally() for handling outcomes.
Code Example
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
NODE.JS
#2.405
Q405:
What is async/await in Node.js?
Ans:
async/await is syntactic sugar built on Promises, allowing asynchronous code to be written in a more synchronous-looking style; an async function always returns a Promise, and await pauses execution until a Promise resolves.
Code Example
async function getData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
}
}
NODE.JS
#2.406
Q406:
What is the difference between Promise.all() and Promise.allSettled()?
Ans:
Promise.all() resolves when all promises fulfill, but rejects immediately if any single promise rejects; Promise.allSettled() waits for all promises to complete regardless of outcome, returning an array of each result's status (fulfilled or rejected).
Code Example
const results = await Promise.allSettled([p1, p2, p3]);
NODE.JS
#2.407
Q407:
How do you convert a callback-based function to a Promise-based one?
Ans:
You can wrap the function in a new Promise, resolving or rejecting inside the callback, or use Node's built-in util.promisify() utility for standard error-first callback functions.
Code Example
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
const data = await readFileAsync('file.txt');
NODE.JS
#2.408
Q408:
Why is Node.js good for I/O-bound applications but less ideal for CPU-bound tasks?
Ans:
Node.js's non-blocking, event-driven architecture excels at handling many concurrent I/O operations efficiently on a single thread, but CPU-intensive synchronous computations block the event loop, delaying all other pending operations until the computation finishes.
NODE.JS
#2.409
Q409:
What is the EventEmitter class in Node.js?
Ans:
EventEmitter is a core Node.js class (from the events module) that implements the observer pattern, allowing objects to emit named events and register listener functions to respond to them.
Code Example
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => console.log(`Hello, ${name}`));
emitter.emit('greet', 'World');
NODE.JS
#2.410
Q410:
What is the difference between .on() and .once() on an EventEmitter?
Ans:
.on() registers a listener that runs every time the event is emitted, while .once() registers a listener that runs only the first time the event is emitted and is then automatically removed.
NODE.JS
#2.411
Q411:
How do you remove an event listener in Node.js?
Ans:
You can use emitter.removeListener(event, listener) or emitter.off(event, listener) to remove a specific listener, or removeAllListeners() to remove all listeners for an event.
Code Example
emitter.off('greet', myListener);
NODE.JS
#2.412
Q412:
Why is the event-driven architecture central to Node.js?
Ans:
Node.js's core APIs (like streams, HTTP servers, and file operations) are built around EventEmitter and callbacks, allowing the runtime to efficiently notify application code when asynchronous operations complete without blocking the main thread.
NODE.JS
#2.413
Q413:
What is module caching in Node.js?
Ans:
After a module is required once, Node.js caches the exported object; subsequent require() calls for the same file return the cached instance rather than re-executing the module's code.
NODE.JS
#2.414
Q414:
What is a scoped npm package?
Ans:
A scoped package is namespaced under an organization or username using the @scope/package-name format, helping avoid naming collisions and grouping related packages, such as @angular/core.
NODE.JS
#2.415
Q415:
What is the fs.promises API?
Ans:
fs.promises (or require('fs/promises')) provides Promise-based versions of the fs module's methods, allowing them to be used with async/await instead of callbacks.
Code Example
const fs = require('fs/promises');
const data = await fs.readFile('data.txt', 'utf8');
NODE.JS
#2.416
Q416:
What is a Stream in Node.js?
Ans:
A Stream is an abstract interface for working with streaming data, processing it piece by piece (in chunks) rather than loading everything into memory at once, useful for large files or network data.
NODE.JS
#2.417
Q417:
What are the four types of streams in Node.js?
Ans:
Node.js has Readable streams (data source, like fs.createReadStream), Writable streams (data destination), Duplex streams (both readable and writable, like a TCP socket), and Transform streams (a duplex stream that modifies data as it passes through, like zlib compression).
NODE.JS
#2.418
Q418:
What is the pipe() method used for in Node.js streams?
Ans:
pipe() connects a readable stream's output directly to a writable stream's input, automatically managing data flow and backpressure without manual event handling.
Code Example
const fs = require('fs');
fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));
NODE.JS
#2.419
Q419:
What is a Buffer in Node.js?
Ans:
A Buffer is a Node.js class for handling raw binary data directly in memory, used when working with streams, files, or network protocols where data isn't naturally represented as UTF-8 text.
Code Example
const buf = Buffer.from('Hello', 'utf8');
console.log(buf); // <Buffer 48 65 6c 6c 6f>
NODE.JS
#2.420
Q420:
What is the difference between a Buffer and a String in Node.js?
Ans:
A Buffer stores raw binary data as a fixed-length sequence of bytes, while a String represents text encoded in a specific character encoding (typically UTF-16 internally in JS); Buffers must be explicitly converted to strings using a specified encoding.
NODE.JS
#2.421
Q421:
How do you watch a file or directory for changes in Node.js?
Ans:
The fs.watch() function monitors a file or directory for changes, invoking a callback with the event type (rename or change) and filename whenever a modification is detected.
Code Example
fs.watch('config.json', (eventType, filename) => {
console.log(`${filename} changed: ${eventType}`);
});
NODE.JS
#2.422
Q422:
What is middleware in Express.js?
Ans:
Middleware functions are functions that have access to the request, response, and the next middleware function in the application's request-response cycle, used for tasks like logging, authentication, and parsing request bodies.
Code Example
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
NODE.JS
#2.423
Q423:
What is the purpose of the next() function in Express middleware?
Ans:
next() passes control to the next middleware function in the stack; if not called (and the response isn't sent), the request will hang and never complete.
NODE.JS
#2.424
Q424:
How do you handle errors in Express.js?
Ans:
Express uses special error-handling middleware functions with four parameters (err, req, res, next), placed after all other routes/middleware, to catch and respond to errors passed via next(err) or thrown in async handlers (with proper setup).
Code Example
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
NODE.JS
#2.425
Q425:
What is the difference between app.use() and app.get() in Express?
Ans:
app.use() mounts middleware for all HTTP methods (and optionally a specific path prefix), while app.get() (and similar methods like post, put, delete) registers a handler specifically for that HTTP method and exact route.
NODE.JS
#2.426
Q426:
What is CORS and how do you enable it in an Express app?
Ans:
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different domain than the one that served them; it can be enabled in Express using the cors npm package or by manually setting appropriate response headers.
Code Example
const cors = require('cors');
app.use(cors());
NODE.JS
#2.427
Q427:
What is a REST API and how does Express help build one?
Ans:
A REST API exposes resources via HTTP endpoints using standard methods (GET, POST, PUT, DELETE) mapped to CRUD operations; Express simplifies building REST APIs through its intuitive routing system and middleware ecosystem.
NODE.JS
#2.428
Q428:
How do you organize routes in a larger Express application?
Ans:
You can use express.Router() to create modular, mountable route handlers grouped by resource or feature, keeping the main app file clean and organized.
Code Example
const router = express.Router();
router.get('/', (req, res) => res.send('User list'));
app.use('/users', router);
NODE.JS
#2.429
Q429:
How do you handle errors in asynchronous callback-based Node.js code?
Ans:
Node.js conventionally uses the 'error-first callback' pattern, where the first argument to a callback is reserved for an error object (or null if no error occurred), which must be checked explicitly.
Code Example
fs.readFile('file.txt', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
NODE.JS
#2.430
Q430:
How do you handle errors in async/await functions?
Ans:
You wrap the awaited code in a try-catch block, since a rejected awaited Promise throws an exception that can be caught synchronously within the async function.
Code Example
async function run() {
try {
const data = await fetchData();
} catch (err) {
console.error(err);
}
}
NODE.JS
#2.431
Q431:
How do you create a custom error class in Node.js?
Ans:
You create a class extending the built-in Error class, calling super(message) in the constructor and optionally adding custom properties like a status code.
Code Example
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
this.statusCode = 404;
}
}
NODE.JS
#2.432
Q432:
What testing frameworks are commonly used with Node.js?
Ans:
Popular Node.js testing frameworks include Jest, Mocha (often paired with Chai for assertions and Sinon for mocking), and the built-in node:test module introduced in recent Node.js versions.
NODE.JS
#2.433
Q433:
How do you write a basic unit test using Jest?
Ans:
You use Jest's test() or it() function with a description and a callback containing assertions made with expect().
Code Example
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
NODE.JS
#2.434
Q434:
What is mocking in the context of Node.js testing?
Ans:
Mocking replaces real dependencies (like database calls or external APIs) with fake implementations during tests, isolating the code under test and making tests faster and more predictable.
Code Example
jest.mock('./db');
db.getUser.mockResolvedValue({ id: 1, name: 'Tom' });
NODE.JS
#2.435
Q435:
How do you debug a Node.js application?
Ans:
You can use the built-in inspector by running 'node --inspect app.js' and connecting Chrome DevTools, use console.log statements, or use an IDE's integrated debugger (like VS Code) with breakpoints.
Code Example
node --inspect-brk app.js
NODE.JS
#2.436
Q436:
What is the difference between console.log() and a proper logging library like Winston or Pino?
Ans:
console.log() is simple but lacks log levels, structured output, and performance optimizations, while libraries like Winston or Pino provide configurable log levels, structured JSON output, and better performance for production logging needs.
NODE.JS
#2.437
Q437:
What is the child_process module used for?
Ans:
child_process allows Node.js to spawn and interact with new OS-level processes, useful for running shell commands, executing other programs, or offloading CPU-intensive work.
Code Example
const { exec } = require('child_process');
exec('ls -la', (err, stdout) => console.log(stdout));
NODE.JS
#2.438
Q438:
What are common security best practices for Node.js applications?
Ans:
Best practices include validating and sanitizing all user input, using parameterized queries to prevent SQL injection, keeping dependencies updated, setting secure HTTP headers (e.g., via helmet), rate-limiting requests, and never exposing detailed error stack traces to clients in production.
NODE.JS
#2.439
Q439:
What is the helmet package used for in Express applications?
Ans:
helmet is a middleware collection that sets various HTTP security headers (like Content-Security-Policy and X-Frame-Options) to help protect Express apps from well-known web vulnerabilities.
Code Example
const helmet = require('helmet');
app.use(helmet());
NODE.JS
#2.440
Q440:
How do you prevent SQL injection in a Node.js application?
Ans:
You should use parameterized queries or prepared statements provided by your database driver or ORM (like pg, mysql2, or Sequelize) instead of concatenating user input directly into SQL strings.
Code Example
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
NODE.JS
#2.441
Q441:
How do you securely store passwords in a Node.js application?
Ans:
Passwords should be hashed using a strong, slow hashing algorithm like bcrypt (via the bcrypt or bcryptjs package), never stored in plain text or reversibly encrypted.
Code Example
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 10);
const match = await bcrypt.compare(inputPassword, hash);
NODE.JS
#2.442
Q442:
What is JWT (JSON Web Token) and how is it used for authentication in Node.js?
Ans:
JWT is a compact, signed token format used to securely transmit claims (like user identity) between parties; in Node.js, libraries like jsonwebtoken create and verify tokens, commonly used for stateless authentication in APIs.
Code Example
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, secretKey, { expiresIn: '1h' });
const decoded = jwt.verify(token, secretKey);
NODE.JS
#2.443
Q443:
What is rate limiting and how can you implement it in an Express app?
Ans:
Rate limiting restricts how many requests a client can make within a given time window, protecting against abuse and denial-of-service attacks; it can be implemented with middleware like express-rate-limit.
Code Example
const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }));
NODE.JS
#2.444
Q444:
Why should NODE_ENV be set to 'production' in a production deployment?
Ans:
Setting NODE_ENV=production enables performance optimizations in frameworks like Express (such as view caching) and signals libraries to disable verbose debugging output, improving both speed and security.
NODE.JS
#2.445
Q445:
How do you connect to a MongoDB database in Node.js?
Ans:
You can use the official MongoDB Node.js driver directly, or an ODM (Object Document Mapper) like Mongoose, which provides schema definitions and validation on top of MongoDB.
Code Example
const mongoose = require('mongoose');
await mongoose.connect('mongodb://localhost:27017/mydb');
NODE.JS
#2.446
Q446:
What is Mongoose and what problem does it solve?
Ans:
Mongoose is an ODM library for MongoDB and Node.js that provides schema-based modeling for application data, including built-in type casting, validation, query building, and middleware hooks.
Code Example
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model('User', userSchema);
NODE.JS
#2.447
Q447:
How do you connect to a PostgreSQL or MySQL database in Node.js?
Ans:
You can use a database driver like pg (PostgreSQL) or mysql2 (MySQL) directly with connection pooling, or use an ORM like Sequelize, Prisma, or TypeORM for higher-level abstractions.
Code Example
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const result = await pool.query('SELECT * FROM users');
NODE.JS
#2.448
Q448:
What is an ORM and what are some popular options for Node.js?
Ans:
An ORM (Object-Relational Mapper) maps database tables to JavaScript objects/classes, abstracting raw SQL; popular Node.js options include Sequelize, TypeORM, and Prisma, each offering different styles of schema definition and query building.
NODE.JS
#2.449
Q449:
What is connection pooling and why is it important for database access in Node.js?
Ans:
Connection pooling maintains a set of reusable database connections instead of opening and closing a new connection for every query, reducing overhead and improving performance under concurrent load.
NODE.JS
#2.450
Q450:
How do you handle database transactions in Node.js?
Ans:
Most database drivers and ORMs provide transaction APIs (like a client.query('BEGIN')/COMMIT/ROLLBACK pattern with pg, or sequelize.transaction()) to group multiple operations so they either all succeed or all roll back together.
Code Example
await sequelize.transaction(async (t) => {
await Account.update({ balance: newBalance }, { transaction: t });
});
NODE.JS
#2.451
Q451:
What is a closure in JavaScript?
Ans:
A closure is a function that retains access to variables from its containing (outer) scope even after that outer function has finished executing.
Code Example
function counter() {
let count = 0;
return () => ++count;
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
NODE.JS
#2.452
Q452:
What is the 'this' keyword in JavaScript and how does it behave differently in arrow functions?
Ans:
'this' refers to the context in which a function is called, which can vary based on how the function is invoked; arrow functions do not have their own 'this' and instead lexically inherit it from the enclosing scope, unlike regular functions.
Code Example
const obj = {
name: 'Tom',
regular: function() { console.log(this.name); }, // 'Tom'
arrow: () => { console.log(this.name); } // undefined, inherits outer scope
};
NODE.JS
#2.453
Q453:
What is prototypal inheritance in JavaScript?
Ans:
JavaScript objects inherit properties and methods from a prototype object; when a property isn't found on an object, the JavaScript engine looks up the prototype chain until it finds the property or reaches null.
NODE.JS
#2.454
Q454:
What is the difference between a JavaScript class and a constructor function?
Ans:
ES6 classes are primarily syntactic sugar over JavaScript's existing prototype-based inheritance, providing a cleaner syntax for defining constructor functions and methods, though classes also enforce being called with 'new' and have stricter semantics.
Code Example
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a sound`); }
}
NODE.JS
#2.455
Q455:
What is destructuring assignment in JavaScript?
Ans:
Destructuring allows extracting values from arrays or properties from objects into distinct variables using a concise syntax.
Code Example
const { name, age } = person;
const [first, second] = [1, 2];
NODE.JS
#2.456
Q456:
What is the spread operator used for in JavaScript?
Ans:
The spread operator (...) expands an iterable (array, string) or object's own enumerable properties into individual elements, useful for copying, merging, or passing arguments.
Code Example
const arr2 = [...arr1, 4, 5];
const merged = { ...obj1, ...obj2 };
NODE.JS
#2.457
Q457:
What are JavaScript Promises' three states?
Ans:
A Promise can be pending (initial state, neither fulfilled nor rejected), fulfilled (operation completed successfully), or rejected (operation failed), and once settled (fulfilled or rejected), its state cannot change again.
NODE.JS
#2.458
Q458:
What is hoisting in JavaScript?
Ans:
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during compilation; var declarations are hoisted and initialized as undefined, function declarations are fully hoisted, while let/const are hoisted but remain uninitialized until their declaration line.
NODE.JS
#2.459
Q459:
What is an IIFE (Immediately Invoked Function Expression)?
Ans:
An IIFE is a function that is defined and executed immediately after its creation, often used to create a private scope and avoid polluting the global namespace.
Code Example
(function() {
console.log('Runs immediately');
})();
NODE.JS
#2.460
Q460:
How can you improve the performance of a Node.js application?
Ans:
Common strategies include using asynchronous non-blocking APIs, caching frequent results (e.g., with Redis), enabling gzip compression, using clustering to utilize multiple CPU cores, optimizing database queries, and profiling to find bottlenecks.
NODE.JS
#2.461
Q461:
What is PM2 and why is it used with Node.js applications?
Ans:
PM2 is a production process manager for Node.js applications that provides features like automatic restarts on crashes, load balancing across CPU cores (cluster mode), log management, and zero-downtime reloads.
Code Example
pm2 start app.js -i max
pm2 list
pm2 logs
NODE.JS
#2.462
Q462:
What is horizontal scaling versus vertical scaling for a Node.js application?
Ans:
Vertical scaling increases the resources (CPU, memory) of a single server instance, while horizontal scaling adds more instances of the application running behind a load balancer, which Node.js's stateless, clusterable nature is well suited for.
NODE.JS
#2.463
Q463:
What is a reverse proxy and why is it commonly used in front of Node.js applications?
Ans:
A reverse proxy (like Nginx) sits in front of the Node.js application, handling tasks like SSL termination, load balancing, static file serving, and request buffering, offloading work that Node.js doesn't need to handle directly.
NODE.JS
#2.464
Q464:
What is the purpose of compression middleware in an Express app?
Ans:
Compression middleware (like the compression npm package) gzips HTTP responses before sending them to the client, reducing payload size and improving load times over the network.
Code Example
const compression = require('compression');
app.use(compression());
NODE.JS
#2.465
Q465:
What is caching and how might you implement it in a Node.js API?
Ans:
Caching stores the results of expensive or frequently repeated operations (like database queries) so subsequent requests can be served faster; it can be implemented in-memory, or using an external store like Redis for shared caching across multiple server instances.
Code Example
const cached = await redisClient.get(key);
if (cached) return JSON.parse(cached);
NODE.JS
#2.466
Q466:
What environment-specific configuration strategies are common in Node.js apps?
Ans:
Common strategies include using environment variables (via process.env and dotenv), separate config files per environment, or configuration management libraries, allowing behavior (like database URLs or log levels) to differ between development, staging, and production.
NODE.JS
#2.467
Q467:
What are WebSockets and how do they differ from HTTP requests?
Ans:
WebSockets provide a persistent, full-duplex communication channel between client and server over a single TCP connection, allowing real-time bidirectional data exchange, unlike HTTP's request-response model which requires a new request for each exchange.
NODE.JS
#2.468
Q468:
What is Socket.IO and how does it relate to WebSockets?
Ans:
Socket.IO is a library that enables real-time, bidirectional communication, built on top of WebSockets with automatic fallback to other transport methods (like long polling) for compatibility, plus features like rooms and automatic reconnection.
Code Example
const io = require('socket.io')(server);
io.on('connection', (socket) => {
socket.on('message', (msg) => io.emit('message', msg));
});
NODE.JS
#2.469
Q469:
What is GraphQL and how does it differ from a REST API?
Ans:
GraphQL is a query language for APIs that allows clients to request exactly the data they need in a single request, unlike REST which typically exposes fixed endpoints returning predetermined data structures, often requiring multiple requests for related resources.
NODE.JS
#2.470
Q470:
What is Apollo Server and how is it used with Node.js?
Ans:
Apollo Server is a popular, production-ready GraphQL server library for Node.js that integrates with frameworks like Express, allowing you to define a GraphQL schema and resolvers to handle queries and mutations.
NODE.JS
#2.471
Q471:
What is API versioning and how might you implement it in an Express app?
Ans:
API versioning allows an API to evolve without breaking existing clients, commonly implemented via URL path prefixes (like /api/v1/), custom headers, or query parameters to indicate which version of the API a client wants to use.
Code Example
app.use('/api/v1', v1Router);
app.use('/api/v2', v2Router);
NODE.JS
#2.472
Q472:
What is the crypto module used for in Node.js?
Ans:
The crypto module provides cryptographic functionality including hashing, HMAC, encryption/decryption, and generating secure random values, built on OpenSSL.
Code Example
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('data').digest('hex');
NODE.JS
#2.473
Q473:
How do you generate a secure random string or token in Node.js?
Ans:
crypto.randomBytes() generates cryptographically strong pseudo-random data, which can be converted to a hex or base64 string, suitable for tokens, session IDs, or salts.
Code Example
const token = crypto.randomBytes(32).toString('hex');
NODE.JS
#2.474
Q474:
What is the util module used for in Node.js?
Ans:
The util module provides utility functions for debugging and working with Node.js internals, such as util.promisify() (converting callback functions to Promises) and util.inspect() (for detailed object string representations).
NODE.JS
#2.475
Q475:
What is the zlib module used for in Node.js?
Ans:
The zlib module provides compression and decompression functionality (gzip, deflate, brotli) implemented as Transform streams, useful for compressing HTTP responses or files.
Code Example
const zlib = require('zlib');
fs.createReadStream('file.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('file.txt.gz'));
NODE.JS
#2.476
Q476:
What is the querystring module used for, and how does it differ from the URL API?
Ans:
The legacy querystring module parses and formats URL query strings, while the more modern URL and URLSearchParams APIs (globally available in Node.js) provide a standards-based, more robust way to parse full URLs and their query parameters.
Code Example
const { URL } = require('url');
const myUrl = new URL('https://example.com/page?name=Tom');
console.log(myUrl.searchParams.get('name'));
NODE.JS
#2.477
Q477:
What is the assert module used for in Node.js?
Ans:
The built-in assert module provides functions for writing simple runtime assertions, primarily used for internal testing, throwing an AssertionError if a given condition fails.
Code Example
const assert = require('assert');
assert.strictEqual(1 + 1, 2);
NODE.JS
#2.478
Q478:
What is the difference between process.exit() and allowing a Node.js process to end naturally?
Ans:
process.exit() immediately terminates the process, potentially cutting off pending asynchronous operations (like unflushed writes), while letting the process end naturally allows the event loop to drain all pending callbacks and I/O before exiting.
NODE.JS
#2.479
Q479:
What are process signals and how can a Node.js application handle them?
Ans:
Signals like SIGINT (Ctrl+C) and SIGTERM (graceful shutdown request) can be intercepted using process.on('SIGTERM', handler), allowing an application to perform cleanup (like closing database connections) before exiting.
Code Example
process.on('SIGTERM', async () => {
await closeConnections();
process.exit(0);
});
NODE.JS
#2.480
Q480:
What is a monorepo and how is it typically managed in the Node.js ecosystem?
Ans:
A monorepo stores multiple related packages or projects within a single repository; tools like npm/yarn/pnpm workspaces, Lerna, or Nx help manage dependencies and versioning across the packages within a monorepo.
NODE.JS
#2.481
Q481:
How do you use TypeScript with Node.js?
Ans:
You install TypeScript and type definitions (like @types/node) as dev dependencies, write .ts files, and compile them to JavaScript using the tsc compiler (or run directly with tools like ts-node) before or during execution.
Code Example
npm install -D typescript @types/node
npx tsc --init
NODE.JS
#2.482
Q482:
What is the difference between a microservice architecture and a monolithic architecture for Node.js applications?
Ans:
A monolithic architecture builds the entire application as a single deployable unit, while a microservice architecture splits functionality into smaller, independently deployable services (often communicating via HTTP or message queues), improving scalability and team autonomy at the cost of added operational complexity.
NODE.JS
#2.483
Q483:
What is a message queue and why might you use one with Node.js?
Ans:
A message queue (like RabbitMQ or Kafka) enables asynchronous communication between services by decoupling producers and consumers of messages, improving reliability and scalability, especially useful for background job processing or event-driven microservices.
NODE.JS
#2.484
Q484:
What is graceful shutdown in a Node.js server and why is it important?
Ans:
Graceful shutdown involves stopping the server from accepting new connections, allowing in-flight requests to complete, and cleanly closing resources (like database connections) before the process exits, preventing dropped requests or data corruption during deployments or restarts.
Code Example
server.close(() => {
console.log('Server closed gracefully');
process.exit(0);
});
NODE.JS
#2.485
Q485:
How do you handle file uploads in an Express application?
Ans:
Middleware like multer handles multipart/form-data requests, parsing uploaded files and making them available via req.file or req.files, while storing them to disk, memory, or a cloud storage service.
Code Example
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('photo'), (req, res) => {
res.send(req.file);
});
NODE.JS
#2.486
Q486:
What is idempotency in the context of REST APIs, and which HTTP methods are idempotent?
Ans:
An idempotent operation produces the same result no matter how many times it's performed; GET, PUT, and DELETE are generally idempotent, while POST is typically not, since repeating it often creates additional resources.
NODE.JS
#2.487
Q487:
What is the difference between PUT and PATCH HTTP methods?
Ans:
PUT typically replaces an entire resource with the provided representation, while PATCH applies a partial update, modifying only the specified fields of an existing resource.
NODE.JS
#2.488
Q488:
What is a health check endpoint and why is it useful in a Node.js service?
Ans:
A health check endpoint (like GET /health) returns the service's operational status, used by load balancers, orchestrators (like Kubernetes), or monitoring tools to determine whether an instance is ready to receive traffic or needs to be restarted.
Code Example
app.get('/health', (req, res) => res.status(200).json({ status: 'ok' }));
NODE.JS
#2.489
Q489:
How do you validate incoming request data in an Express API?
Ans:
You can use validation libraries like Joi, express-validator, or Zod to define schemas and validate/sanitize req.body, req.query, or req.params before processing the request.
Code Example
const { body, validationResult } = require('express-validator');
app.post('/users', body('email').isEmail(), (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
});
NODE.JS
#2.490
Q490:
What is the difference between session-based authentication and token-based (JWT) authentication in Node.js apps?
Ans:
Session-based authentication stores session state on the server (often referenced via a cookie), requiring server-side storage and lookup, while token-based authentication (like JWT) is stateless, embedding user claims directly in a signed token that the server can verify without a database lookup.
NODE.JS
#2.491
Q491:
What is the difference between npm install and npm ci?
Ans:
npm install installs dependencies based on package.json and may update package-lock.json, while npm ci performs a clean, reproducible install strictly following package-lock.json, deleting node_modules first, making it faster and more reliable for CI/CD environments.
NODE.JS
#2.492
Q492:
How do you publish a package to the npm registry?
Ans:
After creating an npm account and logging in via 'npm login', you run 'npm publish' from the package's root directory (with a properly configured package.json), optionally bumping the version first with 'npm version'.
Code Example
npm login
npm version patch
npm publish
NODE.JS
#2.493
Q493:
What is the difference between an Express route handler and a middleware function in terms of signature?
Ans:
Both share a similar (req, res, next) signature, but a route handler typically ends the request-response cycle by sending a response, while middleware often performs a task and calls next() to pass control onward, though the distinction is more about usage than syntax.
NODE.JS
#2.494
Q494:
What is the purpose of Content-Type and Accept headers in HTTP requests?
Ans:
Content-Type indicates the media type of the data being sent in the request/response body (like application/json), while Accept indicates what media types the client is willing to receive in the response, allowing content negotiation.
NODE.JS
#2.495
Q495:
What is Docker and why is it commonly used to deploy Node.js applications?
Ans:
Docker packages an application and its dependencies into a portable container image, ensuring consistent behavior across development, testing, and production environments; Node.js apps are commonly containerized using a Dockerfile that installs dependencies and defines a start command.
Code Example
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
CMD ["node", "index.js"]
NODE.JS
#2.496
Q496:
What is serverless computing and how does it relate to Node.js?
Ans:
Serverless computing (like AWS Lambda) lets you run code (often Node.js functions) without managing servers, automatically scaling and charging based on execution time, well-suited for Node.js due to its fast cold-start times relative to some other runtimes.
NODE.JS
#2.497
Q497:
What is the difference between supertest and a typical HTTP client library for testing Express apps?
Ans:
supertest is specifically designed for testing HTTP servers (like Express apps) by wrapping the app instance directly, allowing assertions on responses without needing to actually bind to a network port, making tests faster and more self-contained.
Code Example
const request = require('supertest');
const response = await request(app).get('/users').expect(200);
NODE.JS
#2.498
Q498:
What is the difference between Buffer.from() and Buffer.alloc()?
Ans:
Buffer.from() creates a buffer initialized with existing data (like a string or array), while Buffer.alloc() creates a new buffer of a specified size, initialized to zero by default for safety (unlike the deprecated, unsafe new Buffer(size)).
Code Example
const buf1 = Buffer.from('hello');
const buf2 = Buffer.alloc(10);
NODE.JS
#2.499
Q499:
What is the difference between http and https modules in Node.js?
Ans:
The http module creates plain, unencrypted HTTP servers/clients, while the https module creates TLS/SSL-encrypted servers/clients, requiring a certificate and private key for the server.
Code Example
const https = require('https');
const options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') };
https.createServer(options, handler).listen(443);
NODE.JS
#2.500
Q500:
What is CSRF and how might you protect an Express application against it?
Ans:
CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into making unwanted requests to your app; protection typically involves using anti-CSRF tokens embedded in forms (e.g., via the csurf middleware, though it's now deprecated in favor of alternatives) and setting proper SameSite cookie attributes.
NODE.JS
#2.501
Q501:
What is middleware chaining and how does error propagate through it in Express?
Ans:
Multiple middleware functions can be chained in sequence for a route; calling next() passes control to the next one, while calling next(err) skips remaining regular middleware and jumps directly to the nearest error-handling middleware.
NODE.JS
#2.502
Q502:
What does the engines field in package.json specify?
Ans:
The engines field declares which versions of Node.js (and optionally npm) a package is compatible with, which can be enforced during installation or used informationally by tooling and hosting platforms.
Code Example
"engines": { "node": ">=18.0.0" }
NODE.JS
#2.503
Q503:
What is the difference between Object.freeze() and const for immutability in JavaScript?
Ans:
const only prevents reassignment of the variable binding itself, not mutation of the object it references, while Object.freeze() prevents adding, removing, or modifying an object's own properties (shallowly), making the object itself immutable.
Code Example
const obj = Object.freeze({ a: 1 });
obj.a = 2; // silently fails (or throws in strict mode)
console.log(obj.a); // 1
NODE.JS
#2.504
Q504:
What is the difference between the Node.js http.Server 'request' event and using Express route handlers?
Ans:
The raw http module emits a single 'request' event for every incoming request, requiring manual URL/method parsing and routing logic, while Express builds on top of this, providing a declarative routing API, middleware pipeline, and many convenience methods out of the box.
NODE.JS
#2.505
Q505:
What is the purpose of the .npmrc file?
Ans:
.npmrc is a configuration file for npm that can set options like the registry URL, authentication tokens, or default settings, applicable at the project, user, or global level.
NODE.JS
#2.506
Q506:
What is the difference between res.send(), res.json(), and res.end() in Express?
Ans:
res.json() explicitly serializes the argument to JSON and sets the Content-Type header accordingly, res.send() is more flexible and infers the content type based on the argument's type (string, object, buffer), and res.end() simply ends the response, optionally with raw data, without content-type inference.
NODE.JS
#2.507
Q507:
What is the purpose of a lockfile like package-lock.json or yarn.lock beyond version pinning?
Ans:
Besides pinning exact resolved versions, lockfiles record the integrity hashes of installed packages, ensuring the exact same code is installed every time, protecting against supply-chain tampering or unexpected changes in a dependency's published content.
NODE.JS
#2.508
Q508:
What is the difference between yarn, npm, and pnpm as package managers?
Ans:
All three manage Node.js dependencies, but differ in implementation: npm is the default bundled manager, yarn historically offered faster, more deterministic installs (features since adopted by npm), and pnpm uses a content-addressable storage system with symlinks to save disk space by avoiding duplicate package copies across projects.
REACT.JS
#2.509
Q509:
How does React's reconciliation algorithm work?
Ans:
Reconciliation is the process React uses to diff the new virtual DOM tree against the previous one; it compares elements by type and position, reuses existing DOM nodes where possible, and uses keys to efficiently match items in lists.
REACT.JS
#2.510
Q510:
What is the useEffect Hook?
Ans:
useEffect lets functional components perform side effects, such as data fetching, subscriptions, or manually changing the DOM, after render; it can also return a cleanup function that runs before the next effect or on unmount.
Code Example
useEffect(() => {
document.title = `Count: ${count}`;
return () => console.log('cleanup');
}, [count]);
REACT.JS
#2.511
Q511:
What is the dependency array in useEffect?
Ans:
The dependency array is the second argument to useEffect that tells React when to re-run the effect; an empty array runs the effect only once after the initial render, omitting it runs the effect after every render, and listing values re-runs it only when those values change.
Code Example
useEffect(() => { fetchData(); }, [userId]);
REACT.JS
#2.512
Q512:
What is the useContext Hook?
Ans:
useContext lets a component subscribe to a React Context and read its current value without wrapping the component in a Context.Consumer, simplifying prop drilling across deeply nested components.
Code Example
const theme = useContext(ThemeContext);
REACT.JS
#2.513
Q513:
What is the useRef Hook?
Ans:
useRef returns a mutable ref object whose .current property persists across renders without causing a re-render when changed; it's commonly used to access DOM nodes directly or store mutable values.
Code Example
const inputRef = useRef(null);
<input ref={inputRef} />
inputRef.current.focus();
REACT.JS
#2.514
Q514:
What is the difference between useRef and useState?
Ans:
Updating state with useState triggers a re-render and the new value is available only after re-render, whereas updating a useRef value does not trigger a re-render and the change is reflected immediately on .current.
REACT.JS
#2.515
Q515:
What is the useMemo Hook?
Ans:
useMemo memoizes the result of an expensive computation and only recalculates it when one of its dependencies changes, helping avoid unnecessary recalculations on every render.
Code Example
const sorted = useMemo(() => sortItems(items), [items]);
REACT.JS
#2.516
Q516:
What is the useCallback Hook?
Ans:
useCallback returns a memoized version of a callback function that only changes if one of its dependencies changes, which is useful for preventing unnecessary re-renders of child components that rely on reference equality.
Code Example
const handleClick = useCallback(() => doSomething(id), [id]);
REACT.JS
#2.517
Q517:
What is the difference between useMemo and useCallback?
Ans:
useMemo memoizes and returns the value of a computation, while useCallback memoizes and returns the function itself; useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
REACT.JS
#2.518
Q518:
What is the useReducer Hook?
Ans:
useReducer is an alternative to useState for managing complex state logic; it accepts a reducer function and an initial state, returning the current state and a dispatch function, similar to Redux's pattern.
Code Example
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'increment' });
REACT.JS
#2.519
Q519:
When should you use useReducer instead of useState?
Ans:
useReducer is preferable when state logic is complex, involves multiple sub-values, or the next state depends on the previous one in non-trivial ways, since it centralizes update logic in a single reducer function.
REACT.JS
#2.520
Q520:
What are custom Hooks?
Ans:
A custom Hook is a JavaScript function whose name starts with 'use' that can call other Hooks, allowing you to extract and reuse stateful logic across multiple components without duplicating code.
Code Example
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setWidth(window.innerWidth);
window.addEventListener('resize', handler);
return () => window.removeEventListener('resize', handler);
}, []);
return width;
}
REACT.JS
#2.521
Q521:
What are the rules of Hooks?
Ans:
Hooks must only be called at the top level of a function component or custom Hook (never inside loops, conditions, or nested functions), and they must only be called from React function components or other custom Hooks.
REACT.JS
#2.522
Q522:
What is the Context API used for?
Ans:
The Context API provides a way to share values like themes, authenticated user data, or locale across a component tree without having to pass props down manually at every level (avoiding 'prop drilling').
Code Example
const ThemeContext = React.createContext('light');
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
REACT.JS
#2.523
Q523:
What is prop drilling and how can it be avoided?
Ans:
Prop drilling is passing data through multiple layers of intermediate components that don't need it themselves, just to reach a deeply nested child; it can be avoided using the Context API, or state management libraries like Redux or Zustand.
REACT.JS
#2.524
Q524:
What are uncontrolled components?
Ans:
An uncontrolled component manages its own state internally in the DOM, and React accesses its current value on demand using a ref rather than tracking every keystroke via state.
Code Example
const inputRef = useRef();
<input ref={inputRef} defaultValue="hello" />
REACT.JS
#2.525
Q525:
What is the significance of keys in React lists?
Ans:
Keys are special string attributes that help React identify which items in a list have changed, been added, or removed, enabling efficient reordering and preventing unnecessary re-renders; keys should be stable and unique, not array indices when the list can change.
Code Example
{items.map(item => <li key={item.id}>{item.name}</li>)}
REACT.JS
#2.526
Q526:
Why is using array index as a key considered an anti-pattern?
Ans:
Using the index as a key can cause incorrect component state association and rendering bugs when items are reordered, inserted, or removed, because React matches elements by key rather than by content, leading to stale UI or lost input state.
REACT.JS
#2.527
Q527:
What is the difference between React.PureComponent and React.Component?
Ans:
React.PureComponent implements shouldComponentUpdate() with a shallow comparison of props and state automatically, skipping re-renders when nothing shallowly changed, while React.Component re-renders on every state or prop change unless you implement shouldComponentUpdate yourself.
REACT.JS
#2.528
Q528:
What is React.memo()?
Ans:
React.memo() is a higher-order component that memoizes a functional component, skipping re-rendering when its props haven't changed (using a shallow comparison by default), analogous to PureComponent for function components.
Code Example
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
REACT.JS
#2.529
Q529:
What are Higher-Order Components (HOCs)?
Ans:
A Higher-Order Component is a function that takes a component and returns a new component with additional props or behavior, used to share reusable logic like authentication checks or data fetching across multiple components.
Code Example
function withLogging(WrappedComponent) {
return function(props) {
console.log('rendering', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
REACT.JS
#2.530
Q530:
What is the render props pattern?
Ans:
The render props pattern is a technique for sharing code between components using a prop whose value is a function that returns JSX, allowing the parent to control what gets rendered based on the child's internal state.
Code Example
<DataProvider render={data => <Display data={data} />} />
REACT.JS
#2.531
Q531:
What are React Error Boundaries?
Ans:
Error boundaries are class components that implement componentDidCatch() and/or static getDerivedStateFromError() to catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.
Code Example
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
return this.state.hasError ? <h1>Something went wrong.</h1> : this.props.children;
}
}
REACT.JS
#2.532
Q532:
Can functional components act as error boundaries?
Ans:
No, error boundaries currently must be class components, since there is no Hook equivalent for componentDidCatch or getDerivedStateFromError; libraries like react-error-boundary provide a functional wrapper around a class-based implementation.
REACT.JS
#2.533
Q533:
What are React Portals?
Ans:
Portals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy, useful for modals, tooltips, and dropdowns that need to escape overflow or z-index constraints of their parent.
Code Example
ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'));
REACT.JS
#2.534
Q534:
What is forwardRef used for?
Ans:
forwardRef lets a component pass a ref it receives through to a child DOM node or component, enabling parent components to directly access a child's underlying DOM element, commonly used when building reusable component libraries.
Code Example
const FancyInput = React.forwardRef((props, ref) => (
<input ref={ref} className="fancy" {...props} />
));
REACT.JS
#2.535
Q535:
What is React.lazy() used for?
Ans:
React.lazy() lets you dynamically import a component and code-split it so it's only loaded when actually rendered, reducing the initial bundle size; it must be paired with a Suspense component to show a fallback while loading.
Code Example
const OtherComponent = React.lazy(() => import('./OtherComponent'));
REACT.JS
#2.536
Q536:
What is the Suspense component used for?
Ans:
Suspense lets you specify a loading indicator (fallback) for a part of the component tree that isn't ready to render yet, commonly used with React.lazy() for code-splitting and with data-fetching libraries that support Suspense.
Code Example
<Suspense fallback={<Spinner />}>
<OtherComponent />
</Suspense>
REACT.JS
#2.537
Q537:
What is code-splitting in React and why is it useful?
Ans:
Code-splitting breaks a large JavaScript bundle into smaller chunks that are loaded on demand rather than all at once, reducing initial load time; in React this is commonly done with dynamic import() combined with React.lazy() and Suspense.
REACT.JS
#2.538
Q538:
What are the main lifecycle methods of a class component?
Ans:
The main lifecycle methods are componentDidMount() (runs after the component is first rendered), componentDidUpdate() (runs after updates), and componentWillUnmount() (runs right before the component is removed), alongside the render() method itself.
REACT.JS
#2.539
Q539:
How do Hooks replicate lifecycle methods like componentDidMount and componentWillUnmount?
Ans:
useEffect with an empty dependency array behaves like componentDidMount, running once after the initial render, and the function it returns behaves like componentWillUnmount, running when the component unmounts.
Code Example
useEffect(() => {
console.log('mounted');
return () => console.log('unmounted');
}, []);
REACT.JS
#2.540
Q540:
What is the purpose of componentDidCatch?
Ans:
componentDidCatch() is a lifecycle method used in error boundaries that is invoked after a descendant component throws an error, allowing you to log the error and update state to render a fallback UI.
REACT.JS
#2.541
Q541:
What is shouldComponentUpdate used for?
Ans:
shouldComponentUpdate() lets a class component control whether it re-renders in response to a change in props or state, returning false skips the re-render, which is a manual way to optimize performance before React.memo/PureComponent existed.
REACT.JS
#2.542
Q542:
What is the difference between state and lifecycle in class components vs Hooks?
Ans:
Class components tie state to this.state and spread related logic across separate lifecycle methods, while Hooks let you colocate related state and side-effect logic together inside a function component, making related code easier to organize and reuse.
REACT.JS
#2.543
Q543:
What is React's StrictMode?
Ans:
StrictMode is a development-only tool that helps surface potential problems by intentionally double-invoking certain functions (like component render, and some effects in React 18+), warning about deprecated APIs, and highlighting unsafe lifecycle usage; it renders no visible UI itself.
Code Example
<React.StrictMode>
<App />
</React.StrictMode>
REACT.JS
#2.544
Q544:
What is server-side rendering (SSR) and why use it with React?
Ans:
SSR renders React components to HTML on the server and sends that markup to the browser, improving perceived load time and SEO by giving users and crawlers meaningful content before JavaScript finishes loading and hydrating.
REACT.JS
#2.545
Q545:
What is the difference between client-side rendering and server-side rendering?
Ans:
Client-side rendering ships a minimal HTML shell and lets the browser download and execute JavaScript to build the UI, while server-side rendering generates the full HTML on the server per request, resulting in faster first paint but requiring hydration on the client.
REACT.JS
#2.546
Q546:
How do you pass data between sibling components in React?
Ans:
Since data flows down through props, sibling components typically share data by lifting shared state up to their closest common ancestor, which then passes the state and updater functions down to both siblings as props.
REACT.JS
#2.547
Q547:
What is 'lifting state up' in React?
Ans:
Lifting state up means moving shared state to the closest common ancestor of the components that need it, so that data flows down as props and stays synchronized between siblings instead of duplicating state in each component.
REACT.JS
#2.548
Q548:
What is Redux and how does it relate to React?
Ans:
Redux is a predictable state management library that stores an application's entire state in a single, centralized store, updated only via dispatched actions processed by pure reducer functions; react-redux provides bindings to connect React components to that store.
Code Example
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'increment': return state + 1;
default: return state;
}
};
REACT.JS
#2.549
Q549:
What is the difference between Redux and the Context API?
Ans:
Context API is built into React and is best for passing relatively static or infrequently changing data through the tree, while Redux offers a structured, predictable pattern with middleware, dev tools, and better performance for complex, frequently updated global state.
REACT.JS
#2.550
Q550:
What are React Hooks rules regarding conditional calls?
Ans:
Hooks must always be called in the same order on every render, so they cannot be placed inside if statements, loops, or nested functions; conditional logic should instead go inside the Hook itself (e.g., inside useEffect's callback).
REACT.JS
#2.551
Q551:
What is the significance of the dependency array being empty vs omitted in useEffect?
Ans:
An empty array ([]) means the effect runs only once after mount and never again, while omitting the array entirely means the effect runs after every single render, which can lead to performance issues or infinite loops if not handled carefully.
REACT.JS
#2.552
Q552:
How do you optimize performance in a React application?
Ans:
Common techniques include memoizing components with React.memo, memoizing values/functions with useMemo/useCallback, code-splitting with React.lazy, virtualizing long lists, avoiding unnecessary re-renders by keeping state as local as possible, and using the React DevTools Profiler to identify bottlenecks.
REACT.JS
#2.553
Q553:
How do you handle forms with multiple inputs in React?
Ans:
A common pattern is to store all field values in a single state object and use a shared onChange handler that updates the corresponding key using the input's name attribute, often combined with computed property names.
Code Example
const [form, setForm] = useState({ name: '', email: '' });
const handleChange = e => setForm({ ...form, [e.target.name]: e.target.value });
REACT.JS
#2.554
Q554:
What is component composition and why is it preferred over inheritance in React?
Ans:
Composition means building complex UIs by combining smaller components (often via props.children or render props) rather than extending a base component class; React's team recommends composition because it's more flexible and avoids the tight coupling and fragility of deep inheritance chains.
REACT.JS
#2.555
Q555:
How do you fetch data in a React component?
Ans:
Data fetching is typically done inside a useEffect Hook that calls fetch() or a library like axios, storing the result in state; libraries like React Query or SWR are often used to handle caching, retries, and loading/error states more robustly.
Code Example
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
REACT.JS
#2.556
Q556:
What is React Query (TanStack Query) used for?
Ans:
React Query is a data-fetching and caching library that manages server state in React apps, handling caching, background refetching, request deduplication, and loading/error states, reducing the need for manual useEffect-based fetching.
REACT.JS
#2.557
Q557:
What is the difference between client state and server state?
Ans:
Client state is local UI state owned entirely by the app (like form input or a toggle), while server state is data that originates from and is owned by a remote server, which can become stale and requires syncing, caching, and revalidation.
REACT.JS
#2.558
Q558:
What are Synthetic Events in React?
Ans:
SyntheticEvent is React's cross-browser wrapper around the browser's native event object, providing a consistent API across different browsers while still giving access to the underlying native event via e.nativeEvent.
Code Example
function handleClick(e) {
console.log(e.type); // 'click'
}
REACT.JS
#2.559
Q559:
Why is TypeScript often used with React?
Ans:
TypeScript adds static type-checking to React code, catching prop-type mismatches, incorrect Hook usage, and other bugs at compile time rather than runtime, and improves editor autocompletion and refactoring safety in larger codebases.
REACT.JS
#2.560
Q560:
What testing tools are commonly used with React?
Ans:
Jest is the most common test runner and assertion library, often paired with React Testing Library, which encourages testing components by simulating user interactions and asserting on rendered output rather than internal implementation details.
Code Example
test('renders greeting', () => {
render(<Greeting name="Sara" />);
expect(screen.getByText('Hello, Sara')).toBeInTheDocument();
});
REACT.JS
#2.561
Q561:
What is the philosophy behind React Testing Library?
Ans:
React Testing Library encourages writing tests that resemble how users interact with the application—querying by visible text, roles, or labels rather than component internals or class names—so tests remain resilient to refactoring.
REACT.JS
#2.562
Q562:
What is the difference between React 17 and React 18 regarding root rendering?
Ans:
React 18 introduced createRoot() from react-dom/client to replace the legacy ReactDOM.render() API, enabling concurrent features; rendering with the old API opts an app out of React 18's concurrent rendering capabilities.
Code Example
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
REACT.JS
#2.563
Q563:
What are common React anti-patterns to avoid?
Ans:
Common anti-patterns include mutating state directly instead of using the setter, using array indices as keys in dynamic lists, overusing Context for frequently-changing state, deeply nesting components unnecessarily, and putting too much logic directly inside JSX instead of extracting it.
REACT.JS
#2.564
Q564:
What is the significance of immutability in React state management?
Ans:
React relies on reference equality checks to detect changes efficiently; mutating state objects or arrays in place means the reference stays the same, so React (and optimizations like PureComponent or memo) may fail to detect the change and skip a necessary re-render.
Code Example
// Wrong: state.push(newItem)
// Correct:
setItems([...items, newItem]);
REACT.JS
#2.565
Q565:
What is the significance of functional updates in useState?
Ans:
Passing a function to the state setter (e.g., setCount(prev => prev + 1)) ensures the update is based on the most current state value, which is important when updating state multiple times in a row or inside closures that might reference stale state.
Code Example
setCount(prevCount => prevCount + 1);
ANGULAR.JS
#2.566
Q566:
What are standalone components in Angular?
Ans:
Standalone components (introduced in Angular 14+ and the default since Angular 17+) are components that don't need to be declared in an NgModule; they specify their own imports directly, simplifying the module system and reducing boilerplate.
Code Example
@Component({
selector: 'app-hero',
standalone: true,
imports: [CommonModule],
template: `<p>Hero</p>`
})
export class HeroComponent {}
ANGULAR.JS
#2.567
Q567:
What is the difference between structural and attribute directives?
Ans:
Structural directives (prefixed with *, like *ngIf and *ngFor) change the DOM structure by adding or removing elements, while attribute directives (like ngClass and ngStyle) change the appearance or behavior of an existing element without adding or removing elements.
ANGULAR.JS
#2.568
Q568:
What is trackBy used for in *ngFor?
Ans:
trackBy provides a function that returns a unique identifier for each item in a list, allowing Angular's change detection to track items by identity rather than object reference, avoiding unnecessary DOM re-creation when the list is updated.
Code Example
trackById(index: number, item: Item): number {
return item.id;
}
ANGULAR.JS
#2.569
Q569:
How do you create a custom pipe in Angular?
Ans:
A custom pipe is created by implementing the PipeTransform interface in a class decorated with @Pipe, defining a transform() method that takes the input value and returns the transformed output.
Code Example
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 20): string {
return value.length > limit ? value.slice(0, limit) + '...' : value;
}
}
ANGULAR.JS
#2.570
Q570:
What is dependency injection in Angular?
Ans:
Dependency injection is a design pattern where a class's dependencies (like services) are provided to it from an external injector rather than being created inside the class itself, which Angular implements through its hierarchical injector system and the @Injectable decorator.
Code Example
@Injectable({ providedIn: 'root' })
export class UserService {
getUsers() { return this.http.get('/api/users'); }
}
ANGULAR.JS
#2.571
Q571:
What does providedIn: 'root' mean when declaring a service?
Ans:
providedIn: 'root' registers the service with the application's root injector, making it a singleton available throughout the entire application without needing to list it in a module's providers array, and enables tree-shaking if the service is never injected anywhere.
ANGULAR.JS
#2.572
Q572:
What is RxJS and how does Angular use it?
Ans:
RxJS is a library for reactive programming using Observables; Angular uses it extensively for asynchronous operations like HTTP requests (via HttpClient), event handling, reactive forms, and the Router, allowing composition of async data streams using operators like map, filter, and switchMap.
Code Example
this.http.get('/api/data').pipe(
map(res => res.items),
filter(items => items.length > 0)
).subscribe(items => this.items = items);
ANGULAR.JS
#2.573
Q573:
What is the difference between an Observable and a Promise?
Ans:
A Promise resolves a single value once and cannot be cancelled, while an Observable can emit multiple values over time, supports cancellation via unsubscribe, and provides a rich set of composable operators for transforming, combining, and filtering streams of data.
ANGULAR.JS
#2.574
Q574:
What is the async pipe used for?
Ans:
The async pipe subscribes to an Observable or Promise directly within a template, automatically displaying emitted values and automatically unsubscribing when the component is destroyed, removing the need for manual subscription management.
Code Example
<div *ngIf="user$ | async as user">{{ user.name }}</div>
ANGULAR.JS
#2.575
Q575:
Why is it important to unsubscribe from Observables in Angular?
Ans:
Failing to unsubscribe from long-lived Observables (like those from event listeners or manual HTTP subscriptions kept open) can cause memory leaks, since the subscription callback keeps a reference to the component even after it has been destroyed.
Code Example
ngOnDestroy() {
this.subscription.unsubscribe();
}
ANGULAR.JS
#2.576
Q576:
What are HTTP interceptors in Angular?
Ans:
Interceptors are services implementing HttpInterceptor that sit in the HTTP request/response pipeline, letting you globally modify outgoing requests (like adding auth headers) or incoming responses (like handling errors) before they reach the calling code.
Code Example
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
return next.handle(authReq);
}
ANGULAR.JS
#2.577
Q577:
What is Angular's component lifecycle?
Ans:
A component progresses through a sequence of lifecycle hooks managed by Angular: ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, and finally ngOnDestroy, each letting you hook into a specific moment of the component's existence.
ANGULAR.JS
#2.578
Q578:
What is ngOnInit used for and how does it differ from a constructor?
Ans:
ngOnInit is called once, right after Angular has initialized all data-bound input properties, making it the right place for initialization logic that depends on those inputs, whereas the constructor is meant only for basic class setup and dependency injection, and runs before inputs are set.
Code Example
ngOnInit() {
this.loadData();
}
ANGULAR.JS
#2.579
Q579:
What is ngOnChanges used for?
Ans:
ngOnChanges is called whenever one or more data-bound input properties change, receiving a SimpleChanges object describing the previous and current values, useful for reacting to specific input updates.
Code Example
ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) this.loadUser();
}
ANGULAR.JS
#2.580
Q580:
What is ngOnDestroy used for?
Ans:
ngOnDestroy is called just before Angular destroys a component or directive, making it the place to clean up resources like unsubscribing from Observables, clearing timers, or detaching event listeners to prevent memory leaks.
ANGULAR.JS
#2.581
Q581:
How does a child component communicate with its parent in Angular?
Ans:
A child component emits a custom event using an @Output EventEmitter, which the parent template listens for using event binding syntax and handles with a method defined in the parent's class.
Code Example
// child
@Output() itemSelected = new EventEmitter<Item>();
select(item: Item) { this.itemSelected.emit(item); }
// parent template
<app-child (itemSelected)="onItemSelected($event)"></app-child>
ANGULAR.JS
#2.582
Q582:
What is @ViewChild used for?
Ans:
@ViewChild lets a component get a reference to a child component, directive, or DOM element within its own template, allowing direct access to its properties and methods after the view has been initialized.
Code Example
@ViewChild('nameInput') nameInput: ElementRef;
ngAfterViewInit() {
this.nameInput.nativeElement.focus();
}
ANGULAR.JS
#2.583
Q583:
What is content projection in Angular?
Ans:
Content projection, implemented with the tag, lets a component render content passed to it from its parent between its opening and closing tags, similar to React's children prop, enabling flexible, reusable wrapper components.
Code Example
// card.component.html
<div class="card"><ng-content></ng-content></div>
// usage
<app-card><p>Hello</p></app-card>
ANGULAR.JS
#2.584
Q584:
What is change detection in Angular?
Ans:
Change detection is the mechanism Angular uses to keep the DOM in sync with the component's data by checking for changes and re-rendering the affected parts of the template; by default, it runs for every component in the tree whenever an event, timer, or HTTP response triggers Zone.js.
ANGULAR.JS
#2.585
Q585:
What are route guards in Angular?
Ans:
Route guards are interfaces (like CanActivate, CanDeactivate, and CanLoad) that let you control whether navigation to or away from a route is allowed, commonly used for authentication checks or preventing navigation away from a form with unsaved changes.
Code Example
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn() || inject(Router).parseUrl('/login');
};
ANGULAR.JS
#2.586
Q586:
What is lazy loading in Angular and why is it used?
Ans:
Lazy loading defers loading a feature module's (or standalone component's) JavaScript bundle until the user actually navigates to a route that needs it, reducing the initial bundle size and improving startup performance.
Code Example
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
ANGULAR.JS
#2.587
Q587:
What is the difference between template-driven forms and reactive forms?
Ans:
Template-driven forms use directives like ngModel directly in the HTML template with the form structure implicitly created by Angular, while reactive forms define the form's structure and validation explicitly in the component class using FormGroup and FormControl, offering more predictability, testability, and control for complex forms.
ANGULAR.JS
#2.588
Q588:
What is FormBuilder used for?
Ans:
FormBuilder is a service that provides convenient shorthand syntax for creating FormGroup, FormControl, and FormArray instances, reducing the boilerplate needed when constructing reactive forms.
Code Example
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
ANGULAR.JS
#2.589
Q589:
What are Validators in Angular reactive forms?
Ans:
Validators are functions attached to a FormControl that check the control's value and return an error object if invalid or null if valid; Angular provides built-in validators like required, minLength, and pattern, and also supports custom validator functions.
Code Example
email: ['', [Validators.required, Validators.email]]
ANGULAR.JS
#2.590
Q590:
What is dependency injection's providers array used for?
Ans:
The providers array (in an @NgModule, @Component, or @Injectable) tells Angular's injector how to create a particular dependency—directly with the class, via a factory function, or with a specific value—and at what scope it should be available.
Code Example
providers: [{ provide: ApiService, useClass: MockApiService }]
ANGULAR.JS
#2.591
Q591:
What is a singleton service in Angular?
Ans:
A singleton service is a service of which only one instance exists for a given injector scope (commonly the whole app when using providedIn: 'root'), ensuring all components that inject it share the same state and instance.
ANGULAR.JS
#2.592
Q592:
How does Angular protect against XSS attacks by default?
Ans:
Angular automatically sanitizes values interpolated into the DOM, stripping out potentially dangerous HTML, styles, or URLs by default, so developers must explicitly opt out via DomSanitizer if they intentionally need to render trusted raw HTML.
ANGULAR.JS
#2.593
Q593:
What is the purpose of ng-container?
Ans:
ng-container is a logical, non-rendering wrapper element that groups multiple elements or applies a structural directive without adding an extra node to the actual DOM, useful when you need *ngIf on multiple sibling elements at once.
Code Example
<ng-container *ngIf="showDetails">
<h2>Title</h2>
<p>Description</p>
</ng-container>
ANGULAR.JS
#2.594
Q594:
What testing tools does Angular use by default?
Ans:
Angular CLI projects are set up by default with Jasmine as the testing framework and Karma as the test runner, though Jest has become a popular alternative; TestBed is used to configure and create testing modules for isolating and testing components and services.
Code Example
TestBed.configureTestingModule({ declarations: [MyComponent] });
const fixture = TestBed.createComponent(MyComponent);
ANGULAR.JS
#2.595
Q595:
What is TestBed used for in Angular testing?
Ans:
TestBed is Angular's primary testing utility that creates a dynamically constructed Angular testing module, letting you configure providers, declarations, and imports to create component fixtures and test them in an environment resembling the real application.
ANGULAR.JS
#2.596
Q596:
What is the difference between a module and a standalone component architecture?
Ans:
The traditional NgModule-based architecture organizes the app into cohesive units declared via @NgModule, while the standalone architecture (default from Angular 17+) lets components, directives, and pipes declare their own dependencies directly, eliminating most or all NgModules and simplifying the mental model.
ANGULAR.JS
#2.597
Q597:
What is the inject() function used for in Angular?
Ans:
inject() is a function that can retrieve a dependency from Angular's injection context outside of a constructor, commonly used in functional route guards, resolvers, and standalone component setup code where a class constructor isn't available.
Code Example
export const authGuard: CanActivateFn = () => {
return inject(AuthService).isLoggedIn();
};
ANGULAR.JS
#2.598
Q598:
What is a directive in Angular?
Ans:
A directive is a class that can attach additional behavior to elements in the DOM; Angular has component directives (with a template), structural directives (that change DOM layout, like *ngIf), and attribute directives (that change appearance or behavior, like ngClass).
ANGULAR.JS
#2.599
Q599:
How do you create a custom attribute directive in Angular?
Ans:
A custom attribute directive is created using the @Directive decorator with a selector, and typically injects ElementRef and Renderer2 to safely manipulate the host element's properties or styles.
Code Example
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
ANGULAR.JS
#2.600
Q600:
How do you optimize the performance of a large Angular application?
Ans:
Common strategies include enabling OnPush change detection, lazy-loading feature modules or routes, using trackBy with *ngFor, avoiding heavy computation directly in templates, using pure pipes instead of methods in bindings, and adopting Signals to reduce reliance on Zone.js-triggered global change detection.
ANGULAR.JS
#2.601
Q601:
What is the significance of the environment.ts files in an Angular project?
Ans:
environment.ts and environment.prod.ts hold environment-specific configuration values (like API URLs), and the Angular CLI's build system automatically swaps in the appropriate file based on the build configuration used (e.g., ng build --configuration production).
ANGULAR.JS
#2.602
Q602:
What is a barrel file in Angular projects?
Ans:
A barrel file is an index.ts file that re-exports multiple modules from a directory, allowing consumers to import several related classes from a single, shorter path rather than importing each file individually.
Code Example
// index.ts
export * from './user.service';
export * from './user.model';
SQL
#2.603
Q603:
What is the difference between a primary key and a unique key?
Ans:
Both enforce uniqueness of values in a column, but a table can have only one primary key (which also disallows NULLs) while it can have multiple unique keys, and unique keys do allow a single NULL value (in most databases).
SQL
#2.604
Q604:
What is a composite key?
Ans:
A composite key is a primary key made up of two or more columns that together uniquely identify a row, used when no single column is sufficient to guarantee uniqueness on its own.
Code Example
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
SQL
#2.605
Q605:
What is a candidate key?
Ans:
A candidate key is any column or combination of columns that could qualify as the primary key because it uniquely identifies rows; a table may have multiple candidate keys, and one of them is chosen as the primary key.
SQL
#2.606
Q606:
What is the difference between WHERE and HAVING?
Ans:
WHERE filters individual rows before any grouping occurs and cannot reference aggregate functions directly, while HAVING filters groups after GROUP BY has been applied and is used specifically to filter based on aggregate results.
Code Example
SELECT dept, COUNT(*) FROM employees
GROUP BY dept
HAVING COUNT(*) > 5;
SQL
#2.607
Q607:
What is the difference between DELETE, TRUNCATE, and DROP?
Ans:
DELETE removes rows one at a time (optionally filtered by WHERE), is logged, and can be rolled back; TRUNCATE removes all rows at once, resets identity counters, is minimally logged, and is faster but generally cannot target specific rows; DROP removes the entire table structure along with its data.
Code Example
DELETE FROM users WHERE id = 1;
TRUNCATE TABLE users;
DROP TABLE users;
SQL
#2.608
Q608:
What are the different types of JOINs in SQL?
Ans:
The main JOIN types are INNER JOIN (only matching rows in both tables), LEFT JOIN (all rows from the left table plus matches from the right, NULLs where no match), RIGHT JOIN (all rows from the right table plus matches from the left), and FULL OUTER JOIN (all rows from both tables, with NULLs where there's no match on either side).
Code Example
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id;
SQL
#2.609
Q609:
What is a self join and when would you use one?
Ans:
A self join joins a table to itself using table aliases, commonly used to compare rows within the same table, such as finding employees and their managers stored in the same employees table.
Code Example
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;
SQL
#2.610
Q610:
What is a CROSS JOIN?
Ans:
A CROSS JOIN returns the Cartesian product of two tables, pairing every row in the first table with every row in the second table, resulting in a row count equal to the product of the two tables' row counts.
Code Example
SELECT a.color, b.size
FROM colors a CROSS JOIN sizes b;
SQL
#2.611
Q611:
What is the difference between UNION and UNION ALL?
Ans:
UNION combines the result sets of two or more SELECT queries and removes duplicate rows, requiring an internal sort/distinct operation, while UNION ALL combines the results without removing duplicates, making it faster when duplicates are acceptable or known not to exist.
Code Example
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
SQL
#2.612
Q612:
What are the requirements for using UNION?
Ans:
All SELECT statements combined with UNION must have the same number of columns, in the same order, with compatible data types across corresponding columns.
SQL
#2.613
Q613:
What is a subquery?
Ans:
A subquery (or inner query) is a query nested inside another SQL statement (SELECT, INSERT, UPDATE, or DELETE), used to compute a value or set of values that the outer query then uses for filtering, joining, or comparison.
Code Example
SELECT name FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
SQL
#2.614
Q614:
What is the difference between a subquery and a JOIN?
Ans:
A JOIN combines columns from multiple tables into a single result set and is often more efficient because the optimizer can plan it as a single set operation, while a subquery nests one query inside another and can sometimes be less efficient, though modern optimizers often rewrite subqueries into equivalent joins internally.
SQL
#2.615
Q615:
What is a Common Table Expression (CTE)?
Ans:
A CTE, defined with the WITH clause, is a named temporary result set that exists only for the duration of a single query, improving readability by breaking complex queries into logical, reusable steps.
Code Example
WITH high_earners AS (
SELECT * FROM employees WHERE salary > 100000
)
SELECT dept, COUNT(*) FROM high_earners GROUP BY dept;
SQL
#2.616
Q616:
What is normalization in database design?
Ans:
Normalization is the process of organizing tables and columns to minimize data redundancy and avoid update, insertion, and deletion anomalies, typically achieved by decomposing tables through a series of normal forms (1NF, 2NF, 3NF, etc.).
SQL
#2.617
Q617:
What is First Normal Form (1NF)?
Ans:
A table is in 1NF if each column contains only atomic (indivisible) values, each row is unique, and there are no repeating groups or arrays stored within a single column.
SQL
#2.618
Q618:
What is Second Normal Form (2NF)?
Ans:
A table is in 2NF if it is already in 1NF and every non-key column is fully functionally dependent on the entire primary key, not just part of a composite key (eliminating partial dependencies).
SQL
#2.619
Q619:
What is Third Normal Form (3NF)?
Ans:
A table is in 3NF if it is already in 2NF and has no transitive dependencies, meaning non-key columns depend only on the primary key and not on other non-key columns.
SQL
#2.620
Q620:
What is denormalization and when would you use it?
Ans:
Denormalization intentionally introduces redundancy into a database design (e.g., duplicating data or pre-computing aggregates) to reduce the number of joins needed for read-heavy workloads, trading some write complexity and storage for improved query performance.
SQL
#2.621
Q621:
What is an index in SQL and why is it used?
Ans:
An index is a database structure (often a B-tree) that speeds up data retrieval by allowing the database to find rows without scanning the entire table, at the cost of additional storage and slower writes since indexes must also be updated.
Code Example
CREATE INDEX idx_users_email ON users(email);
SQL
#2.622
Q622:
What are the downsides of adding too many indexes to a table?
Ans:
Every additional index increases storage usage and slows down INSERT, UPDATE, and DELETE operations because each index must also be updated whenever the underlying data changes, so indexes should be added deliberately based on actual query patterns.
SQL
#2.623
Q623:
What is a database transaction?
Ans:
A transaction is a sequence of one or more SQL operations executed as a single logical unit of work, which either fully completes (COMMIT) or is fully undone (ROLLBACK), ensuring the database never ends up in a partially-updated, inconsistent state.
Code Example
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
SQL
#2.624
Q624:
What does ACID stand for in the context of databases?
Ans:
ACID stands for Atomicity (a transaction fully completes or fully fails), Consistency (a transaction moves the database from one valid state to another), Isolation (concurrent transactions don't interfere with each other), and Durability (once committed, changes survive system failures).
SQL
#2.625
Q625:
What is the difference between a view and a table?
Ans:
A table physically stores data on disk, while a view is a stored, named SELECT query that presents data virtually and is recomputed (or partially materialized, depending on the database) each time it's queried, without storing the data itself.
Code Example
CREATE VIEW active_users AS
SELECT * FROM users WHERE status = 'active';
SQL
#2.626
Q626:
What is a stored procedure?
Ans:
A stored procedure is a precompiled, named collection of SQL statements stored in the database that can accept parameters and be invoked repeatedly, useful for encapsulating complex business logic close to the data.
Code Example
CREATE PROCEDURE GetUserById(IN uid INT)
BEGIN
SELECT * FROM users WHERE id = uid;
END;
SQL
#2.627
Q627:
What is the difference between a stored procedure and a function?
Ans:
A stored procedure can perform actions (like INSERT/UPDATE/DELETE) and may or may not return a value, and is invoked with CALL, while a user-defined function must return a single value or table and can be used directly within a SELECT statement, but generally cannot modify data.
SQL
#2.628
Q628:
What is a trigger in SQL?
Ans:
A trigger is a stored procedure that automatically executes in response to a specific event (INSERT, UPDATE, or DELETE) on a table, commonly used for enforcing business rules, auditing changes, or maintaining derived data.
Code Example
CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
SET NEW.created_at = NOW();
SQL
#2.629
Q629:
What is the difference between CHAR and VARCHAR data types?
Ans:
CHAR is a fixed-length string type that pads shorter values with spaces up to the defined length, while VARCHAR is a variable-length string type that only uses as much storage as the actual data requires (plus a small overhead), making VARCHAR generally more space-efficient for variable-length text.
SQL
#2.630
Q630:
What is the difference between TEXT and VARCHAR?
Ans:
VARCHAR requires a defined maximum length and is typically stored inline with the row for faster access, while TEXT (or similar large-object types) is designed for very large, variable-length text and may be stored separately from the row depending on the database engine.
SQL
#2.631
Q631:
What is the CHECK constraint used for?
Ans:
The CHECK constraint enforces that values in a column satisfy a specific boolean condition, rejecting any INSERT or UPDATE that would violate it, such as ensuring an age column is always non-negative.
Code Example
ALTER TABLE employees ADD CONSTRAINT chk_age CHECK (age >= 18);
SQL
#2.632
Q632:
What is the ON DELETE CASCADE option used for?
Ans:
ON DELETE CASCADE, defined on a foreign key, automatically deletes child rows referencing a parent row when that parent row is deleted, maintaining referential integrity without requiring the application to manually clean up related records.
Code Example
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
SQL
#2.633
Q633:
How do you implement pagination in SQL?
Ans:
Pagination is typically implemented using LIMIT combined with OFFSET (or FETCH NEXT ... OFFSET in SQL Server/standard SQL), which skips a specified number of rows before returning the next page's worth of results.
Code Example
SELECT * FROM products ORDER BY id LIMIT 10 OFFSET 20;
SQL
#2.634
Q634:
What is the difference between LIKE and REGEXP for pattern matching?
Ans:
LIKE performs simple pattern matching using wildcards (% for any sequence of characters and _ for a single character), while REGEXP (or RLIKE) supports full regular expression pattern matching, offering much more powerful and complex text matching capabilities.
Code Example
SELECT * FROM users WHERE email LIKE '%@gmail.com';
SELECT * FROM users WHERE email REGEXP '^[a-z]+@gmail\.com$';
SQL
#2.635
Q635:
What is the difference between IN and EXISTS?
Ans:
IN compares a value against a fixed or subquery-derived list of values and works well for smaller sets, while EXISTS checks only whether a correlated subquery returns any rows at all (stopping at the first match) and often performs better for large or correlated subqueries.
Code Example
SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
SQL
#2.636
Q636:
What is the COALESCE function used for?
Ans:
COALESCE returns the first non-NULL value from a list of expressions, commonly used to provide a fallback/default value when a column might contain NULL.
Code Example
SELECT COALESCE(phone, 'N/A') FROM users;
SQL
#2.637
Q637:
What is the difference between COALESCE and ISNULL?
Ans:
COALESCE is standard SQL and can accept any number of arguments, returning the first non-NULL one, while ISNULL (SQL Server-specific, or IFNULL in MySQL) accepts exactly two arguments and is not portable across all database systems.
SQL
#2.638
Q638:
What is the CASE statement used for in SQL?
Ans:
CASE provides conditional (if-else-like) logic within a SQL query, letting you compute different output values in a SELECT, ORDER BY, or WHERE clause based on evaluated conditions.
Code Example
SELECT name,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary > 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_band
FROM employees;
SQL
#2.639
Q639:
What is the difference between DISTINCT and GROUP BY?
Ans:
DISTINCT simply removes duplicate rows from the result set, while GROUP BY groups rows by shared column values specifically to enable aggregate calculations per group; GROUP BY without aggregates behaves similarly to DISTINCT but is generally used with aggregate functions.
Code Example
SELECT DISTINCT city FROM customers;
SQL
#2.640
Q640:
What is a schema in SQL?
Ans:
A schema is a logical namespace or container that organizes database objects like tables, views, and procedures, helping separate and manage related objects, control access permissions, and avoid naming collisions within a database.
SQL
#2.641
Q641:
What is the difference between a database and a schema?
Ans:
A database is the overall container that holds data and its structures, while a schema is a logical grouping within a database (in systems like PostgreSQL and SQL Server); in MySQL, however, 'database' and 'schema' are often used interchangeably.
SQL
#2.642
Q642:
What is a many-to-many relationship and how is it implemented in a relational database?
Ans:
A many-to-many relationship, where multiple rows in one table can relate to multiple rows in another, is implemented using a junction (or bridge/associative) table that holds foreign keys referencing both related tables.
Code Example
CREATE TABLE student_courses (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
SQL
#2.643
Q643:
What is a full table scan and why is it usually undesirable?
Ans:
A full table scan occurs when the database reads every row in a table to satisfy a query instead of using an index, which is slow and resource-intensive for large tables, typically indicating a missing or unused index for the query's filter conditions.
SQL
#2.644
Q644:
What is SQL injection and how can it be prevented?
Ans:
SQL injection is a security vulnerability where untrusted user input is concatenated directly into a SQL query, allowing an attacker to alter the query's logic; it is prevented by using parameterized queries or prepared statements instead of string concatenation, and by validating/escaping user input.
Code Example
-- Vulnerable:
"SELECT * FROM users WHERE username = '" + input + "'"
-- Safe (parameterized):
"SELECT * FROM users WHERE username = ?"
SQL
#2.645
Q645:
What is the difference between a prepared statement and a regular query?
Ans:
A prepared statement separates the SQL query structure from the data values, sending the query template to the database once and binding parameter values separately, which prevents SQL injection and can improve performance for repeated executions of the same query shape.
SQL
#2.646
Q646:
What is the difference between a temporary table and a regular table?
Ans:
A temporary table exists only for the duration of a session or transaction (depending on the database and how it's declared) and is automatically dropped afterward, while a regular table persists permanently until explicitly dropped.
Code Example
CREATE TEMPORARY TABLE temp_results AS
SELECT * FROM orders WHERE status = 'pending';
SQL
#2.647
Q647:
What is the difference between a relational database and a NoSQL database?
Ans:
A relational database stores structured data in tables with a fixed schema and enforces relationships via foreign keys, typically prioritizing strong consistency (ACID), while NoSQL databases (document, key-value, column-family, or graph stores) offer flexible or schema-less data models and often favor horizontal scalability and eventual consistency over strict relational integrity.
SQL
#2.648
Q648:
What is the difference between horizontal and vertical scaling for a database?
Ans:
Vertical scaling increases the capacity of a single server (more CPU, RAM, or storage), while horizontal scaling adds more servers and distributes the data and load across them (as with sharding or read replicas), generally offering better long-term scalability for very large workloads.
SQL
#2.649
Q649:
What is a database replica and what is it used for?
Ans:
A replica is a copy of a database (often read-only) kept synchronized with a primary database, used to distribute read traffic across multiple servers, provide failover in case the primary fails, or support geographically distributed access.
SQL
#2.650
Q650:
What is the difference between OLTP and OLAP systems?
Ans:
OLTP (Online Transaction Processing) systems are optimized for many short, frequent read/write transactions typical of everyday application use, while OLAP (Online Analytical Processing) systems are optimized for complex, read-heavy analytical queries over large historical datasets, often using denormalized or star-schema designs.
SQL
#2.651
Q651:
What is a data warehouse?
Ans:
A data warehouse is a centralized repository that consolidates data from multiple operational sources for reporting and analysis, typically organized using star or snowflake schemas optimized for complex analytical (OLAP) queries rather than transactional workloads.
SQL
#2.652
Q652:
What is the GROUP_CONCAT (or STRING_AGG) function used for?
Ans:
GROUP_CONCAT (MySQL) or STRING_AGG (PostgreSQL/SQL Server) concatenates values from multiple rows within a group into a single delimited string, useful for producing comma-separated lists in a result set.
Code Example
SELECT dept, GROUP_CONCAT(name SEPARATOR ', ') FROM employees GROUP BY dept;
SQL
#2.653
Q653:
What are the different storage engines in MySQL?
Ans:
MySQL supports multiple storage engines that determine how data is stored and accessed, including InnoDB (the default, supporting transactions and foreign keys), MyISAM (faster reads but no transaction support), MEMORY (stores data entirely in RAM for speed), and CSV (stores data in plain comma-separated files).
Code Example
CREATE TABLE logs (
id INT,
message VARCHAR(255)
) ENGINE=MyISAM;
SQL
#2.654
Q654:
What is the difference between the MEMORY and MyISAM storage engines?
Ans:
The MEMORY engine stores all table data directly in RAM, making it extremely fast but volatile (data is lost on server restart), while MyISAM stores data persistently on disk, surviving restarts but with slower access than in-memory storage.
SQL
#2.655
Q655:
Why is InnoDB the default storage engine in MySQL?
Ans:
InnoDB became the default engine because it supports ACID-compliant transactions, foreign key constraints, and row-level locking, making it far more suitable for reliable, concurrent, real-world applications than the older MyISAM engine.
SQL
#2.656
Q656:
What are the advantages of the InnoDB storage engine?
Ans:
InnoDB offers ACID compliance for reliable transactions, automatic crash recovery, row-level locking for better write concurrency, and support for foreign key constraints to enforce referential integrity.
SQL
#2.657
Q657:
What are the disadvantages of the InnoDB storage engine?
Ans:
InnoDB generally uses more disk space and memory than simpler engines like MyISAM, and can be somewhat slower for simple, read-only workloads where MyISAM's lighter-weight design and full-text indexing (in older MySQL versions) had an edge.
SQL
#2.658
Q658:
What is a super key?
Ans:
A super key is any combination of one or more columns that can uniquely identify a row in a table; unlike a candidate key, a super key may include extra, redundant columns beyond what's strictly necessary for uniqueness.
SQL
#2.659
Q659:
How do you find the nth highest salary in SQL?
Ans:
A common approach is to use LIMIT with OFFSET after sorting in descending order, or to use the DENSE_RANK() window function to properly handle ties, then filter for the desired rank.
Code Example
-- Using LIMIT/OFFSET (nth = 3rd highest)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC LIMIT 1 OFFSET 2;
-- Using DENSE_RANK
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t WHERE rnk = 3;
SQL
#2.660
Q660:
What is row-level locking?
Ans:
Row-level locking locks only the specific rows being read or modified by a transaction, rather than the entire table, allowing other transactions to concurrently access unrelated rows and improving overall concurrency; InnoDB supports row-level locking while MyISAM only supports table-level locking.
SQL
#2.661
Q661:
How do you provide security to a database?
Ans:
Database security is achieved through a combination of measures: using prepared statements/parameterized queries to prevent SQL injection, enforcing strict access control and least-privilege user permissions, encrypting sensitive data at rest and in transit, using strong passwords and rotating credentials, and maintaining regular backups.
Hard
213 questions
PHP
#3.1
Q1:
Why should you unset the reference variable after a foreach loop by reference?
Ans:
Because the reference variable continues to point to the last array element after the loop, so subsequent reuse of that variable name can unintentionally overwrite array data.
PHP
#3.2
Q2:
What is the difference between func_get_args() and variadic parameters?
Ans:
func_get_args() retrieves all arguments passed to a function regardless of the declared parameter list, while variadic parameters (...) explicitly collect extra arguments into a named array within the signature.
PHP
#3.3
Q3:
What is a first-class callable syntax in PHP 8.1?
Ans:
PHP 8.1 introduced a shorthand (strlen(...)) to create a Closure from any callable without using Closure::fromCallable() or a string reference.
Code Example
$fn = strlen(...);
PHP
#3.4
Q4:
How do you flatten a multidimensional array?
Ans:
There's no single built-in flatten function; you typically use array_merge(...$array) with the spread operator, or a recursive function combined with array_walk_recursive().
PHP
#3.5
Q5:
How do you iterate over an array and modify keys?
Ans:
You can build a new array using array_map with ARRAY_FILTER_USE_KEY, or manually loop and reassign, since PHP has no direct 'map keys' function.
PHP
#3.6
Q6:
Does PHP support method overloading like some other languages?
Ans:
PHP does not support traditional method overloading (same method name, different signatures); instead it uses magic methods like __call() to simulate dynamic method handling.
PHP
#3.7
Q7:
How do you resolve method conflicts between multiple traits?
Ans:
You use the 'insteadof' operator to specify which trait's method takes precedence, and 'as' to create an alias for a conflicting method.
Code Example
class C { use A, B { A::hello insteadof B; B::hello as helloB; } }
PHP
#3.8
Q8:
What is the difference between self:: and static:: in PHP?
Ans:
self:: refers to the class where the code is defined (compile-time binding), while static:: uses late static binding, resolving to the actual called class at runtime.
PHP
#3.9
Q9:
What is late static binding?
Ans:
Late static binding, introduced in PHP 5.3, allows referencing the called class in a context of static inheritance using the static:: keyword instead of self::.
PHP
#3.10
Q10:
What is __get() and __set() used for?
Ans:
__get() and __set() are magic methods triggered when accessing or assigning inaccessible or non-existent properties, enabling dynamic property handling.
Code Example
class Bag {
private array $data = [];
function __get($name){ return $this->data[$name] ?? null; }
function __set($name, $value){ $this->data[$name] = $value; }
}
PHP
#3.11
Q11:
What is __call() and __callStatic() used for?
Ans:
__call() is invoked when calling inaccessible or undefined instance methods, and __callStatic() does the same for static method calls, both useful for dynamic method dispatch.
PHP
#3.12
Q12:
What is __invoke() used for?
Ans:
__invoke() allows an object to be called as if it were a function.
Code Example
class Adder {
function __invoke($a, $b) { return $a + $b; }
}
$add = new Adder();
echo $add(2,3); // 5
PHP
#3.13
Q13:
What is __clone() used for?
Ans:
__clone() is automatically called when an object is cloned with the clone keyword, useful for deep-copying nested objects.
Code Example
$copy = clone $original;
PHP
#3.14
Q14:
What is an anonymous class in PHP?
Ans:
Introduced in PHP 7, anonymous classes let you create an object with a class definition inline, without naming the class, useful for simple one-off objects.
Code Example
$obj = new class {
public function hello() { return 'hi'; }
};
PHP
#3.15
Q15:
What is the Throwable interface?
Ans:
Throwable is the base interface implemented by both the Error and Exception class hierarchies, allowing a single catch block to handle either type.
PHP
#3.16
Q16:
What is a custom error handler in PHP?
Ans:
set_error_handler() registers a user-defined function to handle PHP errors instead of the default handler, allowing custom logging or formatting.
Code Example
set_error_handler(function($errno, $errstr) {
echo "Error: $errstr";
});
PHP
#3.17
Q17:
What is set_exception_handler() used for?
Ans:
set_exception_handler() defines a global function to handle any uncaught exceptions in the script, useful as a last resort for logging fatal issues.
PHP
#3.18
Q18:
What security checks should you perform on file uploads?
Ans:
You should validate file type and extension, check MIME type, enforce file size limits, rename files to avoid path traversal, and store uploads outside the web root or with restricted execution permissions.
PHP
#3.19
Q19:
What is session hijacking and how can it be mitigated?
Ans:
Session hijacking is when an attacker steals a valid session ID to impersonate a user; mitigations include regenerating the session ID after login with session_regenerate_id(), using HTTPS, and setting HttpOnly/Secure cookie flags.
PHP
#3.20
Q20:
What is a CSRF token and how is it typically implemented?
Ans:
A CSRF token is a random, unique value generated per session or form, embedded as a hidden field, and verified against the stored value on submission to ensure the request originated from the legitimate site.
Code Example
$_SESSION['csrf'] = bin2hex(random_bytes(32));
// in form:
<input type='hidden' name='csrf' value='<?= $_SESSION['csrf'] ?>'>
PHP
#3.21
Q21:
How do you prevent directory traversal attacks in PHP file operations?
Ans:
You should validate and sanitize file paths, use realpath() to resolve and confirm paths stay within an allowed directory, and avoid directly using user input to build file paths.
PHP
#3.22
Q22:
How do you validate an email format using regex versus filter_var?
Ans:
While regex patterns can validate email format, filter_var() with FILTER_VALIDATE_EMAIL is generally preferred since it is built-in, well-tested, and handles edge cases more reliably than most custom regex.
PHP
#3.23
Q23:
What is a non-greedy quantifier in regex?
Ans:
A non-greedy (lazy) quantifier, denoted by adding a ? after * or +, matches as few characters as possible instead of the default greedy behavior of matching as many as possible.
Code Example
preg_match('/<.+?>/', '<a><b>', $m); // matches '<a>' not '<a><b>'
PHP
#3.24
Q24:
What are attributes in PHP 8?
Ans:
Attributes provide a structured, native way to add metadata to classes, methods, and properties using #[...] syntax, replacing many use cases previously handled by docblock annotations.
Code Example
#[Route('/users', methods: ['GET'])]
function listUsers() {}
PHP
#3.25
Q25:
What is the JIT compiler introduced in PHP 8?
Ans:
The Just-In-Time compiler translates parts of the code into machine code at runtime, which can improve performance for CPU-intensive tasks, though typical web request performance gains are often modest.
PHP
#3.26
Q26:
What are the differences in error handling for division by zero between PHP 7 and PHP 8?
Ans:
In PHP 8, dividing an integer or float by zero using the / operator throws a DivisionByZeroError, whereas in PHP 7 it produced a warning and returned INF or NAN.
PHP
#3.27
Q27:
How has string-to-number comparison changed in PHP 8?
Ans:
In PHP 8, when comparing a number to a non-numeric string, the number is converted to a string for comparison (rather than the string being converted to 0 as in PHP 7), making comparisons more intuitive.
PHP
#3.28
Q28:
What is the WeakMap class introduced in PHP 8?
Ans:
WeakMap allows objects to be used as keys without preventing those objects from being garbage collected, useful for caching metadata about objects without causing memory leaks.
PHP
#3.29
Q29:
What are traits' limitations compared to interfaces?
Ans:
Traits provide actual method implementations for code reuse but do not enforce a contract or support polymorphism through type checking the way interfaces do; a class using a trait isn't considered an instance of that trait via instanceof.
PHP
#3.30
Q30:
What is Composer's autoload-dev section used for?
Ans:
autoload-dev defines autoloading rules that apply only during development, such as loading test classes, and are excluded when the package is installed as a dependency in production.
PHP
#3.31
Q31:
What is a PHP interface constant and can it be overridden?
Ans:
Interfaces can declare constants that implementing classes inherit; as of PHP 8.1, interface constants can be effectively customized via enum-based interfaces, but classic interface constants cannot be changed by implementing classes, only used.
PHP
#3.32
Q32:
What does the yield keyword do in PHP?
Ans:
yield is used inside a generator function to return a value to the caller while pausing execution, allowing iteration over potentially large or infinite sequences without holding all values in memory at once.
Code Example
function numbers() {
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
foreach (numbers() as $n) { echo $n; }
PHP
#3.33
Q33:
What is a PHP generator?
Ans:
A generator is a special type of iterator defined using a function containing yield statements, producing values one at a time on demand rather than computing and storing them all at once.
PHP
#3.34
Q34:
What is the difference between a generator and a regular array-returning function?
Ans:
A generator produces values lazily one at a time as they're requested, using minimal memory even for large datasets, while a regular function that returns an array must build and hold the entire result set in memory at once.
PHP
#3.35
Q35:
What is the __autoload function and why is it deprecated?
Ans:
__autoload() was a magic function used before PSR-based autoloaders to automatically load classes, but it was deprecated and removed in favor of the more flexible spl_autoload_register() function.
PHP
#3.36
Q36:
What does spl_autoload_register() do?
Ans:
spl_autoload_register() registers a function to be called automatically whenever an undefined class is referenced, forming the foundation for modern autoloading systems.
Code Example
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
PHP
#3.37
Q37:
What is the difference between abstract methods and interface methods in terms of visibility?
Ans:
Abstract methods can be declared as public or protected, while interface methods are implicitly and must be public since interfaces define a public contract.
PHP
#3.38
Q38:
What is the difference between a shallow copy and deep copy of an array in PHP?
Ans:
PHP arrays are copied by value by default (a shallow copy of scalar elements), but arrays containing objects only copy object references, so modifying a nested object still affects the original array's object.
JAVA
#3.39
Q39:
What happens if a class implements two interfaces with the same default method?
Ans:
The implementing class must explicitly override the method to resolve the ambiguity, otherwise a compile-time error occurs.
JAVA
#3.40
Q40:
What is the diamond problem and how does Java handle it with interfaces?
Ans:
The diamond problem occurs when a class inherits conflicting implementations from two sources; Java avoids it for classes by disallowing multiple inheritance, and for interfaces with conflicting default methods, it forces the implementing class to explicitly override the method.
JAVA
#3.41
Q41:
What is a local inner class?
Ans:
A local inner class is defined within a method body and is only visible and usable within that method's scope.
JAVA
#3.42
Q42:
What is method hiding in Java?
Ans:
Method hiding occurs when a subclass defines a static method with the same signature as a static method in the superclass; unlike overriding, the method called is determined by the reference type at compile time, not the actual object type.
JAVA
#3.43
Q43:
What is exception chaining?
Ans:
Exception chaining wraps a lower-level exception inside a new, higher-level exception (using the cause constructor parameter), preserving the original exception's information while providing more context.
Code Example
try {
// code
} catch (SQLException e) {
throw new RuntimeException("Query failed", e);
}
JAVA
#3.44
Q44:
How does a HashMap work internally?
Ans:
A HashMap stores entries in an array of buckets, computing a bucket index from the key's hashCode(); when multiple keys hash to the same bucket (collision), Java 8+ uses a linked list (or a balanced tree for large buckets) to store them.
JAVA
#3.45
Q45:
What is a ConcurrentModificationException?
Ans:
This runtime exception is thrown when a collection is structurally modified (e.g., adding/removing elements) while being iterated using a fail-fast iterator, other than through the iterator's own remove method.
JAVA
#3.46
Q46:
What is the difference between fail-fast and fail-safe iterators?
Ans:
Fail-fast iterators throw a ConcurrentModificationException if the underlying collection is modified during iteration (e.g., ArrayList), while fail-safe iterators operate on a cloned or separate copy of the collection, allowing modifications without exceptions (e.g., CopyOnWriteArrayList).
JAVA
#3.47
Q47:
What is the initial capacity and load factor of a HashMap?
Ans:
The default initial capacity is 16 buckets and the default load factor is 0.75, meaning the HashMap resizes (doubles capacity) once it is 75% full to maintain efficient performance.
JAVA
#3.48
Q48:
Why must objects used as HashMap keys override equals() and hashCode()?
Ans:
The HashMap relies on hashCode() to locate the correct bucket and equals() to confirm key equality within that bucket; without proper overrides, lookups and duplicate detection would not work correctly for custom objects.
JAVA
#3.49
Q49:
What is type erasure in Java generics?
Ans:
Type erasure is the process by which the compiler removes generic type information after compile-time checks, replacing type parameters with their bounds or Object, so generic type info is not available at runtime.
JAVA
#3.50
Q50:
What is a wildcard in Java generics?
Ans:
A wildcard (?) represents an unknown type in generics; ? extends T restricts to T or its subtypes (producer, read-only), and ? super T restricts to T or its supertypes (consumer, write-only).
Code Example
void printList(List<? extends Number> list) {
for (Number n : list) System.out.println(n);
}
JAVA
#3.51
Q51:
What is the PECS principle in Java generics?
Ans:
PECS stands for 'Producer Extends, Consumer Super' — use ? extends T when you only read (produce) items from a structure, and ? super T when you only write (consume) items into it.
JAVA
#3.52
Q52:
Can you create a generic array in Java?
Ans:
No, Java does not allow creating generic arrays directly (like new T[10]) due to type erasure and array covariance issues; workarounds include using Object arrays with casting or collections instead.
JAVA
#3.53
Q53:
What is the difference between String.intern() and creating a new String?
Ans:
intern() returns a canonical reference from the string pool for a given string's content, ensuring that equal string values share the same reference, unlike 'new String()' which always creates a distinct object on the heap.
JAVA
#3.54
Q54:
How can you prevent deadlocks in Java?
Ans:
Common strategies include acquiring locks in a consistent global order, using timeouts when attempting to acquire locks, minimizing lock scope, and avoiding nested locks where possible.
JAVA
#3.55
Q55:
What is the volatile keyword used for?
Ans:
volatile ensures that a variable's value is always read from and written directly to main memory, guaranteeing visibility of changes across threads, though it does not provide atomicity for compound operations.
Code Example
private volatile boolean running = true;
JAVA
#3.56
Q56:
What is the difference between synchronized and volatile?
Ans:
synchronized provides both mutual exclusion (atomicity) and visibility for a block of code, while volatile only guarantees visibility of a single variable's latest value across threads, without locking or atomicity for compound actions.
JAVA
#3.57
Q57:
What is the wait(), notify(), and notifyAll() used for?
Ans:
These Object class methods enable inter-thread communication: wait() makes a thread release its lock and pause until notified, notify() wakes one waiting thread, and notifyAll() wakes all threads waiting on that object's monitor.
JAVA
#3.58
Q58:
What is CompletableFuture used for?
Ans:
CompletableFuture, introduced in Java 8, represents a future result that can be composed, chained, and combined with other asynchronous operations without blocking, using methods like thenApply() and thenCombine().
Code Example
CompletableFuture.supplyAsync(() -> compute())
.thenApply(result -> result * 2)
.thenAccept(System.out::println);
JAVA
#3.59
Q59:
What are atomic classes in Java concurrency?
Ans:
Classes like AtomicInteger and AtomicLong provide lock-free, thread-safe operations on single variables using low-level compare-and-swap (CAS) instructions, useful for simple counters without full synchronization overhead.
Code Example
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
JAVA
#3.60
Q60:
What is the difference between a thread's user thread and daemon thread?
Ans:
User threads keep the JVM running until they complete, while daemon threads run in the background and are automatically terminated when all user threads finish, typically used for tasks like garbage collection.
JAVA
#3.61
Q61:
What is the difference between java.io and java.nio?
Ans:
java.io provides a stream-based, blocking I/O API, while java.nio (New I/O) introduced buffer-based, potentially non-blocking I/O with channels, offering better performance for certain use cases like handling many connections.
JAVA
#3.62
Q62:
What is the difference between map() and flatMap() in streams?
Ans:
map() transforms each element into another single element, while flatMap() transforms each element into a stream and flattens all resulting streams into a single stream.
Code Example
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4));
List<Integer> flat = nested.stream().flatMap(List::stream).collect(Collectors.toList());
JAVA
#3.63
Q63:
What are the different types of method references?
Ans:
Java supports references to static methods (ClassName::staticMethod), instance methods of a particular object (instance::method), instance methods of an arbitrary object of a type (ClassName::instanceMethod), and constructors (ClassName::new).
JAVA
#3.64
Q64:
What is the difference between findFirst() and findAny() in streams?
Ans:
findFirst() returns the first element encountered in encounter order, while findAny() returns any element and may be more efficient in parallel streams since it doesn't need to respect ordering.
JAVA
#3.65
Q65:
What is a parallel stream in Java?
Ans:
A parallel stream splits the source data into multiple chunks processed concurrently across multiple threads (using the common ForkJoinPool), potentially improving performance for large datasets and CPU-intensive operations.
Code Example
list.parallelStream().forEach(System.out::println);
JAVA
#3.66
Q66:
What is a sealed class in Java 17?
Ans:
Sealed classes restrict which other classes or interfaces may extend or implement them, explicitly listing permitted subtypes, improving control over class hierarchies for pattern matching and exhaustiveness.
Code Example
public sealed interface Shape permits Circle, Square {}
JAVA
#3.67
Q67:
What are the different memory areas managed by the JVM?
Ans:
The JVM manages the heap (objects), the stack (method frames per thread), the method area/metaspace (class metadata), the program counter register, and native method stacks.
JAVA
#3.68
Q68:
What is the difference between the young generation and old generation in heap memory?
Ans:
The young generation holds newly created, typically short-lived objects and is collected frequently (minor GC), while the old (tenured) generation holds long-lived objects that have survived multiple garbage collection cycles, collected less frequently (major GC).
JAVA
#3.69
Q69:
What causes a memory leak in Java despite automatic garbage collection?
Ans:
Memory leaks can still occur when objects remain reachable through unintended references (like static collections that keep growing, unclosed resources, or listeners not deregistered), preventing the garbage collector from reclaiming them.
JAVA
#3.70
Q70:
What is class loading in Java?
Ans:
Class loading is the process by which the JVM's class loader dynamically loads compiled .class files into memory, following a hierarchy (bootstrap, extension/platform, and application class loaders) as classes are needed.
JAVA
#3.71
Q71:
What is reflection in Java?
Ans:
Reflection is an API (java.lang.reflect) that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even those not known at compile time.
Code Example
Class<?> clazz = Class.forName("com.example.User");
Method[] methods = clazz.getDeclaredMethods();
JAVA
#3.72
Q72:
What is the difference between == and equals() for wrapper classes like Integer?
Ans:
For small cached Integer values (-128 to 127), == may return true due to integer caching, but for values outside that range or explicitly created objects, == compares references while equals() correctly compares values.
Code Example
Integer a = 100, b = 100;
System.out.println(a == b); // true (cached)
Integer c = 200, d = 200;
System.out.println(c == d); // false
JAVA
#3.73
Q73:
What is object cloning in Java?
Ans:
Cloning creates a copy of an object using the clone() method from the Cloneable interface; by default, Object's clone() performs a shallow copy, so classes needing deep copies must override clone() accordingly.
Code Example
class Point implements Cloneable {
public Point clone() throws CloneNotSupportedException {
return (Point) super.clone();
}
}
JAVA
#3.74
Q74:
What is the difference between a top-level class and an inner class regarding access to private members?
Ans:
An inner (non-static nested) class has implicit access to the enclosing instance's private members, while a top-level class must access another class's members through normal visibility rules (public/protected/package-private).
JAVA
#3.75
Q75:
What does the Collectors.groupingBy() do?
Ans:
groupingBy() collects stream elements into a Map grouped by a classifier function, similar to a SQL GROUP BY, optionally combined with a downstream collector for further aggregation.
Code Example
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
JAVA
#3.76
Q76:
What is the difference between reduce() and collect() in the Stream API?
Ans:
reduce() combines stream elements into a single immutable result using an associative accumulator function, while collect() performs a mutable reduction, accumulating elements into a mutable container like a List or Map.
JAVA
#3.77
Q77:
What is the difference between Arrays.asList() and a regular ArrayList?
Ans:
Arrays.asList() returns a fixed-size list backed directly by the array, so you cannot add or remove elements (though you can set existing ones), while a regular ArrayList is fully resizable and independent of any array.
JAVA
#3.78
Q78:
What is the difference between peek() and forEach() in streams?
Ans:
peek() is an intermediate operation used mainly for debugging that returns the same stream unchanged for further processing, while forEach() is a terminal operation that consumes the stream and returns nothing.
JAVA
#3.79
Q79:
What is the Liskov Substitution Principle?
Ans:
It states that objects of a superclass should be replaceable with objects of a subclass without altering the correctness of the program, meaning subclasses must honor the behavioral contract of their parent type.
JAVA
#3.80
Q80:
What is the purpose of the Comparable interface's compareTo() method contract?
Ans:
compareTo() should return a negative number, zero, or a positive number if the current object is less than, equal to, or greater than the specified object, and should be consistent with equals() for well-behaved sorted collections.
JAVA
#3.81
Q81:
What is the purpose of the assert keyword in Java?
Ans:
assert evaluates a boolean expression and throws an AssertionError if it's false, primarily used for internal self-checks during development and testing; assertions are disabled by default at runtime unless explicitly enabled with the -ea flag.
Code Example
assert age >= 0 : "Age cannot be negative";
PYTHON
#3.82
Q82:
What is the else clause on a loop used for in Python?
Ans:
The else block on a for or while loop executes only if the loop completes normally without hitting a break statement.
Code Example
for i in range(5):
if i == 10:
break
else:
print('Loop completed without break')
PYTHON
#3.83
Q83:
What is the danger of using a mutable default argument in Python?
Ans:
Default argument values are evaluated only once when the function is defined, so using a mutable object (like a list or dict) as a default can cause it to be shared and unexpectedly modified across multiple calls.
Code Example
def add_item(item, items=[]): # BUG: shared list
items.append(item)
return items
PYTHON
#3.84
Q84:
How do you write a decorator that accepts arguments?
Ans:
You need an additional outer function that accepts the decorator's arguments and returns the actual decorator function, which in turn wraps the target function.
Code Example
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hi():
print('Hi')
PYTHON
#3.85
Q85:
What does functools.wraps do?
Ans:
functools.wraps is a decorator used inside custom decorators to preserve the original function's metadata (like __name__ and __doc__) on the wrapper function, which would otherwise be overwritten.
Code Example
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
PYTHON
#3.86
Q86:
What is the maximum recursion depth in Python and how can you change it?
Ans:
Python has a default recursion limit (typically 1000) to prevent stack overflow from infinite recursion, which can be adjusted using sys.setrecursionlimit(), though increasing it too much risks crashing the interpreter.
Code Example
import sys
sys.setrecursionlimit(2000)
PYTHON
#3.87
Q87:
What is the difference between pass by value and pass by reference in Python function calls?
Ans:
Python uses 'pass by object reference': mutable objects passed to a function can be modified in place affecting the caller, while reassigning the parameter to a new object inside the function does not affect the caller's original reference.
Code Example
def modify(lst):
lst.append(4) # affects caller's list
lst = [9,9,9] # does not affect caller's reference
my_list = [1,2,3]
modify(my_list) # my_list becomes [1,2,3,4]
PYTHON
#3.88
Q88:
What is the Method Resolution Order (MRO) in Python?
Ans:
MRO defines the order in which base classes are searched when executing a method, determined by the C3 linearization algorithm; it can be inspected using ClassName.__mro__ or ClassName.mro().
PYTHON
#3.89
Q89:
Why should you define __hash__ when overriding __eq__?
Ans:
If a class overrides __eq__, Python sets __hash__ to None by default, making instances unhashable; if the objects need to be used in sets or as dict keys, __hash__ must be explicitly defined consistently with __eq__.
PYTHON
#3.90
Q90:
What is name mangling in Python?
Ans:
Name mangling automatically renames attributes prefixed with double underscores (like __value) to _ClassName__value internally, helping avoid accidental name clashes in subclasses rather than providing true access restriction.
Code Example
class Base:
def __init__(self):
self.__secret = 42 # becomes _Base__secret
PYTHON
#3.91
Q91:
What is a class's __slots__ attribute used for?
Ans:
__slots__ restricts the set of attributes an instance can have, preventing creation of a per-instance __dict__ and reducing memory usage, useful when creating many instances of a simple class.
Code Example
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
PYTHON
#3.92
Q92:
What is a metaclass in Python?
Ans:
A metaclass is the 'class of a class', controlling how classes themselves are created; by default this is type, but custom metaclasses can customize class creation behavior, commonly used in advanced frameworks.
Code Example
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
PYTHON
#3.93
Q93:
What is the purpose of the __call__ method?
Ans:
__call__ allows an instance of a class to be invoked like a function using parentheses, enabling objects to behave as callables.
Code Example
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
triple = Multiplier(3)
print(triple(5)) # 15
PYTHON
#3.94
Q94:
What is exception chaining in Python using 'raise ... from ...'?
Ans:
The 'raise NewException() from original_exception' syntax explicitly links a new exception to the one that caused it, preserving context and making the traceback clearer when re-raising a different exception type.
Code Example
try:
int('abc')
except ValueError as e:
raise RuntimeError('Conversion failed') from e
PYTHON
#3.95
Q95:
How do you write a custom context manager using a class?
Ans:
You implement __enter__ (returning the resource, run at the start of the with block) and __exit__ (handling cleanup and optionally suppressing exceptions, run at the end).
Code Example
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f'Elapsed: {time.time() - self.start}')
PYTHON
#3.96
Q96:
How do you write a context manager using a generator and the contextlib module?
Ans:
The @contextlib.contextmanager decorator lets you write a context manager as a generator function, using yield to separate setup code (before yield) from teardown code (after yield).
Code Example
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
yield
print(f'Elapsed: {time.time() - start}')
PYTHON
#3.97
Q97:
What does the yield from statement do?
Ans:
yield from delegates iteration to a sub-generator or other iterable, yielding all of its values directly, simplifying code that would otherwise require an explicit loop to forward each value.
Code Example
def inner():
yield 1
yield 2
def outer():
yield from inner()
yield 3
PYTHON
#3.98
Q98:
How do you create a custom iterable class in Python?
Ans:
You implement __iter__ (returning an iterator object, often self) and __next__ (returning the next item or raising StopIteration when done) on your class.
Code Example
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
PYTHON
#3.99
Q99:
What is the Global Interpreter Lock (GIL) in Python?
Ans:
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems, which limits true parallelism for CPU-bound multithreaded code but doesn't affect I/O-bound concurrency as much.
PYTHON
#3.100
Q100:
What is the difference between multithreading and multiprocessing in Python?
Ans:
Multithreading runs multiple threads within a single process sharing memory, but is limited by the GIL for CPU-bound tasks, while multiprocessing runs separate processes each with its own Python interpreter and memory space, achieving true parallelism for CPU-bound work at the cost of higher overhead.
PYTHON
#3.101
Q101:
When should you use multiprocessing instead of multithreading in Python?
Ans:
Multiprocessing is preferred for CPU-bound tasks that need true parallel execution across cores, since it bypasses the GIL, while multithreading is more suitable for I/O-bound tasks (like network requests or file operations) where threads spend most of their time waiting.
PYTHON
#3.102
Q102:
What is the difference between async/await and threading in Python?
Ans:
async/await uses a single-threaded event loop with cooperative multitasking, where tasks explicitly yield control at await points, while threading uses OS-level preemptive multitasking across multiple threads, subject to the GIL for CPU-bound work.
PYTHON
#3.103
Q103:
What is a race condition and how can you prevent it in Python threads?
Ans:
A race condition occurs when multiple threads access and modify shared data concurrently, producing unpredictable results; it can be prevented using synchronization primitives like threading.Lock to ensure exclusive access to shared resources.
Code Example
lock = threading.Lock()
with lock:
shared_counter += 1
PYTHON
#3.104
Q104:
What is a reference cycle and how does Python handle it?
Ans:
A reference cycle occurs when two or more objects reference each other, preventing their reference counts from reaching zero even when they're unreachable from the rest of the program; Python's generational garbage collector (gc module) periodically detects and collects these cycles.
PYTHON
#3.105
Q105:
What are Python's memory optimization techniques like interning?
Ans:
Python caches small integers (-5 to 256) and some string literals so that multiple references to the same value point to the same object in memory, reducing memory usage and improving comparison speed for common ones.
PYTHON
#3.106
Q106:
What is functools.singledispatch used for?
Ans:
singledispatch allows a function to have different implementations based on the type of its first argument, effectively simulating single-argument type-based overloading in Python.
Code Example
from functools import singledispatch
@singledispatch
def process(arg):
print('default')
@process.register
def _(arg: int):
print('int handler')
PYTHON
#3.107
Q107:
What is the difference between deepcopy and copy.copy for functions with default arguments?
Ans:
This is unrelated to defaults directly, but copy.copy() creates a shallow copy sharing nested references, while copy.deepcopy() recursively duplicates all nested objects; using deepcopy avoids unintentionally shared mutable state between copies.
PYTHON
#3.108
Q108:
What is currying in the context of Python functions?
Ans:
Currying transforms a function taking multiple arguments into a sequence of functions each taking a single argument; Python doesn't support it natively but it can be implemented manually or via functools.partial.
PYTHON
#3.109
Q109:
What is the difference between deepcopy of an object and pickling/unpickling it?
Ans:
Both can produce an independent copy of complex nested objects, but deepcopy operates purely in memory and works with more object types directly, while pickling serializes to bytes (useful for storage or transfer) and requires objects to be picklable.
PYTHON
#3.110
Q110:
What is monkey patching in Python?
Ans:
Monkey patching is dynamically modifying or extending a class or module's attributes/methods at runtime, often used in testing or to patch third-party code, though it can make code harder to understand and maintain if overused.
Code Example
import module
module.some_function = lambda: 'patched'
PYTHON
#3.111
Q111:
What is the __new__ method and how does it differ from __init__?
Ans:
__new__ is a static method responsible for creating and returning a new instance (called before __init__), while __init__ initializes the already-created instance's attributes; __new__ is rarely overridden except for immutable types or metaclass-related patterns.
Code Example
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
PYTHON
#3.112
Q112:
What is the difference between a shallow interface and Python's protocol typing (structural typing)?
Ans:
Python's typing.Protocol (PEP 544) enables structural typing, where an object is considered compatible with a type if it has the required methods/attributes, regardless of explicit inheritance, aligning with duck typing but allowing static type checkers to verify it.
Code Example
from typing import Protocol
class Sized(Protocol):
def __len__(self) -> int: ...
PYTHON
#3.113
Q113:
What is the purpose of the __del__ method?
Ans:
__del__ is called when an object is about to be garbage collected, sometimes used for cleanup, but its exact timing is not guaranteed (especially with reference cycles), so context managers are generally preferred for reliable resource cleanup.
PYTHON
#3.114
Q114:
What is the difference between shallow scoping in list comprehensions across Python 2 and 3?
Ans:
In Python 3, the loop variable in a list comprehension is scoped locally to the comprehension itself and doesn't leak into the enclosing scope, unlike in Python 2 where it did leak and could overwrite existing variables.
PYTHON
#3.115
Q115:
What is the GIL's impact on I/O-bound versus CPU-bound multithreaded programs?
Ans:
The GIL is released during blocking I/O operations, so I/O-bound multithreaded programs can still achieve good concurrency, while CPU-bound multithreaded programs see little to no speedup from multiple threads since only one thread executes Python bytecode at a time.
PYTHON
#3.116
Q116:
What is the difference between iter(obj) and iter(callable, sentinel)?
Ans:
iter(obj) returns an iterator from an iterable object, while the two-argument form iter(callable, sentinel) repeatedly calls the callable, yielding its results until the sentinel value is returned, at which point iteration stops.
PYTHON
#3.117
Q117:
What is a context variable and when might contextvars be used?
Ans:
The contextvars module provides context-local state that works correctly across async tasks and threads, useful for tracking per-request data (like a request ID) in asynchronous web applications without relying on thread-local storage.
PYTHON
#3.118
Q118:
What is the difference between Python's == operator behavior for lists versus tuples containing the same elements?
Ans:
Both lists and tuples compare element-wise for equality with ==, so a list and tuple with identical elements in the same order compare as unequal only because their types differ, not their contents; comparing list == tuple with same elements returns False due to differing types, but list == list or tuple == tuple with matching contents returns True.
NODE.JS
#3.119
Q119:
What are the phases of the Node.js event loop?
Ans:
The main phases are: timers (setTimeout/setInterval callbacks), pending callbacks, poll (retrieving new I/O events), check (setImmediate callbacks), and close callbacks, cycling repeatedly while the process runs.
NODE.JS
#3.120
Q120:
What is the difference between process.nextTick() and setImmediate()?
Ans:
process.nextTick() queues a callback to run immediately after the current operation completes, before the event loop continues to the next phase, while setImmediate() queues a callback to run in the check phase of the next event loop iteration.
Code Example
process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('immediate'));
console.log('sync');
NODE.JS
#3.121
Q121:
What is the difference between Promise.race() and Promise.any()?
Ans:
Promise.race() resolves or rejects as soon as the first promise settles (whether fulfilled or rejected), while Promise.any() resolves as soon as the first promise fulfills, only rejecting if all promises reject.
NODE.JS
#3.122
Q122:
How can you handle CPU-intensive tasks in Node.js without blocking the event loop?
Ans:
You can offload CPU-intensive work to worker threads (via the worker_threads module), child processes, or a separate microservice, keeping the main event loop free to handle I/O.
Code Example
const { Worker } = require('worker_threads');
const worker = new Worker('./heavy-task.js');
NODE.JS
#3.123
Q123:
What is the microtask queue and how does it relate to the event loop?
Ans:
The microtask queue holds callbacks from resolved Promises (and process.nextTick callbacks in Node), which are processed completely after the current synchronous code finishes but before the event loop proceeds to the next macrotask (like a timer callback).
NODE.JS
#3.124
Q124:
What happens if an EventEmitter emits an 'error' event with no listener attached?
Ans:
If there is no listener for the 'error' event, Node.js throws the error and crashes the process, so it's considered best practice to always attach an error listener to EventEmitters that may emit errors.
NODE.JS
#3.125
Q125:
What is the module wrapper function in Node.js?
Ans:
Node.js wraps every CommonJS module's code in a function providing the exports, require, module, __filename, and __dirname parameters, giving each module its own private scope.
Code Example
(function(exports, require, module, __filename, __dirname) {
// module code
});
NODE.JS
#3.126
Q126:
How does Node.js resolve a require('./module') call?
Ans:
Node.js looks for an exact file match first, then tries appending extensions like .js, .json, and .node, and if it's a directory, looks for an index.js file or a 'main' field in that directory's package.json.
NODE.JS
#3.127
Q127:
What is backpressure in the context of Node.js streams?
Ans:
Backpressure occurs when a writable stream cannot process incoming data as fast as a readable stream produces it; Node.js streams handle this automatically when using pipe(), pausing the readable stream until the writable stream catches up.
NODE.JS
#3.128
Q128:
What is an uncaught exception in Node.js and how can you handle it globally?
Ans:
An uncaught exception is a synchronous error not caught by any try-catch block, which by default crashes the process; you can listen for process.on('uncaughtException', handler) as a last-resort safety net, though it's best practice to let the process exit and restart via a process manager after logging.
Code Example
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
NODE.JS
#3.129
Q129:
What is an unhandled promise rejection and how do you catch it globally?
Ans:
An unhandled rejection occurs when a Promise rejects without a .catch() handler; you can listen for process.on('unhandledRejection', handler) to log or handle such cases globally, though Node.js may terminate the process by default in newer versions.
Code Example
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
});
NODE.JS
#3.130
Q130:
What is the difference between operational errors and programmer errors in Node.js?
Ans:
Operational errors are runtime problems in a correctly written program (like a failed network request or invalid user input) that should be handled gracefully, while programmer errors are bugs (like accessing a property of undefined) that generally indicate the process should be restarted rather than recovered from.
NODE.JS
#3.131
Q131:
What is the difference between exec(), execFile(), spawn(), and fork() in child_process?
Ans:
exec() runs a command in a shell and buffers the entire output; execFile() runs an executable directly without a shell; spawn() launches a process and streams output incrementally, better for large data; fork() specifically spawns a new Node.js process with a built-in IPC channel for message passing.
NODE.JS
#3.132
Q132:
What is the cluster module used for in Node.js?
Ans:
The cluster module allows a Node.js application to spawn multiple worker processes (typically one per CPU core) that share the same server port, improving throughput and resilience by utilizing multiple cores despite Node.js's single-threaded nature.
Code Example
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
for (let i = 0; i < os.cpus().length; i++) cluster.fork();
} else {
require('./server');
}
NODE.JS
#3.133
Q133:
What is the difference between cluster and worker_threads in Node.js?
Ans:
cluster creates multiple independent processes (each with its own memory and event loop) primarily to scale network servers across CPU cores, while worker_threads creates threads within the same process that can share memory (via SharedArrayBuffer), better suited for CPU-intensive computations.
NODE.JS
#3.134
Q134:
How do parent and child processes communicate in Node.js when using fork()?
Ans:
fork() automatically sets up an IPC (inter-process communication) channel, allowing the parent and child to send messages to each other using process.send() and listening with the 'message' event.
Code Example
// parent.js
const child = require('child_process').fork('child.js');
child.send({ hello: 'world' });
child.on('message', msg => console.log(msg));
NODE.JS
#3.135
Q135:
What are JavaScript Symbols used for?
Ans:
A Symbol is a unique and immutable primitive value often used as a special, collision-free property key on objects, useful for defining semi-private object properties or well-known meta-behaviors (like Symbol.iterator).
NODE.JS
#3.136
Q136:
What is memory leak detection in Node.js and what tools can help?
Ans:
A memory leak occurs when an application unintentionally retains references to objects, preventing garbage collection and causing memory usage to grow over time; tools like the built-in --inspect flag with Chrome DevTools, heap snapshots, and clinic.js can help identify leaks.
NODE.JS
#3.137
Q137:
What is HATEOAS in the context of REST APIs?
Ans:
HATEOAS (Hypermedia as the Engine of Application State) is a REST constraint where API responses include links to related actions or resources, allowing clients to navigate the API dynamically rather than hardcoding endpoint URLs.
NODE.JS
#3.138
Q138:
What is the difference between synchronous middleware and asynchronous middleware in Express?
Ans:
Synchronous middleware executes and calls next() immediately, while asynchronous middleware (using Promises or async/await) must properly handle errors (e.g., wrapping with a try-catch and calling next(err), or using a wrapper utility) since unhandled async errors won't be automatically caught by Express's default error handling.
NODE.JS
#3.139
Q139:
What is the difference between a Node.js Buffer and a TypedArray?
Ans:
Buffer is a Node.js-specific subclass of Uint8Array (a TypedArray) with additional Node-specific convenience methods for encoding/decoding, and both provide a fixed-length view over raw binary data.
NODE.JS
#3.140
Q140:
What is the difference between an ESM default export and a named export when required from CommonJS?
Ans:
When a CommonJS module requires an ES Module, the ESM's default export is accessed via the .default property of the imported object, while named exports are accessed as properties directly, since Node.js wraps the ESM's exports in an interop object.
NODE.JS
#3.141
Q141:
What is the difference between synchronous logging and asynchronous logging performance implications in Node.js?
Ans:
Synchronous logging (like writing directly and waiting) can block the event loop under heavy load, while asynchronous, buffered logging libraries (like Pino) minimize performance impact by writing logs without blocking the main thread's request processing.
NODE.JS
#3.142
Q142:
What is the difference between a synchronous stack overflow and an event loop blocking issue in Node.js?
Ans:
A stack overflow occurs from excessive nested/recursive synchronous function calls exceeding the call stack size, crashing with a RangeError, while event loop blocking occurs when a long-running synchronous operation (like a heavy loop) prevents the event loop from processing other pending callbacks, without necessarily crashing.
NODE.JS
#3.143
Q143:
What is the difference between npm workspaces and a tool like Lerna for monorepos?
Ans:
npm workspaces (built into npm 7+) provide native support for managing multiple packages within a single repository, handling shared dependency hoisting and cross-package linking, while Lerna is a third-party tool that adds additional monorepo-specific features like versioning and publishing workflows, and can be used alongside or instead of workspaces.
NODE.JS
#3.144
Q144:
What is the difference between readable stream 'flowing' and 'paused' modes?
Ans:
In flowing mode, data is read from the underlying system automatically and emitted via 'data' events as fast as possible, while in paused mode, you must explicitly call stream.read() to retrieve chunks of data, giving more manual control over consumption.
NODE.JS
#3.145
Q145:
How do you create a custom readable stream in Node.js?
Ans:
You extend the stream.Readable class and implement the _read() method, pushing data using this.push() and signaling the end of the stream by pushing null.
Code Example
const { Readable } = require('stream');
class MyStream extends Readable {
_read() {
this.push('data chunk');
this.push(null); // end stream
}
}
NODE.JS
#3.146
Q146:
What is the SameSite cookie attribute and why does it matter for security?
Ans:
SameSite controls whether a cookie is sent with cross-site requests; setting it to 'Strict' or 'Lax' helps mitigate CSRF attacks by preventing the browser from automatically including the cookie on requests originating from other sites.
NODE.JS
#3.147
Q147:
What is the difference between a synchronous route handler throwing an error and an async route handler throwing an error in Express (pre-Express 5)?
Ans:
In versions before Express 5, a thrown error in a synchronous handler is automatically caught by Express's default mechanism, but an error thrown inside an async function (rejected Promise) is not automatically caught and must be explicitly passed to next(err) or handled with a wrapper utility, otherwise it becomes an unhandled rejection.
NODE.JS
#3.148
Q148:
What is a common pattern for wrapping async Express route handlers to catch errors automatically?
Ans:
A helper function wraps the async handler in a try-catch (or uses .catch(next) on the returned Promise), forwarding any error to next() so Express's error-handling middleware can process it consistently.
Code Example
const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.get('/users', asyncHandler(async (req, res) => {
const users = await getUsers();
res.json(users);
}));
NODE.JS
#3.149
Q149:
What is the difference between a hard dependency and a peer dependency in package.json?
Ans:
A regular dependency is installed automatically alongside the package that requires it, while a peerDependency signals that the package expects the consuming project to provide a compatible version itself (commonly used by plugins that must share the exact instance of a host library, like React or Express).
NODE.JS
#3.150
Q150:
What is clustering's main limitation regarding shared in-memory state?
Ans:
Since each cluster worker is a separate process with its own memory space, in-memory data (like a cache or session store) is not automatically shared between workers, requiring an external shared store (like Redis) for consistent state across the cluster.
NODE.JS
#3.151
Q151:
What is the difference between synchronous crypto hashing and bcrypt's intentional slowness?
Ans:
General-purpose hash functions (like SHA-256) are designed to be extremely fast, making them unsuitable for password hashing since attackers can brute-force them quickly, while bcrypt is intentionally slow and configurable (via a cost factor) specifically to resist brute-force password cracking.
NODE.JS
#3.152
Q152:
What is the difference between require.cache and clearing a module's cached export?
Ans:
require.cache is an object where Node.js stores already-loaded modules keyed by their resolved file path; deleting an entry from require.cache forces the next require() call for that path to re-execute and re-cache the module, useful in certain hot-reloading or testing scenarios.
Code Example
delete require.cache[require.resolve('./myModule')];
NODE.JS
#3.153
Q153:
What is the difference between a Node.js Timer object returned by setTimeout and the underlying OS timer?
Ans:
The object returned by setTimeout() is a Node.js Timeout object providing methods like .unref() (allowing the process to exit even if the timer is still pending) and .ref(), managed internally by libuv's timer implementation rather than directly by the OS.
NODE.JS
#3.154
Q154:
What is the purpose of the Content-Length and Transfer-Encoding: chunked headers in HTTP responses?
Ans:
Content-Length specifies the exact size of the response body in bytes, while Transfer-Encoding: chunked is used when the total size isn't known upfront, allowing the response to be sent in a series of chunks, common with streaming responses.
NODE.JS
#3.155
Q155:
What is a Node.js worker_threads module used for?
Ans:
worker_threads allows running JavaScript in parallel on separate threads within the same process, useful for CPU-intensive tasks, and supports sharing memory between threads via SharedArrayBuffer, unlike child processes which have fully isolated memory.
NODE.JS
#3.156
Q156:
What is the difference between synchronous compression and streaming compression using zlib?
Ans:
Synchronous methods like zlib.gzipSync() compress an entire buffer in memory at once and block execution, while streaming compression (piping through zlib.createGzip()) processes data incrementally in chunks, using less memory for large files and not blocking the event loop.
REACT.JS
#3.157
Q157:
What is the significance of the key prop when using Portals?
Ans:
Keys behave the same for portals as for any other React element; even though a portal renders elsewhere in the DOM, it still participates in the normal React tree for event bubbling and reconciliation purposes, so keys remain relevant when rendering lists of portals.
REACT.JS
#3.158
Q158:
What is useImperativeHandle used for?
Ans:
useImperativeHandle customizes the instance value that is exposed to parent components when using ref, letting you expose a limited, specific API instead of the raw DOM node.
Code Example
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus()
}));
REACT.JS
#3.159
Q159:
What is the significance of the useLayoutEffect Hook?
Ans:
useLayoutEffect fires synchronously after all DOM mutations but before the browser paints, making it suitable for reading layout and synchronously re-rendering to avoid visual flicker, unlike useEffect which fires asynchronously after paint.
REACT.JS
#3.160
Q160:
What is the difference between synchronous and batched state updates in React?
Ans:
React batches multiple state updates that occur within the same event handler into a single re-render for performance; React 18 extended automatic batching to updates inside promises, timeouts, and native event handlers, which previously were not batched.
REACT.JS
#3.161
Q161:
What is React 18's concurrent rendering?
Ans:
Concurrent rendering allows React to prepare multiple versions of the UI at the same time, interrupt rendering work that is no longer relevant, and prioritize urgent updates over less urgent ones, improving perceived responsiveness without blocking the main thread.
REACT.JS
#3.162
Q162:
What is useTransition used for?
Ans:
useTransition lets you mark certain state updates as non-urgent 'transitions,' so React can keep the UI responsive by rendering more urgent updates first and showing the transition's result when it's ready, along with an isPending flag to show a pending state.
Code Example
const [isPending, startTransition] = useTransition();
startTransition(() => setTab('profile'));
REACT.JS
#3.163
Q163:
What is useDeferredValue used for?
Ans:
useDeferredValue lets you defer re-rendering a non-urgent part of the UI, returning a deferred version of a value that lags behind the latest value until more urgent updates have completed, useful for keeping typing responsive while filtering large lists.
Code Example
const deferredQuery = useDeferredValue(query);
REACT.JS
#3.164
Q164:
What is hydration in the context of React?
Ans:
Hydration is the process by which React attaches event listeners and internal state to server-rendered HTML on the client, reusing the existing markup instead of re-creating the DOM from scratch, used with server-side rendering frameworks like Next.js.
REACT.JS
#3.165
Q165:
What is list virtualization and when should you use it?
Ans:
List virtualization (or windowing) renders only the items currently visible in the viewport instead of the entire list, dramatically improving performance for very long lists; libraries like react-window and react-virtualized implement this pattern.
REACT.JS
#3.166
Q166:
What is the difference between React.Component and PureComponent regarding deep data structures?
Ans:
Both perform shallow comparisons only, so mutating a nested object or array in place (rather than creating a new reference) will not be detected by PureComponent's shouldComponentUpdate, leading to a missed re-render; immutable update patterns are required.
REACT.JS
#3.167
Q167:
What is the difference between shallow rendering and full DOM rendering in testing?
Ans:
Shallow rendering (via Enzyme) renders only one level deep, stubbing out child components, while full DOM rendering mounts the entire component tree into a real or simulated DOM; React Testing Library favors full rendering to better reflect actual behavior.
REACT.JS
#3.168
Q168:
What is the useId Hook used for?
Ans:
useId (introduced in React 18) generates a unique, stable ID that is consistent between server and client renders, useful for associating form labels with inputs via id/htmlFor without risking hydration mismatches.
Code Example
const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />
REACT.JS
#3.169
Q169:
What is the useSyncExternalStore Hook used for?
Ans:
useSyncExternalStore lets components safely subscribe to external data sources outside of React's state (like a browser API or a third-party store) in a way that's compatible with concurrent rendering, avoiding tearing between renders.
REACT.JS
#3.170
Q170:
What is 'tearing' in the context of concurrent React rendering?
Ans:
Tearing refers to a UI inconsistency where different parts of the same render show different versions of external mutable state because React rendered concurrently while that state changed mid-render; hooks like useSyncExternalStore are designed to prevent it.
REACT.JS
#3.171
Q171:
What are React Server Components?
Ans:
React Server Components are components that render entirely on the server, never shipping their JavaScript to the client, allowing direct access to server-side resources (like a database) and reducing client bundle size; they're used alongside regular client components, notably in Next.js's App Router.
REACT.JS
#3.172
Q172:
What is the difference between a React Server Component and a Client Component?
Ans:
Server Components run only on the server and cannot use state, effects, or browser APIs, whereas Client Components (marked with 'use client') run in the browser, can use Hooks and event handlers, and are what traditional React components have always been.
REACT.JS
#3.173
Q173:
What is the significance of the 'use client' directive?
Ans:
The 'use client' directive, used in frameworks supporting React Server Components like Next.js, marks a module boundary indicating that the component and its imports should be bundled and rendered on the client rather than the server.
REACT.JS
#3.174
Q174:
What is a stale closure in React and how does it happen?
Ans:
A stale closure occurs when a function (like an effect or event handler) captures an outdated value of a state or prop variable from a previous render, often because it was defined without the current variable in its dependency array.
ANGULAR.JS
#3.175
Q175:
What is the difference between a pure pipe and an impure pipe?
Ans:
A pure pipe only re-executes when Angular detects a pure change to its input (a different object reference or primitive value), while an impure pipe (declared with pure: false) re-executes on every change detection cycle regardless of whether the input reference changed, which is more expensive but necessary for mutable data like arrays being pushed to.
ANGULAR.JS
#3.176
Q176:
What is the injector hierarchy in Angular?
Ans:
Angular maintains a tree of injectors mirroring the component tree; when a component requests a dependency, Angular looks for a provider starting at that component's own injector and walks up through ancestor injectors until it finds one, allowing different scopes (root, module, or component-level) to provide different instances.
ANGULAR.JS
#3.177
Q177:
What is the difference between @ViewChild and @ContentChild?
Ans:
@ViewChild queries elements defined in the component's own template, while @ContentChild queries elements that were projected into the component from its parent via .
ANGULAR.JS
#3.178
Q178:
What is the difference between ChangeDetectionStrategy.Default and OnPush?
Ans:
The Default strategy checks a component on every change detection cycle triggered anywhere in the app, while OnPush restricts checks to only run when an @Input reference changes, an event originates from within the component, or an Observable bound with async emits, significantly improving performance for large applications.
Code Example
@Component({
selector: 'app-item',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ItemComponent {}
ANGULAR.JS
#3.179
Q179:
What is Zone.js and what role does it play in Angular?
Ans:
Zone.js is a library that patches asynchronous browser APIs (like setTimeout, promises, and event listeners) so Angular can automatically know when to run change detection after any async operation completes, without the developer having to trigger it manually.
ANGULAR.JS
#3.180
Q180:
What are Angular Signals?
Ans:
Signals (introduced in Angular 16+ and stabilized further in later versions) are a reactive primitive that wraps a value and notifies consumers when it changes, enabling fine-grained, more predictable reactivity and eventually reducing reliance on Zone.js for change detection.
Code Example
const count = signal(0);
count.set(count() + 1);
const doubled = computed(() => count() * 2);
ANGULAR.JS
#3.181
Q181:
What is the difference between a signal and an Observable?
Ans:
A signal is a synchronous, always-has-a-current-value reactive primitive read by calling it as a function, designed for UI state and integrated directly with change detection, while an Observable models an asynchronous stream of values over time and requires explicit subscription/unsubscription.
ANGULAR.JS
#3.182
Q182:
What is a resolver in Angular routing?
Ans:
A resolver implements the Resolve interface to pre-fetch data before a route is activated, ensuring the component has the data available immediately upon initialization rather than showing an empty state while fetching.
ANGULAR.JS
#3.183
Q183:
How do you create a custom validator in Angular?
Ans:
A custom validator is a function that takes an AbstractControl and returns either null (valid) or a ValidationErrors object; it's attached to a FormControl alongside built-in validators.
Code Example
function forbiddenNameValidator(control: AbstractControl): ValidationErrors | null {
return control.value === 'admin' ? { forbiddenName: true } : null;
}
ANGULAR.JS
#3.184
Q184:
What is a FormArray used for?
Ans:
FormArray manages a dynamic, variable-length collection of FormControl, FormGroup, or nested FormArray instances, useful for forms where the user can add or remove repeated sets of fields, like a list of phone numbers.
ANGULAR.JS
#3.185
Q185:
What is Ahead-of-Time (AOT) compilation in Angular?
Ans:
AOT compilation converts Angular templates and components into efficient JavaScript during the build process (before the browser downloads the app), as opposed to Just-in-Time (JIT) compilation which does this in the browser at runtime; AOT results in faster rendering, smaller bundles, and earlier template error detection.
ANGULAR.JS
#3.186
Q186:
What is the difference between JIT and AOT compilation?
Ans:
JIT compiles the application in the browser at runtime, which is slower to start and ships the Angular compiler in the bundle, while AOT compiles during the build step on the server/CI machine, producing a smaller, faster-starting bundle that doesn't need to include the compiler; Angular CLI uses AOT by default for production builds.
ANGULAR.JS
#3.187
Q187:
What is the difference between providedIn: 'root' and listing a service in a module's providers array?
Ans:
providedIn: 'root' registers the service as a tree-shakable, application-wide singleton without needing to be listed anywhere else, while adding a service to a specific module's or component's providers array scopes a separate instance of that service to that module or component subtree.
ANGULAR.JS
#3.188
Q188:
What is the purpose of Angular's DomSanitizer?
Ans:
DomSanitizer sanitizes values (like HTML, URLs, or styles) that would otherwise be automatically escaped by Angular for security, allowing developers to explicitly mark content as safe to bypass Angular's built-in XSS protection when necessary and appropriate.
Code Example
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
ANGULAR.JS
#3.189
Q189:
What is the purpose of the ng-template directive?
Ans:
ng-template defines a template fragment that isn't rendered by default; it can be rendered conditionally or repeatedly using structural directives, ngIf/else, or programmatically via a ViewContainerRef and TemplateRef.
Code Example
<ng-template #loading><p>Loading...</p></ng-template>
<div *ngIf="data; else loading">{{ data }}</div>
ANGULAR.JS
#3.190
Q190:
What are Angular animations and how are they implemented?
Ans:
Angular's animation module lets you define state-based transitions and keyframe animations declaratively using the @angular/animations package, triggered by binding an animation trigger to a component property, without relying on external CSS animation libraries.
Code Example
trigger('fade', [
state('void', style({ opacity: 0 })),
transition(':enter', animate('300ms'))
])
ANGULAR.JS
#3.191
Q191:
What is the difference between Angular's constructor injection and inject()?
Ans:
Constructor injection declares dependencies as constructor parameters and is the traditional class-based approach, while inject() retrieves a dependency imperatively from within an injection context (like a factory function or a functional guard), useful in places where defining a class isn't convenient.
ANGULAR.JS
#3.192
Q192:
What is the purpose of Renderer2 in Angular?
Ans:
Renderer2 provides an abstraction for manipulating DOM elements (setting styles, attributes, or classes) in a platform-independent way, which is safer than directly accessing nativeElement since it works correctly across server-side rendering and web worker contexts.
ANGULAR.JS
#3.193
Q193:
What is Angular Universal used for?
Ans:
Angular Universal is Angular's server-side rendering solution, rendering the application to static HTML on the server for faster initial page loads and improved SEO, then hydrating it on the client once JavaScript loads.
SQL
#3.194
Q194:
What is the difference between a correlated and a non-correlated subquery?
Ans:
A non-correlated subquery runs independently of the outer query and executes only once, while a correlated subquery references a column from the outer query and is re-evaluated once for every row processed by the outer query, which can be significantly slower.
Code Example
SELECT e.name FROM employees e
WHERE salary > (
SELECT AVG(salary) FROM employees e2
WHERE e2.dept_id = e.dept_id
);
SQL
#3.195
Q195:
What is a recursive CTE?
Ans:
A recursive CTE references itself within its own definition, combining an anchor member (base case) with a recursive member (which joins back to the CTE) via UNION ALL, commonly used to traverse hierarchical data like org charts or category trees.
Code Example
WITH RECURSIVE org_chart AS (
SELECT id, manager_id, name FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.manager_id, e.name
FROM employees e
JOIN org_chart o ON e.manager_id = o.id
)
SELECT * FROM org_chart;
SQL
#3.196
Q196:
What are window functions in SQL?
Ans:
Window functions perform calculations across a set of rows related to the current row (defined by an OVER clause with PARTITION BY and ORDER BY) without collapsing the result into a single row per group, unlike regular aggregate functions.
Code Example
SELECT name, salary,
AVG(salary) OVER (PARTITION BY dept) AS dept_avg
FROM employees;
SQL
#3.197
Q197:
What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
Ans:
ROW_NUMBER() assigns a unique sequential number to each row regardless of ties, RANK() assigns the same rank to tied rows but skips subsequent rank numbers, and DENSE_RANK() assigns the same rank to tied rows without skipping any rank numbers.
Code Example
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;
SQL
#3.198
Q198:
What is the PARTITION BY clause used for?
Ans:
PARTITION BY, used within a window function's OVER clause, divides the result set into partitions (groups) to which the window function is applied separately, similar to GROUP BY but without collapsing rows.
Code Example
SELECT name, dept, salary,
SUM(salary) OVER (PARTITION BY dept) AS dept_total
FROM employees;
SQL
#3.199
Q199:
What is the LAG() and LEAD() window function used for?
Ans:
LAG() returns the value of a column from a previous row within the same result set/partition, and LEAD() returns the value from a following row, both commonly used for comparing a row to the row before or after it, like computing period-over-period differences.
Code Example
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month_revenue
FROM sales;
SQL
#3.200
Q200:
What is the difference between a clustered and a non-clustered index?
Ans:
A clustered index determines the physical order in which table rows are stored on disk, so a table can have only one, while a non-clustered index is a separate structure that stores pointers back to the actual rows, and a table can have multiple non-clustered indexes.
SQL
#3.201
Q201:
What is a composite index?
Ans:
A composite (or compound) index is built on two or more columns together, useful for queries that filter or sort on that same combination of columns, though the column order in the index definition matters for which query patterns it can efficiently serve.
Code Example
CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date);
SQL
#3.202
Q202:
What is a SAVEPOINT in SQL?
Ans:
A SAVEPOINT marks an intermediate point within a transaction that you can later roll back to without undoing the entire transaction, useful for partially undoing work while keeping earlier changes intact.
Code Example
SAVEPOINT before_update;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO before_update;
SQL
#3.203
Q203:
What are the different transaction isolation levels?
Ans:
The standard SQL isolation levels, from least to most strict, are READ UNCOMMITTED (allows dirty reads), READ COMMITTED (prevents dirty reads), REPEATABLE READ (prevents dirty and non-repeatable reads), and SERIALIZABLE (fully isolates transactions, preventing phantom reads too, at the cost of concurrency).
Code Example
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SQL
#3.204
Q204:
What is a dirty read?
Ans:
A dirty read occurs when a transaction reads data that has been modified by another transaction but not yet committed, meaning the read value might later be rolled back and never actually exist in the database's final state.
SQL
#3.205
Q205:
What is a deadlock in SQL and how can it be avoided?
Ans:
A deadlock occurs when two or more transactions each hold a lock the other needs and wait indefinitely for each other to release it; it can be mitigated by always acquiring locks in a consistent order, keeping transactions short, and using appropriate isolation levels or timeout settings.
SQL
#3.206
Q206:
What is a materialized view?
Ans:
A materialized view is a view whose result set is physically stored on disk and periodically refreshed, trading storage and staleness for much faster read performance compared to recomputing a complex query every time.
SQL
#3.207
Q207:
What is the difference between BEFORE and AFTER triggers?
Ans:
A BEFORE trigger fires prior to the triggering event actually being applied to the table, allowing you to validate or modify the incoming data, while an AFTER trigger fires once the event has already been applied, useful for logging or cascading updates to other tables.
SQL
#3.208
Q208:
What is the difference between ON DELETE CASCADE, SET NULL, and RESTRICT?
Ans:
CASCADE deletes child rows automatically when the referenced parent row is deleted, SET NULL sets the foreign key column in child rows to NULL instead of deleting them, and RESTRICT (or NO ACTION) prevents the parent row from being deleted at all while matching child rows still exist.
SQL
#3.209
Q209:
What is the difference between WHERE and ON in a JOIN?
Ans:
The ON clause specifies the condition used to match rows between the joined tables, evaluated as the join is performed, while the WHERE clause filters the combined result set afterward; this distinction matters especially with OUTER JOINs, where conditions in ON versus WHERE can produce different results.
Code Example
SELECT * FROM a
LEFT JOIN b ON a.id = b.a_id AND b.active = 1
WHERE a.status = 'open';
SQL
#3.210
Q210:
What is query optimization and what is the EXPLAIN statement used for?
Ans:
Query optimization involves rewriting queries or adjusting indexes/schema so the database engine can execute them more efficiently; the EXPLAIN (or EXPLAIN ANALYZE) statement shows the execution plan a database will use for a given query, revealing whether it uses indexes, full table scans, or particular join strategies.
Code Example
EXPLAIN SELECT * FROM orders WHERE customer_id = 5;
SQL
#3.211
Q211:
What is the difference between UPDATE and MERGE (UPSERT)?
Ans:
UPDATE modifies existing rows that match a condition but does nothing if no matching row exists, while MERGE (or an UPSERT pattern like INSERT ... ON CONFLICT / ON DUPLICATE KEY UPDATE) inserts a new row if no match is found or updates the existing row if one is, combining both operations in a single statement.
Code Example
INSERT INTO inventory (product_id, quantity)
VALUES (1, 10)
ON DUPLICATE KEY UPDATE quantity = quantity + 10;
SQL
#3.212
Q212:
What is database sharding?
Ans:
Sharding is a horizontal scaling technique that splits a large database into smaller, independent pieces (shards) distributed across multiple servers, typically partitioned by a key (like customer ID), so that each server handles only a subset of the total data.
SQL
#3.213
Q213:
What is the difference between a natural join and an equi join?
Ans:
A natural join automatically joins tables based on all columns that share the same name, without needing an explicit ON clause, while an equi join requires you to explicitly specify the columns to compare using an equality condition, giving more control and clarity over which columns are used.