Comprehensive guide to all major programming languages with beginner-friendly examples, use cases, and detailed explanations
Python has become the most strategic "all-rounder" language due to:
Python dominates with TensorFlow, PyTorch, and extensive data science libraries. R excels in statistical analysis and research.
JavaScript powers frontend interactivity and backend via Node.js. TypeScript adds type safety for large-scale applications.
C# powers Unity (most popular mobile game engine). C++ is used for high-performance games like PUBG Mobile.
Python is used for automation, malware analysis, and security tools. C is essential for reverse engineering and exploit development.
SQL remains the essential standard for relational databases across all industries, despite the rise of NoSQL solutions.
Kotlin is the default for Android development. Swift dominates the Apple ecosystem (iOS, macOS, watchOS).
Go has surged in 2025 for cloud-native infrastructure (Docker/Kubernetes) due to high efficiency and concurrency.
Java and C# remain the backbone of large-scale corporate systems (banking, insurance) where stability is preferred.
C++ and C are leaders for high-performance needs like game engines (Unreal Engine) and operating systems.
Python
Why: Simple syntax, vital role in AI boom, most-used on GitHub, excellent for beginners and professionals.
Best for: AI/ML, Data Science, Web Development, Automation, Cybersecurity
JavaScript
Why: Used by 66% of developers globally, powers 98% of websites, essential for modern web development.
Best for: Frontend, Backend (Node.js), Full-Stack, Web Apps
C++
Why: Critical for high-performance sectors where execution speed is essential.
Best for: Game Development, Financial Trading, System Programming, Embedded Systems
JavaScript is the programming language of the web. Created in 1995 by Brendan Eich, it has evolved from a simple scripting language to one of the most powerful and versatile programming languages today. JavaScript runs in web browsers (client-side) and can also run on servers using Node.js (server-side), making it a full-stack language.
JavaScript is interpreted, meaning code runs directly without compilation. It's dynamically typed, so you don't need to declare variable types. It supports multiple programming paradigms: object-oriented, functional, and procedural programming.
Today, JavaScript powers over 95% of all websites and is essential for modern web development. With frameworks like React, Vue, and Angular, JavaScript enables building complex, interactive user interfaces. On the server side, Node.js allows JavaScript to handle backend operations, database interactions, and API development.
// Simple Hello World
console.log("Hello, World!");
// Variables - Three ways to declare
let name = "John"; // Can be reassigned
const age = 25; // Cannot be reassigned (constant)
var city = "Boston"; // Old way (avoid in modern code)
// Different data types
let number = 42; // Number
let text = "Hello"; // String
let isActive = true; // Boolean
let nothing = null; // Null
let notDefined = undefined; // Undefined
let person = { name: "John" }; // Object
let fruits = ["apple", "banana"]; // Array
// Template literals (modern way to combine strings)
let greeting = `Hello, my name is ${name} and I'm ${age} years old`;
console.log(greeting); // "Hello, my name is John and I'm 25 years old"
// Traditional function
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function (modern, shorter)
const greetArrow = (name) => {
return `Hello, ${name}!`;
}
// Arrow function with single expression (even shorter)
const greetShort = name => `Hello, ${name}!`;
// Function with default parameters
function introduce(name = "Guest", age = 0) {
return `Hi, I'm ${name} and I'm ${age} years old`;
}
console.log(introduce()); // "Hi, I'm Guest and I'm 0 years old"
console.log(introduce("John", 25)); // "Hi, I'm John and I'm 25 years old"
// Creating arrays
const fruits = ["apple", "banana", "orange"];
// Accessing elements
console.log(fruits[0]); // "apple"
// Adding elements
fruits.push("grape"); // Add to end
fruits.unshift("mango"); // Add to beginning
// Different ways to loop
// 1. forEach (most common)
fruits.forEach(fruit => {
console.log(fruit);
});
// 2. for...of loop
for (const fruit of fruits) {
console.log(fruit);
}
// 3. Traditional for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, num) => acc + num, 0); // 15
// Creating objects
const person = {
name: "John",
age: 25,
city: "Boston",
// Method (function inside object)
greet: function() {
return `Hi, I'm ${this.name}`;
},
// Shorthand method (ES6)
introduce() {
return `I'm ${this.name}, ${this.age} years old, from ${this.city}`;
}
};
console.log(person.greet()); // "Hi, I'm John"
console.log(person.introduce()); // "I'm John, 25 years old, from Boston"
// Accessing properties
console.log(person.name); // "John"
console.log(person["age"]); // 25 (bracket notation)
// Adding new properties
person.email = "john@example.com";
person.sayHello = () => "Hello!";
// ES6 Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
getInfo() {
return `${this.name} is ${this.age} years old`;
}
}
// Creating instances
const john = new Person("John", 25);
const jane = new Person("Jane", 30);
console.log(john.greet()); // "Hello, I'm John"
console.log(jane.getInfo()); // "Jane is 30 years old"
// Inheritance
class Student extends Person {
constructor(name, age, school) {
super(name, age); // Call parent constructor
this.school = school;
}
study() {
return `${this.name} is studying at ${this.school}`;
}
}
const student = new Student("Alice", 20, "MIT");
console.log(student.greet()); // "Hello, I'm Alice" (inherited)
console.log(student.study()); // "Alice is studying at MIT"
// Selecting elements
const button = document.getElementById("myButton");
const heading = document.querySelector("h1");
const allParagraphs = document.querySelectorAll("p");
// Changing content
heading.textContent = "New Heading";
heading.innerHTML = "Bold Heading";
// Adding event listeners
button.addEventListener("click", function() {
alert("Button clicked!");
});
// Modern arrow function version
button.addEventListener("click", () => {
console.log("Button clicked!");
heading.style.color = "blue";
});
// Creating new elements
const newDiv = document.createElement("div");
newDiv.textContent = "Hello from JavaScript!";
newDiv.className = "my-class";
document.body.appendChild(newDiv);
// Modifying styles
const element = document.querySelector(".my-element");
element.style.backgroundColor = "red";
element.style.padding = "20px";
element.classList.add("active"); // Add CSS class
element.classList.remove("inactive"); // Remove CSS class
// Promises - Handling operations that take time
function fetchUserData(userId) {
return new Promise((resolve, reject) => {
// Simulate API call
setTimeout(() => {
if (userId) {
resolve({ id: userId, name: "John", email: "john@example.com" });
} else {
reject("User ID is required");
}
}, 1000);
});
}
// Using Promises with .then()
fetchUserData(1)
.then(user => {
console.log("User:", user);
return user.email;
})
.then(email => {
console.log("Email:", email);
})
.catch(error => {
console.error("Error:", error);
});
// Using async/await (modern, cleaner way)
async function getUserInfo(userId) {
try {
const user = await fetchUserData(userId);
console.log("User:", user);
return user;
} catch (error) {
console.error("Error:", error);
}
}
// Fetching data from API (real-world example)
async function fetchData() {
try {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error("Failed to fetch:", error);
}
}
// Destructuring arrays
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// Destructuring objects
const person = { name: "John", age: 25, city: "Boston" };
const { name, age } = person;
console.log(name); // "John"
console.log(age); // 25
// Renaming during destructuring
const { name: personName, age: personAge } = person;
// Spread operator - copying arrays/objects
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// Combining arrays
const combined = [...arr1, ...arr2];
// mathUtils.js (exporting)
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;
// Or export all at once
export { add, subtract, PI };
// main.js (importing)
import { add, subtract, PI } from './mathUtils.js';
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
console.log(PI); // 3.14159
// Import everything
import * as math from './mathUtils.js';
console.log(math.add(2, 3)); // 5
// Default export
// calculator.js
export default function calculate(a, b, operation) {
// calculation logic
}
// main.js
import calculate from './calculator.js';
var instead of let or const: Modern JavaScript uses let and const. Use const by default, and let only when you need to reassign.this context: In arrow functions, this behaves differently. Use regular functions when you need this to refer to the object.== instead of ===: Always use === (strict equality) to avoid type coercion bugs.map(), filter(), and spread operator to avoid unintended mutations.console.log() liberally when learning. It's your best friend for debugging. Also, use browser DevTools to set breakpoints and step through your code.
Python is one of the most beginner-friendly and versatile programming languages. Created by Guido van Rossum in 1991, Python emphasizes code readability and simplicity. Its syntax is so clear that it's often called "executable pseudocode" - meaning it reads almost like English.
Python is an interpreted language, meaning code runs line by line without compilation. It's dynamically typed (you don't declare variable types) and supports multiple programming paradigms: object-oriented, functional, and procedural.
Python's philosophy is captured in "The Zen of Python": "Beautiful is better than ugly. Simple is better than complex. Readability counts." This makes Python perfect for beginners and ideal for rapid development. It's used by major companies like Google, Instagram, Netflix, Spotify, and NASA.
Python has the largest ecosystem of libraries (packages) of any language, with over 400,000 packages available on PyPI (Python Package Index). This means you can find a library for almost anything you want to do!
# Simple Hello World
print("Hello, World!")
# Variables - No type declaration needed!
name = "John" # String
age = 25 # Integer
height = 5.9 # Float (decimal number)
is_student = True # Boolean (True/False)
nothing = None # None (like null in other languages)
# Python automatically figures out the type
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
# Type conversion
age_str = str(age) # Convert to string: "25"
age_float = float(age) # Convert to float: 25.0
# Multiple assignment
x, y, z = 1, 2, 3 # x=1, y=2, z=3
a = b = c = 0 # All equal to 0
# F-strings (modern way to format strings)
greeting = f"Hello, my name is {name} and I'm {age} years old"
print(greeting) # "Hello, my name is John and I'm 25 years old"
# Lists (like arrays, but more powerful)
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
# Accessing elements
print(fruits[0]) # "apple" (first element)
print(fruits[-1]) # "orange" (last element)
# Adding elements
fruits.append("grape") # Add to end
fruits.insert(0, "mango") # Insert at beginning
fruits.extend(["kiwi", "pear"]) # Add multiple
# List slicing
print(fruits[1:3]) # ["banana", "orange"] (elements 1 to 2)
print(fruits[:2]) # ["apple", "banana"] (first 2)
print(fruits[2:]) # ["orange", "grape"] (from index 2)
# List comprehensions (Pythonic way)
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Tuples (immutable lists)
coordinates = (10, 20)
point = (x, y) = (5, 3) # Unpacking
# Dictionaries (like objects in JavaScript)
person = {
"name": "John",
"age": 25,
"city": "Boston",
"email": "john@example.com"
}
# Accessing values
print(person["name"]) # "John"
print(person.get("age")) # 25 (safer, returns None if key doesn't exist)
# Adding/updating
person["phone"] = "123-456-7890"
person["age"] = 26
# Looping through dictionary
for key, value in person.items():
print(f"{key}: {value}")
# Functions
def greet(name):
"""This is a docstring - explains what the function does"""
return f"Hello, {name}!"
# Function with default parameters
def introduce(name, age=0, city="Unknown"):
return f"Hi, I'm {name}, {age} years old, from {city}"
print(introduce("John")) # Uses defaults for age and city
print(introduce("Jane", 30, "NYC")) # All parameters provided
# Function with multiple return values
def get_name_age():
return "John", 25 # Returns a tuple
name, age = get_name_age() # Unpacking
# Control flow - if/else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
# Loops
# For loop
for fruit in fruits:
print(fruit)
# For loop with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Loop control
for num in range(10):
if num == 3:
continue # Skip this iteration
if num == 7:
break # Exit loop
print(num)
# Classes
class Person:
# Class variable (shared by all instances)
species = "Homo sapiens"
# Constructor (called when object is created)
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
# Instance method
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old"
# Another method
def have_birthday(self):
self.age += 1
return f"Happy birthday! Now I'm {self.age} years old"
# Special method (called when printing)
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
# Creating objects
john = Person("John", 25)
jane = Person("Jane", 30)
print(john.introduce()) # "Hi, I'm John and I'm 25 years old"
print(john) # Uses __str__ method
# Inheritance
class Student(Person):
def __init__(self, name, age, school):
super().__init__(name, age) # Call parent constructor
self.school = school
def study(self):
return f"{self.name} is studying at {self.school}"
student = Student("Alice", 20, "MIT")
print(student.introduce()) # Inherited from Person
print(student.study()) # "Alice is studying at MIT"
# Reading from a file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline
# Writing to a file
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line")
# Appending to a file
with open("output.txt", "a") as file:
file.write("\nThis is appended")
# Reading JSON file
import json
with open("data.json", "r") as file:
data = json.load(file)
# Writing JSON file
data = {"name": "John", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
# NumPy - Numerical computing
import numpy as np
# Create arrays
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Array operations
print(arr * 2) # [2, 4, 6, 8, 10]
print(arr + 10) # [11, 12, 13, 14, 15]
print(np.sum(arr)) # 15
# Pandas - Data analysis
import pandas as pd
# Create DataFrame (like Excel spreadsheet)
data = {
"name": ["John", "Jane", "Bob"],
"age": [25, 30, 35],
"city": ["Boston", "NYC", "LA"]
}
df = pd.DataFrame(data)
# View data
print(df.head()) # First 5 rows
print(df.describe()) # Statistics
# Filtering
young_people = df[df["age"] < 30]
print(young_people)
# Reading CSV
df = pd.read_csv("data.csv")
df.to_csv("output.csv", index=False)
import requests
from bs4 import BeautifulSoup
# Fetch webpage
url = "https://example.com"
response = requests.get(url)
html = response.text
# Parse HTML
soup = BeautifulSoup(html, "html.parser")
# Find elements
title = soup.find("title").text
all_links = soup.find_all("a")
# Extract data
for link in all_links:
print(link.get("href"))
print(link.text)
import requests
# GET request
response = requests.get("https://api.example.com/users")
data = response.json()
# POST request
new_user = {"name": "John", "email": "john@example.com"}
response = requests.post("https://api.example.com/users", json=new_user)
# With error handling
try:
response = requests.get("https://api.example.com/data", timeout=5)
response.raise_for_status() # Raises exception for bad status codes
data = response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# Basic error handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f"Result: {result}") # Runs if no error
finally:
print("This always runs") # Always executes
# Raising custom exceptions
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age < 18:
raise ValueError("Must be 18 or older!")
return True
== instead of =: Use = for assignment, == for comparison.venv or conda to isolate project dependencies.pip install package_name before importing.print() statements liberally when debugging. Python's error messages are very helpful - read them carefully! Also, use type() and dir() to explore objects.
Java is a powerful, object-oriented programming language used for building large-scale enterprise applications, Android mobile apps, and server-side systems. It's known for "write once, run anywhere" - code runs on any device with Java installed.
// Simple Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// Variables
String name = "John";
int age = 25;
double height = 5.9;
// Methods
public static String greet(String name) {
return "Hello, " + name + "!";
}
// Arrays
String[] fruits = {"apple", "banana", "orange"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// Classes
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println("Hi, I'm " + name +
" and I'm " + age + " years old");
}
}
Person john = new Person("John", 25);
john.introduce();
C++ is a powerful, high-performance programming language used for system programming, game development, and applications requiring direct hardware control. It's an extension of C with object-oriented features.
// Simple Hello World
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
// Variables
string name = "John";
int age = 25;
double height = 5.9;
// Functions
string greet(string name) {
return "Hello, " + name + "!";
}
// Arrays
string fruits[] = {"apple", "banana", "orange"};
for (int i = 0; i < 3; i++) {
cout << fruits[i] << endl;
}
// Classes
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
void introduce() {
cout << "Hi, I'm " << name <<
" and I'm " << age << " years old" << endl;
}
};
Person john("John", 25);
john.introduce();
C# (pronounced "C sharp") is Microsoft's object-oriented programming language. It's used for Windows applications, web development with ASP.NET, game development with Unity, and cross-platform applications.
// Simple Hello World
using System;
class Program {
static void Main() {
Console.WriteLine("Hello, World!");
}
}
// Variables
string name = "John";
int age = 25;
double height = 5.9;
// Methods
static string Greet(string name) {
return $"Hello, {name}!";
}
// Arrays
string[] fruits = {"apple", "banana", "orange"};
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
// Classes
class Person {
private string name;
private int age;
public Person(string name, int age) {
this.name = name;
this.age = age;
}
public void Introduce() {
Console.WriteLine($"Hi, I'm {name} and I'm {age} years old");
}
}
Person john = new Person("John", 25);
john.Introduce();
TypeScript is JavaScript with type checking. It adds static types to JavaScript, making code more reliable and easier to maintain. TypeScript compiles to JavaScript, so it works everywhere JavaScript works.
// Simple Hello World
console.log("Hello, World!");
// Type annotations
let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
// Functions with types
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Interfaces
interface Person {
name: string;
age: number;
email?: string; // Optional property
}
// Using interfaces
function introduce(person: Person): void {
console.log(`Hi, I'm ${person.name} and I'm ${person.age} years old`);
}
const john: Person = {
name: "John",
age: 25,
email: "john@example.com"
};
introduce(john);
// Classes with types
class Employee {
private name: string;
private salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
getInfo(): string {
return `${this.name} earns $${this.salary}`;
}
}
PHP is a server-side scripting language designed for web development. It powers millions of websites including WordPress, Facebook (originally), and many content management systems.
<?php
// Simple Hello World
echo "Hello, World!";
// Variables
$name = "John";
$age = 25;
$height = 5.9;
// Functions
function greet($name) {
return "Hello, " . $name . "!";
}
// Arrays
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Associative Arrays
$person = array(
"name" => "John",
"age" => 25,
"city" => "Boston"
);
// Classes
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
return "Hi, I'm " . $this->name .
" and I'm " . $this->age . " years old";
}
}
$john = new Person("John", 25);
echo $john->introduce();
?>
Ruby is known for its elegant, readable syntax that prioritizes developer happiness. It's the language behind Ruby on Rails, a popular web framework. Ruby is great for rapid prototyping and web development.
# Simple Hello World
puts "Hello, World!"
# Variables
name = "John"
age = 25
height = 5.9
# Methods
def greet(name)
"Hello, #{name}!"
end
# Arrays
fruits = ["apple", "banana", "orange"]
fruits.each do |fruit|
puts fruit
end
# Hashes (like dictionaries)
person = {
name: "John",
age: 25,
city: "Boston"
}
# Classes
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
"Hi, I'm #{@name} and I'm #{@age} years old"
end
end
john = Person.new("John", 25)
puts john.introduce
Go (also called Golang) is Google's programming language designed for simplicity, efficiency, and concurrent programming. It's great for building scalable web services, microservices, and cloud-native applications.
package main
import "fmt"
// Simple Hello World
func main() {
fmt.Println("Hello, World!")
}
// Variables
var name string = "John"
age := 25 // Short variable declaration
height := 5.9
// Functions
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
// Arrays and Slices
fruits := []string{"apple", "banana", "orange"}
for _, fruit := range fruits {
fmt.Println(fruit)
}
// Structs
type Person struct {
Name string
Age int
}
// Methods
func (p Person) Introduce() string {
return fmt.Sprintf("Hi, I'm %s and I'm %d years old",
p.Name, p.Age)
}
john := Person{Name: "John", Age: 25}
fmt.Println(john.Introduce())
// Goroutines (concurrency)
go func() {
fmt.Println("Running in a goroutine")
}()
Rust is a systems programming language focused on safety, speed, and concurrency. It prevents common programming errors like memory leaks and data races at compile time, without sacrificing performance.
// Simple Hello World
fn main() {
println!("Hello, World!");
}
// Variables (immutable by default)
let name = "John";
let age = 25;
let mut counter = 0; // mutable variable
// Functions
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
// Vectors (dynamic arrays)
let fruits = vec!["apple", "banana", "orange"];
for fruit in fruits.iter() {
println!("{}", fruit);
}
// Structs
struct Person {
name: String,
age: u32,
}
// Implementation
impl Person {
fn new(name: String, age: u32) -> Person {
Person { name, age }
}
fn introduce(&self) -> String {
format!("Hi, I'm {} and I'm {} years old",
self.name, self.age)
}
}
let john = Person::new("John".to_string(), 25);
println!("{}", john.introduce());
// Ownership example
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // Error! s1 is no longer valid
Swift is Apple's modern programming language for iOS, macOS, watchOS, and tvOS development. It's designed to be safe, fast, and expressive, replacing Objective-C as the primary language for Apple platforms.
// Simple Hello World
print("Hello, World!")
// Variables
var name = "John" // mutable
let age = 25 // immutable (constant)
let height = 5.9
// Functions
func greet(name: String) -> String {
return "Hello, \(name)!"
}
// Arrays
let fruits = ["apple", "banana", "orange"]
for fruit in fruits {
print(fruit)
}
// Dictionaries
var person: [String: Any] = [
"name": "John",
"age": 25,
"city": "Boston"
]
// Classes
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func introduce() -> String {
return "Hi, I'm \(name) and I'm \(age) years old"
}
}
let john = Person(name: "John", age: 25)
print(john.introduce())
// Optionals (Swift's safety feature)
var optionalName: String? = "John"
if let name = optionalName {
print("Name is \(name)")
}
Kotlin is Google's preferred language for Android development. It's concise, safe, and fully interoperable with Java. Kotlin reduces boilerplate code and makes Android development more enjoyable.
// Simple Hello World
fun main() {
println("Hello, World!")
}
// Variables
var name = "John" // mutable
val age = 25 // immutable (read-only)
val height = 5.9
// Functions
fun greet(name: String): String {
return "Hello, $name!"
}
// Single-expression function
fun add(a: Int, b: Int) = a + b
// Lists
val fruits = listOf("apple", "banana", "orange")
fruits.forEach { fruit ->
println(fruit)
}
// Data classes (like structs)
data class Person(
val name: String,
val age: Int
) {
fun introduce(): String {
return "Hi, I'm $name and I'm $age years old"
}
}
val john = Person("John", 25)
println(john.introduce())
// Null safety
var name: String? = "John" // nullable
val length = name?.length // safe call
val safeLength = name?.length ?: 0 // Elvis operator
SQL (Structured Query Language) is the standard language for managing and querying relational databases. It's essential for working with data, whether you're a developer, data analyst, or database administrator.
-- Create a table
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert data
INSERT INTO users (name, email, age)
VALUES ('John', 'john@example.com', 25);
-- Select data
SELECT * FROM users;
SELECT name, email FROM users WHERE age > 20;
-- Update data
UPDATE users
SET age = 26
WHERE name = 'John';
-- Delete data
DELETE FROM users WHERE id = 1;
-- Join tables
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id;
-- Aggregate functions
SELECT
COUNT(*) as total_users,
AVG(age) as average_age,
MAX(age) as max_age
FROM users;
-- Group by
SELECT age, COUNT(*) as count
FROM users
GROUP BY age
HAVING COUNT(*) > 1;
HTML (HyperText Markup Language) structures web content, while CSS (Cascading Style Sheets) styles it. Together, they form the foundation of every website. Every web developer must know these.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background: #f4f4f4;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
.button {
background: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<h1>Hello, World!</h1>
<p>This is my first web page.</p>
<button class="button">Click Me</button>
</div>
</body>
</html>
Bash (Bourne Again Shell) is a command-line shell and scripting language for Unix/Linux systems. It's essential for automation, DevOps, system administration, and working with servers.
#!/bin/bash
# Simple Hello World
echo "Hello, World!"
# Variables
name="John"
age=25
echo "Name: $name, Age: $age"
# User input
read -p "Enter your name: " username
echo "Hello, $username!"
# Conditional statements
if [ $age -gt 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
# Loops
for i in {1..5}; do
echo "Number: $i"
done
# Functions
greet() {
local name=$1
echo "Hello, $name!"
}
greet "John"
# File operations
if [ -f "file.txt" ]; then
echo "File exists"
cat file.txt
else
echo "File does not exist"
fi
# Command substitution
current_date=$(date)
echo "Current date: $current_date"
There are many other important programming languages used in specific domains and industries. Here are some notable ones: