Multi-Language Code Repository

⚡ Subject-Specific Code Examples

Each technology features compilable, native syntax examples that can be copied or run directly on the online IDE.

← Back to Platform
SAP CPI Java Python C Language PHP C++ C# Groovy SAP ABAP SAP PI/PO
Technology 1

📚 SAP CPI (Native Syntax)

15 Real Programs

#1 Read and Log Message Body

Extracts payload and appends attachment to message log.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    def body = message.getBody(java.lang.String) as String;
    def messageLog = messageLogFactory.getMessageLog(message);
    if(messageLog != null) {
        messageLog.addAttachmentAsString("Log", body, "text/plain");
    }
    return message;
}

#2 Capture Exception Caught

Catches camel routing errors and logs stack traces.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    def ex = message.getProperty("CamelExceptionCaught");
    if (ex != null) {
        message.setProperty("ErrorSummary", ex.getMessage());
    }
    return message;
}

#3 Set Custom Tracking Header

Injects dynamic correlation headers into exchange.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    message.setHeader("X-Correlation-ID", java.util.UUID.randomUUID().toString());
    return message;
}

#4 Read and Set Exchange Properties

Stores routing status in pipeline exchange properties.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    def amount = message.getProperty("OrderAmount") ?: "0";
    message.setProperty("IsHighPriority", (amount.toInteger() > 5000).toString());
    return message;
}

#5 JSON Payload Transformation (JsonSlurper)

Parses incoming JSON and injects verified timestamp.

import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.json.JsonSlurper;
import groovy.json.JsonBuilder;
def Message processData(Message message) {
    def json = new JsonSlurper().parseText(message.getBody(String));
    json.processedAt = new Date().format("yyyy-MM-dd HH:mm:ss");
    message.setBody(new JsonBuilder(json).toString());
    return message;
}

#6 XML Slurper Element Extraction

Extracts specific node values from XML payloads.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    def root = new XmlSlurper().parseText(message.getBody(String));
    message.setProperty("OrderID", root.Header.OrderID.text());
    return message;
}

#7 Remove XML Namespaces

Cleans prefix namespaces from XML strings.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    String clean = message.getBody(String).replaceAll("xmlns.*?(\"|\\').*?(\"|\\')", "");
    message.setBody(clean);
    return message;
}

#8 Date Arithmetic in CPI

Computes future due dates using TimeCategory.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    use(groovy.time.TimeCategory) {
        message.setProperty("DueDate", (new Date() + 30.days).format("yyyy-MM-dd"));
    }
    return message;
}

#9 Throw Validation Exception

Halts iFlow processing if required fields are missing.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    if (!message.getBody(String)) {
        throw new Exception("Payload cannot be empty");
    }
    return message;
}

#10 Base64 Encode Payload

Encodes message payload into Base64 format.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    String enc = message.getBody(String).bytes.encodeBase64().toString();
    message.setBody(enc);
    return message;
}

#11 Base64 Decode Payload

Decodes incoming Base64 payload into plain text.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    byte[] dec = message.getBody(String).decodeBase64();
    message.setBody(new String(dec));
    return message;
}

#12 Format CSV to JSON

Converts comma-separated rows into JSON array.

import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.json.JsonBuilder;
def Message processData(Message message) {
    def lines = message.getBody(String).readLines();
    def headers = lines[0].split(",");
    def data = lines[1..-1].collect { line ->
        def vals = line.split(",");
        [headers, vals].transpose().collectEntries();
    };
    message.setBody(new JsonBuilder(data).toString());
    return message;
}

#13 Sleep / Rate Limiter

Pauses pipeline execution thread safely.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    sleep(1000);
    return message;
}

#14 Check Header with Elvis Operator

Provides safe defaults when headers are missing.

import com.sap.gateway.ip.core.customdev.util.Message;
def Message processData(Message message) {
    def sender = message.getHeader("SenderSystem") ?: "DEFAULT_ERP";
    message.setProperty("ResolvedSender", sender);
    return message;
}

#15 IgnoreMessageException Termination

Gracefully terminates iFlow branch execution.

import com.sap.gateway.ip.core.customdev.util.Message;
import com.sap.it.api.exception.IgnoreMessageException;
def Message processData(Message message) {
    if (message.getProperty("Skip") == "true") {
        throw new IgnoreMessageException();
    }
    return message;
}
Technology 2

📚 Java (Native Syntax)

15 Real Programs

#1 Hello World and Console Output

Standard entry point and output stream.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

#2 Find Maximum Element in Array

Iterates through an array to determine highest value.

public class Main {
    public static void main(String[] args) {
        int[] numbers = {14, 82, 3, 99, 45};
        int max = numbers[0];
        for (int num : numbers) {
            if (num > max) max = num;
        }
        System.out.println("Maximum: " + max);
    }
}

#3 String Palindrome Check

Checks if a string reads identically in reverse.

public class Main {
    public static void main(String[] args) {
        String str = "radar";
        String rev = new StringBuilder(str).reverse().toString();
        System.out.println(str + " is palindrome: " + str.equalsIgnoreCase(rev));
    }
}

#4 Fibonacci Series Generator

Computes the first N numbers in the Fibonacci sequence.

public class Main {
    public static void main(String[] args) {
        int n = 8, a = 0, b = 1;
        System.out.print("Fibonacci: ");
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
    }
}

#5 ArrayList and Collection Operations

Iterates and manages elements with ArrayList.

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java"); list.add("Python"); list.add("C++");
        list.forEach(item -> System.out.println("Course: " + item));
    }
}

#6 HashMap Key-Value Lookups

Associative dictionary mappings in Java.

import java.util.HashMap;
public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("A", 100); map.put("B", 200);
        System.out.println("Value of A: " + map.get("A"));
    }
}

#7 Streams API Filter and Map

Filters and transforms lists using Java Streams.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
        List<Integer> squares = nums.stream()
            .filter(n -> n % 2 == 0)
            .map(n -> n * n)
            .collect(Collectors.toList());
        System.out.println("Even Squares: " + squares);
    }
}

#8 Object-Oriented Encapsulation

Demonstrates classes and getters/setters.

class Employee {
    private String name;
    public Employee(String name) { this.name = name; }
    public String getName() { return this.name; }
}
public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee("Alice");
        System.out.println("Employee: " + emp.getName());
    }
}

#9 Interface Polymorphism

Implements interface contracts across classes.

interface Shape { double area(); }
class Circle implements Shape {
    double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}
public class Main {
    public static void main(String[] args) {
        Shape s = new Circle(5.0);
        System.out.println("Circle Area: " + s.area());
    }
}

#10 Try-Catch-Finally Handling

Catches arithmetic exceptions safely.

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error Caught: Division by zero");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

#11 Regex Pattern Matcher

Validates alphanumeric strings via regex.

import java.util.regex.Pattern;
public class Main {
    public static void main(String[] args) {
        String pattern = "^[A-Z0-9]+$";
        boolean valid = Pattern.matches(pattern, "CODE123");
        System.out.println("Is Alphanumeric: " + valid);
    }
}

#12 Base64 Encoding/Decoding

Encodes and decodes standard string bytes.

import java.util.Base64;
public class Main {
    public static void main(String[] args) {
        String original = "SecureCredentials";
        String encoded = Base64.getEncoder().encodeToString(original.getBytes());
        String decoded = new String(Base64.getDecoder().decode(encoded));
        System.out.println("Encoded: " + encoded + " | Decoded: " + decoded);
    }
}

#13 Multi-Threading with Runnable

Launches background concurrent threads.

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> System.out.println("Worker thread executing"));
        t.start();
        System.out.println("Main thread executing");
    }
}

#14 Generic Method Implementation

Executes generic type-safe methods.

public class Main {
    public static <T> void printElement(T elem) {
        System.out.println("Element: " + elem);
    }
    public static void main(String[] args) {
        printElement("Hello");
        printElement(42);
    }
}

#15 LocalDate Date Manipulation

Calculates date offsets with Java 8+ time API.

import java.time.LocalDate;
public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plusDays(7);
        System.out.println("Today: " + today + " | Next Week: " + nextWeek);
    }
}
Technology 3

📚 Python (Native Syntax)

15 Real Programs

#1 Hello World and F-Strings

Formats and prints string variables.

name = "Python"
print(f"Hello from {name} 3!")

#2 List Comprehensions

Filters and computes values in a single expression.

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens_squared = [x**2 for x in numbers if x % 2 == 0]
print("Even Squares:", evens_squared)

#3 Dictionary Operations

Queries and updates key-value dictionaries.

user = {"id": 101, "name": "User", "role": "Admin"}
user["status"] = "Active"
for key, val in user.items():
    print(f"{key}: {val}")

#4 Reverse a String

Reverses string slices with step notation.

text = "CodexCareerPrep"
print("Reversed:", text[::-1])

#5 Lambda Functions & Filter

Transforms collections with anonymous functions.

nums = [5, 12, 17, 18, 24, 32]
filtered = list(filter(lambda x: x > 15, nums))
print("Greater than 15:", filtered)

#6 Context Manager Simulation

Demonstrates with-statement resource closing.

import io
stream = io.StringIO("First Line\nSecond Line")
with stream as f:
    for line in f:
        print("Read:", line.strip())

#7 Functions with *args & **kwargs

Handles arbitrary arguments and keywords.

def summarize(*args, **kwargs):
    print("Sum:", sum(args))
    print("Keywords:", kwargs)
summarize(10, 20, 30, platform="Python")

#8 OOP Class & Inheritance

Implements inheritance and super() calls.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand
    def drive(self):
        return f"{self.brand} is moving"

class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand)
        self.doors = doors

c = Car("Mahindra", 5)
print(c.drive(), "with", c.doors, "doors")

#9 Try-Except-Finally

Catches division by zero exceptions.

try:
    res = 100 / 0
except ZeroDivisionError as err:
    print("Caught error:", err)
finally:
    print("Execution complete.")

#10 JSON Encoding & Parsing

Serializes and parses JSON records.

import json
data = {"course": "Python", "pages": 10}
json_str = json.dumps(data)
parsed = json.loads(json_str)
print("Parsed Course:", parsed["course"])

#11 Generators with Yield

Yields values lazily.

def countdown(n):
    while n > 0:
        yield n
        n -= 1
print(list(countdown(5)))

#12 Set Operations

Calculates intersection and union.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Intersection:", a & b)
print("Union:", a | b)

#13 Regular Expressions (re)

Extracts matching email strings.

import re
text = "Contact support at support@codexcareerprep.shop"
match = re.search(r'[\w\.-]+@[\w\.-]+', text)
if match:
    print("Found:", match.group(0))

#14 Function Decorators

Wraps and inspects functions.

def logger(func):
    def wrapper(*args):
        print(f"Calling {func.__name__}")
        return func(*args)
    return wrapper

@logger
def multiply(a, b): return a * b
print("Result:", multiply(6, 7))

#15 Datetime Operations

Calculates calendar offsets.

from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=14)
print("Future Date:", future.strftime("%Y-%m-%d"))
Technology 4

📚 C Language (Native Syntax)

15 Real Programs

#1 Hello World in C

Standard C output stream.

#include <stdio.h>
int main() {
    printf("Hello, World from C!\n");
    return 0;
}

#2 Pointers and Addresses

Inspects pointers and dereferenced values.

#include <stdio.h>
int main() {
    int val = 42;
    int *ptr = &val;
    printf("Value: %d | Address: %p\n", *ptr, ptr);
    return 0;
}

#3 Dynamic Memory Allocation

Allocates and frees memory with malloc/free.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr = (int*)malloc(3 * sizeof(int));
    if (!arr) return 1;
    arr[0] = 10; arr[1] = 20; arr[2] = 30;
    for(int i = 0; i < 3; i++) printf("%d ", arr[i]);
    printf("\n");
    free(arr);
    return 0;
}

#4 String Length Counter

Loops until reaching null terminator.

#include <stdio.h>
int main() {
    char str[] = "CodexCareerPrep";
    int len = 0;
    while(str[len] != '\0') len++;
    printf("Length: %d\n", len);
    return 0;
}

#5 Structures in C

Defines and initializes struct variables.

#include <stdio.h>
struct Student {
    int id;
    char name[30];
};
int main() {
    struct Student s1 = {101, "Student"};
    printf("ID: %d | Name: %s\n", s1.id, s1.name);
    return 0;
}

#6 Bubble Sort Algorithm

Sorts an array in ascending order.

#include <stdio.h>
int main() {
    int a[] = {5, 2, 8, 1, 3};
    int n = 5;
    for(int i = 0; i < n-1; i++) {
        for(int j = 0; j < n-i-1; j++) {
            if(a[j] > a[j+1]) {
                int t = a[j]; a[j] = a[j+1]; a[j+1] = t;
            }
        }
    }
    for(int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

#7 Bitwise Flags

Checks active binary bit flags.

#include <stdio.h>
int main() {
    int flags = 0x01 | 0x04;
    printf("Is Bit 2 Set: %s\n", (flags & 0x04) ? "YES" : "NO");
    return 0;
}

#8 Pass-by-Reference Swapping

Swaps integers using pointer memory addresses.

#include <stdio.h>
void swap(int *x, int *y) {
    int t = *x; *x = *y; *y = t;
}
int main() {
    int a = 5, b = 10;
    swap(&a, &b);
    printf("a=%d, b=%d\n", a, b);
    return 0;
}

#9 Recursion (Factorial)

Computes factorials recursively.

#include <stdio.h>
long factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}
int main() {
    printf("5! = %ld\n", factorial(5));
    return 0;
}

#10 String Buffer Formatting (sprintf)

Constructs formatted char buffers.

#include <stdio.h>
int main() {
    char buffer[50];
    sprintf(buffer, "STATUS:%d:OK", 200);
    printf("%s\n", buffer);
    return 0;
}

#11 Enumeration (enum)

Uses named integer constants.

#include <stdio.h>
enum Level { LOW = 1, MEDIUM, HIGH };
int main() {
    enum Level l = HIGH;
    printf("Level: %d\n", l);
    return 0;
}

#12 Linear Search

Finds target element index in array.

#include <stdio.h>
int main() {
    int arr[] = {10, 25, 30, 45, 50};
    int target = 30, found = -1;
    for(int i = 0; i < 5; i++) {
        if(arr[i] == target) { found = i; break; }
    }
    printf("Found at index: %d\n", found);
    return 0;
}

#13 2D Matrix Iteration

Traverses two-dimensional arrays.

#include <stdio.h>
int main() {
    int matrix[2][2] = {{1, 2}, {3, 4}};
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) printf("%d ", matrix[i][j]);
        printf("\n");
    }
    return 0;
}

#14 Function Pointers

Calls functions dynamically via pointer.

#include <stdio.h>
int add(int a, int b) { return a + b; }
int main() {
    int (*op)(int, int) = add;
    printf("Result: %d\n", op(12, 8));
    return 0;
}

#15 ASCII Manipulation

Transforms lowercase character to uppercase.

#include <stdio.h>
int main() {
    char c = 'a';
    printf("Upper: %c\n", c - ('a' - 'A'));
    return 0;
}
Technology 5

📚 PHP (Native Syntax)

15 Real Programs

#1 Hello World and Variables

Basic PHP output syntax.

<?php
$platform = "CodexCareerPrep";
echo "Welcome to " . $platform . "\n";
?>

#2 Associative Arrays & JSON Encoding

Encodes PHP arrays into JSON.

<?php
$record = array(
    "status" => "success",
    "code" => 200,
    "data" => array("course" => "PHP", "modules" => 10)
);
echo json_encode($record, JSON_PRETTY_PRINT);
?>

#3 Array Filter and Array Map

Filters and transforms arrays.

<?php
$nums = array(1, 2, 3, 4, 5, 6);
$evens = array_filter($nums, function($n) { return $n % 2 === 0; });
$doubled = array_map(function($n) { return $n * 2; }, $evens);
print_r(array_values($doubled));
?>

#4 String Explode & Implode

Splits and joins delimited text.

<?php
$csv = "SAP,Java,Python,PHP";
$arr = explode(",", $csv);
$joined = implode(" | ", $arr);
echo $joined . "\n";
?>

#5 Class Definition & Methods

Defines object properties and methods.

<?php
class Course {
    public $title;
    public $pages;
    public function __construct($title, $pages) {
        $this->title = $title;
        $this->pages = $pages;
    }
    public function getSummary() {
        return $this->title . " (" . $this->pages . " Pages)";
    }
}
$c = new Course("PHP Masterclass", 10);
echo $c->getSummary();
?>

#6 Try-Catch Exception Handling

Catches runtime exceptions in PHP.

<?php
try {
    throw new Exception("Database connection error.");
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} finally {
    echo "Finished execution.\n";
}
?>

#7 Password Hashing & Verification

Hashes and verifies password strings.

<?php
$password = "SecurePass@123";
$hash = password_hash($password, PASSWORD_BCRYPT);
$matches = password_verify("SecurePass@123", $hash);
echo "Password Matches: " . ($matches ? "YES" : "NO");
?>

#8 Null Coalescing Operator (??)

Assigns fallbacks for missing keys.

<?php
$config = array("theme" => "dark");
$font = isset($config["font"]) ? $config["font"] : "Inter";
echo "Font: " . $font;
?>

#9 Regex Pattern Matching (preg_match)

Validates string formats.

<?php
$email = "support@codexcareerprep.shop";
if (preg_match('/^[\w\.-]+@[\w\.-]+$/', $email)) {
    echo "Valid Email Address";
}
?>

#10 Date and Timezone Formatting

Manipulates DateTime objects.

<?php
$dt = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
echo "Current Time: " . $dt->format("Y-m-d H:i:s T");
?>

#11 Array Summation with array_reduce

Computes totals using array_reduce.

<?php
$prices = array(10.5, 20.0, 5.5);
$total = array_reduce($prices, function($carry, $item) { return $carry + $item; }, 0);
echo "Total: " . $total;
?>

#12 Conditional Classification

Evaluates status codes.

<?php
$status = 200;
$msg = ($status === 200) ? "OK" : "Error";
echo "Status: " . $msg;
?>

#13 Multi-Dimensional Array Search

Filters structured associative arrays.

<?php
$users = array(
    array('id' => 1, 'name' => 'Alice'),
    array('id' => 2, 'name' => 'Bob')
);
$found = array_filter($users, function($u) { return $u['id'] === 2; });
print_r(array_values($found));
?>

#14 String Replacement (str_replace)

Substitutes text in string templates.

<?php
$template = "Hello, {NAME}! Welcome to {PLATFORM}.";
$output = str_replace(array('{NAME}', '{PLATFORM}'), array('Learner', 'CodexCareerPrep'), $template);
echo $output;
?>

#15 Directory Traversal

Inspects base directories.

<?php
$path = __DIR__;
echo "Directory: " . basename($path);
?>
Technology 6

📚 C++ (Native Syntax)

15 Real Programs

#1 Hello World and Console Output

Standard C++ stream entry point.

#include <iostream>
using namespace std;
int main() {
    cout << "Hello, World from C++!" << endl;
    return 0;
}

#2 Vector Sorting

Sorts elements in a standard vector.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    vector<int> nums = {42, 12, 89, 5, 23};
    sort(nums.begin(), nums.end());
    for(int n : nums) cout << n << " ";
    return 0;
}

#3 Class and Object Encapsulation

Defines constructors, getters, and setters.

#include <iostream>
#include <string>
using namespace std;
class Rectangle {
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    int area() { return width * height; }
};
int main() {
    Rectangle rect(10, 5);
    cout << "Area: " << rect.area() << endl;
    return 0;
}

#4 Pointer Arithmetic

Traverses arrays using memory pointers.

#include <iostream>
using namespace std;
int main() {
    int arr[] = {10, 20, 30, 40};
    int *ptr = arr;
    for(int i = 0; i < 4; i++) {
        cout << "Element " << i << ": " << *(ptr + i) << endl;
    }
    return 0;
}

#5 Templates (Generic Programming)

Creates type-safe generic functions.

#include <iostream>
using namespace std;
template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}
int main() {
    cout << "Max int: " << getMax(15, 25) << endl;
    cout << "Max double: " << getMax(5.5, 2.1) << endl;
    return 0;
}

#6 Exception Handling

Catches runtime logic errors safely.

#include <iostream>
using namespace std;
int main() {
    try {
        int numerator = 10, denominator = 0;
        if (denominator == 0) throw "Division by zero error!";
        int res = numerator / denominator;
    } catch (const char* msg) {
        cerr << "Caught exception: " << msg << endl;
    }
    return 0;
}

#7 Standard Template Library (Map)

Manages key-value dictionaries.

#include <iostream>
#include <map>
using namespace std;
int main() {
    map<string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"] = 82;
    cout << "Alice Score: " << scores["Alice"] << endl;
    return 0;
}

#8 Dynamic Memory Allocation

Allocates and releases heap memory.

#include <iostream>
using namespace std;
int main() {
    int *val = new int(100);
    cout << "Heap Value: " << *val << endl;
    delete val;
    return 0;
}

#9 Lambda Expressions

Anonymous inline function definitions.

#include <iostream>
using namespace std;
int main() {
    auto add = [](int a, int b) { return a + b; };
    cout << "Sum: " << add(12, 18) << endl;
    return 0;
}

#10 Smart Pointers (unique_ptr)

Manages safe automatic memory disposal.

#include <iostream>
#include <memory>
using namespace std;
class Resource {
public:
    void show() { cout << "Resource active" << endl; }
};
int main() {
    unique_ptr<Resource> res = make_unique<Resource>();
    res->show();
    return 0;
}

#11 Operator Overloading

Customizes operator behaviors for classes.

#include <iostream>
using namespace std;
struct Point {
    int x, y;
    Point operator + (const Point& p) {
        return {x + p.x, y + p.y};
    }
};
int main() {
    Point p1 = {1, 2}, p2 = {3, 4};
    Point p3 = p1 + p2;
    cout << "Result: " << p3.x << ", " << p3.y << endl;
    return 0;
}

#12 Inheritance and Polymorphism

Demonstrates virtual runtime functions.

#include <iostream>
using namespace std;
class Base {
public:
    virtual void print() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
    void print() override { cout << "Derived class" << endl; }
};
int main() {
    Base *b = new Derived();
    b->print();
    delete b;
    return 0;
}

#13 String Reversal

Reverses strings using algorithms.

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string text = "Codex";
    reverse(text.begin(), text.end());
    cout << "Reversed: " << text << endl;
    return 0;
}

#14 Recursive Fibonacci Sequence

Computes Fibonacci numbers recursively.

#include <iostream>
using namespace std;
int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}
int main() {
    cout << "Fibonacci(6): " << fib(6) << endl;
    return 0;
}

#15 File Stream Output

Writes text content to external files.

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outFile("output.txt");
    outFile << "Writing text from C++ program.";
    outFile.close();
    cout << "File written successfully." << endl;
    return 0;
}
Technology 7

📚 C# (Native Syntax)

15 Real Programs

#1 Hello World and Console

Standard entry point in C#.

using System;
class Program {
    static void Main() {
        Console.WriteLine("Hello, World from C#!");
    }
}

#2 LINQ Query Syntax

Queries collections declaratively.

using System;
using System.Linq;
using System.Collections.Generic;
class Program {
    static void Main() {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
        var evens = from n in numbers where n % 2 == 0 select n;
        Console.WriteLine(string.Join(", ", evens));
    }
}

#3 Async / Await Task Execution

Executes asynchronous background methods.

using System;
using System.Threading.Tasks;
class Program {
    static async Task Main() {
        string result = await FetchDataAsync();
        Console.WriteLine(result);
    }
    static async Task<string> FetchDataAsync() {
        await Task.Delay(100);
        return "Data retrieved asynchronously.";
    }
}

#4 Properties and Encapsulation

Implements auto-implemented properties.

using System;
class Employee {
    public string Name { get; set; }
    public decimal Salary { get; set; }
}
class Program {
    static void Main() {
        Employee emp = new Employee { Name = "Alice", Salary = 75000M };
        Console.WriteLine($"{emp.Name} earns {emp.Salary}");
    }
}

#5 Generic Lists and Dictionary

Manages key-value stores cleanly.

using System;
using System.Collections.Generic;
class Program {
    static void Main() {
        Dictionary<string, string> config = new Dictionary<string, string>();
        config["Env"] = "Production";
        config["Region"] = "AP-South";
        Console.WriteLine("Environment: " + config["Env"]);
    }
}

#6 Exception Handling (Try-Catch)

Catches application exceptions safely.

using System;
class Program {
    static void Main() {
        try {
            int val = int.Parse("invalid_number");
        } catch (FormatException e) {
            Console.WriteLine("Caught format error: " + e.Message);
        }
    }
}

#7 Extension Methods

Extends existing built-in type capabilities.

using System;
public static class StringExtensions {
    public static bool IsNullOrEmptyCustom(this string str) {
        return string.IsNullOrEmpty(str);
    }
}
class Program {
    static void Main() {
        string text = "Test";
        Console.WriteLine(text.IsNullOrEmptyCustom());
    }
}

#8 Interface Implementation

Enforces structured class contracts.

using System;
interface ILogger {
    void Log(string message);
}
class ConsoleLogger : ILogger {
    public void Log(string message) => Console.WriteLine("[LOG]: " + message);
}
class Program {
    static void Main() {
        ILogger logger = new ConsoleLogger();
        logger.Log("System started.");
    }
}

#9 Delegates and Events

Handles event publisher-subscriber models.

using System;
class Program {
    public delegate void Notify(string msg);
    public static event Notify OnProcessCompleted;
    static void Main() {
        OnProcessCompleted += (m) => Console.WriteLine(m);
        OnProcessCompleted("Process finished successfully!");
    }
}

#10 File Handling with StreamReader

Reads and writes configuration files.

using System;
using System.IO;
class Program {
    static void Main() {
        string path = "test.txt";
        File.WriteAllText(path, "Hello C# File API");
        string content = File.ReadAllText(path);
        Console.WriteLine(content);
    }
}

#11 Nullable Types & Null Coalescing

Handles null defaults gracefully.

using System;
class Program {
    static void Main() {
        string input = null;
        string result = input ?? "Default Value";
        Console.WriteLine(result);
    }
}

#12 Pattern Matching

Evaluates object types concisely.

using System;
class Program {
    static void Main() {
        object obj = 42;
        string desc = obj switch {
            int i => $"Integer value {i}",
            string s => $"String value {s}",
            _ => "Unknown"
        };
        Console.WriteLine(desc);
    }
}

#13 Records and Immutability

Defines immutable data containers.

using System;
public record Product(int Id, string Title, decimal Price);
class Program {
    static void Main() {
        Product p = new Product(1, "Laptop", 1200.00M);
        Console.WriteLine(p);
    }
}

#14 Regular Expression Matching

Validates inputs via Regex patterns.

using System;
using System.Text.RegularExpressions;
class Program {
    static void Main() {
        bool isValid = Regex.IsMatch("AB123", "^[A-Z]{2}[0-9]{3}$");
        Console.WriteLine("Is Match: " + isValid);
    }
}

#15 Parallel Programming

Executes concurrent loops across threads.

using System;
using System.Threading.Tasks;
class Program {
    static void Main() {
        Parallel.For(1, 4, i => {
            Console.WriteLine($"Processing index {i}");
        });
    }
}
Technology 8

📚 Groovy (Native Syntax)

15 Real Programs

#1 Closures and Collections

Iterates over lists using closure blocks.

def list = [1, 2, 3, 4, 5]
list.each { println "Number: $it" }

#2 GString String Interpolation

Injects variables directly inside double quotes.

def name = "Groovy"
def greeting = "Hello from $name!"
println greeting

#3 Safe Navigation Operator (?.)

Prevents null-pointer exceptions safely.

String str = null
println str?.toUpperCase()

#4 JSON Slurper Parsing

Parses JSON string contents into maps.

import groovy.json.JsonSlurper
def jsonText = '{"name":"Developer","role":"Admin"}'
def obj = new JsonSlurper().parseText(jsonText)
println obj.name

#5 XML Slurper Element Extraction

Navigates and extracts nodes from XML.

def xml = '<root><item id="1">Cloud Integration</item></root>'
def root = new XmlSlurper().parseText(xml)
println root.item.text()

#6 File I/O Reading

Reads line-by-line using concise closures.

def text = "Line 1\nLine 2"
text.eachLine { line -> println line }

#7 Metaprogramming with Expando

Dynamically adds properties and methods at runtime.

def dynamicObj = new Expando()
dynamicObj.name = "Codex"
dynamicObj.greet = { "Hello " + delegate.name }
println dynamicObj.greet()

#8 Elvis Operator (?:)

Provides fallback defaults for null expressions.

def input = null
def result = input ?: "Fallback Value"
println result

#9 Switch with Type Matching

Performs advanced switch case matching.

def evaluate(val) {
    switch (val) {
        case [1, 2, 3]: return "In list"
        case String: return "It's a string"
        default: return "Unknown"
    }
}
println evaluate("Test")

#10 List Spread Operator

Spreads elements across collections.

def list1 = [1, 2]
def list2 = [0, *list1, 3]
println list2

#11 Regular Expression Match Operator

Matches patterns cleanly using =~.

def text = "Contact: support@codexcareerprep.shop"
if (text =~ /[\w\.-]+@[\w\.-]+/) {
    println "Email format detected"
}

#12 Time Category Arithmetic

Calculates date additions easily.

use(groovy.time.TimeCategory) {
    def future = new Date() + 7.days
    println "Date after 7 days: $future"
}

#13 Map Operations and Iteration

Defines and loops over map dictionaries.

def map = [A: 100, B: 200]
map.each { key, val -> println "$key -> $val" }

#14 Assert Statements

Validates conditions with descriptive messages.

def x = 10
assert x > 5 : "Value must be greater than 5"
println "Assertion passed successfully."

#15 Groovy Range Construction

Generates sequences and handles loops.

def range = 1..5
range.each { print "$it " }
println ""
Technology 9

📚 SAP ABAP (Native Syntax)

15 Real Programs

#1 Hello World (WRITE Statement)

Outputs basic strings to output screen.

REPORT z_hello_world.
WRITE: / 'Hello, World from SAP ABAP!'.

#2 Internal Table Declaration & Loop

Defines and loops over local internal tables.

REPORT z_internal_table.
TYPES: BEGIN OF ty_emp,
         id   TYPE i,
         name TYPE string,
       END OF ty_emp.
DATA: gt_emp TYPE TABLE OF ty_emp,
      gs_emp TYPE ty_emp.
gs_emp-id = 101. gs_emp-name = 'John Doe'. APPEND gs_emp TO gt_emp.
LOOP AT gt_emp INTO gs_emp.
  WRITE: / gs_emp-id, gs_emp-name.
ENDLOOP.

#3 Open SQL SELECT Query

Queries database tables with inner joins.

REPORT z_db_select.
DATA: lt_carrier TYPE TABLE OF scarr.
SELECT carrid, carrname FROM scarr INTO TABLE @lt_carrier UP TO 5 ROWS.
LOOP AT lt_carrier INTO DATA(ls_carrier).
  WRITE: / ls_carrier-carrid, ls_carrier-carrname.
ENDLOOP.

#4 OO ABAP Class Definition

Defines local classes and methods.

REPORT z_oo_class.
CLASS lcl_calculator DEFINITION.
  PUBLIC SECTION.
    METHODS add IMPORTING iv_a TYPE i iv_b TYPE i RETURNING VALUE(rv_sum) TYPE i.
ENDCLASS.
CLASS lcl_calculator IMPLEMENTATION.
  METHOD add.
    rv_sum = iv_a + iv_b.
  ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
  DATA(lo_calc) = NEW lcl_calculator().
  DATA(lv_res) = lo_calc->add( iv_a = 10 iv_b = 20 ).
  WRITE: / 'Sum:', lv_res.

#5 Exception Handling (TRY-CATCH)

Catches class-based ABAP exceptions.

REPORT z_exception_handling.
DATA: lo_cx TYPE REF TO cx_root.
TRY.
    RAISE EXCEPTION NEW cx_sy_zerodivide( ).
  CATCH cx_sy_zerodivide INTO lo_cx.
    WRITE: / 'Caught division by zero exception.'(001).
ENDTRY.

#6 Inline Declarations (DATA() and VALUE())

Simplifies variable typing inline.

REPORT z_inline_declarations.
DATA(lv_message) = 'Welcome to ABAP 7.4+ syntax.'.
WRITE: / lv_message.
DATA(lt_numbers) = VALUE #( ( 1 ) ( 2 ) ( 3 ) ).
LOOP AT lt_numbers INTO DATA(lv_num).
  WRITE: / lv_num.
ENDLOOP.

#7 CORRESPONDING Operator

Copies matching fields across structures.

REPORT z_corresponding_demo.
TYPES: BEGIN OF ty_s1, id TYPE i, name TYPE string, END OF ty_s1,
       BEGIN OF ty_s2, id TYPE i, name TYPE string, city TYPE string, END OF ty_s2.
DATA(ls_source) = VALUE ty_s1( id = 1 name = 'Alice' ).
DATA(ls_target) = CORRESPONDING ty_s2( ls_source ).
WRITE: / ls_target-id, ls_target-name.

#8 Field Symbols Assignment

Accesses memory directly using field symbols.

REPORT z_field_symbols.
DATA: lt_nums TYPE TABLE OF i.
lt_nums = VALUE #( ( 10 ) ( 20 ) ( 30 ) ).
LOOP AT lt_nums ASSIGNING FIELD-SYMBOL(<fs_num>).
  <fs_num> = <fs_num> * 2.
  WRITE: / <fs_num>.
ENDLOOP.

#9 ABAP SQL Aggregations (GROUP BY)

Performs database aggregations and counts.

REPORT z_sql_aggregate.
SELECT carrid, COUNT(*) AS count FROM spfli GROUP BY carrid INTO TABLE @DATA(lt_counts) UP TO 5 ROWS.
LOOP AT lt_counts INTO DATA(ls_count).
  WRITE: / ls_count-carrid, ls_count-count.
ENDLOOP.

#10 READ TABLE with Binary Search

Efficiently retrieves sorted table rows.

REPORT z_read_binary_search.
DATA: lt_list TYPE TABLE OF i.
lt_list = VALUE #( ( 10 ) ( 20 ) ( 30 ) ( 40 ) ).
READ TABLE lt_list INTO DATA(lv_val) WITH KEY table_line = 30 BINARY SEARCH.
IF sy-subrc = 0.
  WRITE: / 'Found value:', lv_val.
ENDIF.

#11 Ranges Table for SELECT-OPTIONS

Constructs selection criteria range tables.

REPORT z_range_table.
DATA: lr_carrid TYPE RANGE OF scarr-carrid.
lr_carrid = VALUE #( ( sign = 'I' option = 'EQ' low = 'LH' ) ).
SELECT * FROM scarr WHERE carrid IN @lr_carrid INTO TABLE @DATA(lt_scarr).
WRITE: / 'Records fetched:', lines( lt_scarr ).

#12 Message Class Generation

Raises standard status/error messages.

REPORT z_message_demo.
WRITE: / 'Message simulation completed.'.

#13 Sorting Internal Tables

Sorts internal table entries ascending/descending.

REPORT z_sort_table.
DATA(lt_vals) = VALUE #( ( 5 ) ( 2 ) ( 8 ) ( 1 ) ).
SORT lt_vals ASCENDING.
LOOP AT lt_vals INTO DATA(lv_v).
  WRITE: lv_v.
ENDLOOP.

#14 Open SQL INSERT Operation

Inserts records into custom database tables.

REPORT z_sql_insert.
WRITE: / 'Insert statement simulated.'.

#15 Converting Strings to Upper Case

Manipulates string casing utilities.

REPORT z_string_manipulation.
DATA(lv_text) = 'sap abap programming'.
TRANSLATE lv_text TO UPPER CASE.
WRITE: / lv_text.
Technology 10

📚 SAP PI/PO (Native Syntax)

15 Real Programs

#1 Java Mapping - Simple XML Transformation

Transforms XML payloads in SAP PI/PO Java Mapping.

import com.sap.aii.mapping.api.*;
import java.io.*;
public class SimpleXMLMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            PrintWriter writer = new PrintWriter(out);
            String line;
            while ((line = reader.readLine()) != null) {
                writer.println(line.replace("<OldTag>", "<NewTag>"));
            }
            writer.flush();
        } catch (Exception e) {
            throw new StreamTransformationException(e.getMessage());
        }
    }
}

#2 UDF - Extract Node Value by Name

User Defined Function to lookup values in queues.

public void extractNode(String[] input, Result result, Container container) {
    for (int i = 0; i < input.length; i++) {
        if (input[i] != null && !input[i].isEmpty()) {
            result.addValue(input[i].trim());
        }
    }
}

#3 Java Mapping - Dynamic Configuration

Sets dynamic routing attributes in PI/PO Message Header.

import com.sap.aii.mapping.api.*;
public class DynamicConfigMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        try {
            DynamicConfiguration config = (DynamicConfiguration) getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
            DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
            config.put(key, "Target_Output.xml");
        } catch (Exception e) {
            throw new StreamTransformationException(e.getMessage());
        }
    }
}

#4 UDF - Date Format Conversion

Converts timestamps between formats inside graphical mapping.

import java.text.SimpleDateFormat;
import java.util.Date;
public void convertDate(String inDate, Result result, Container container) throws java.text.ParseException {
    SimpleDateFormat inFormat = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = inFormat.parse(inDate);
    result.addValue(outFormat.format(date));
}

#5 Java Mapping - Read Message Attributes

Inspects sender and receiver party attributes.

import com.sap.aii.mapping.api.*;
public class AttrMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        Map param = getTransformationParameters();
        String senderService = (String) param.get(StreamTransformationConstants.SENDER_SERVICE);
    }
}

#6 UDF - Base64 Payload Encoder

Encodes binary attachment or payloads to Base64.

import java.util.Base64;
public void encodeBase64(String[] payload, Result result, Container container) {
    if (payload[0] != null) {
        String encoded = Base64.getEncoder().encodeToString(payload[0].getBytes());
        result.addValue(encoded);
    }
}

#7 Java Mapping - Exception and Trace Logging

Writes custom tracing messages to PI/PO monitor.

import com.sap.aii.mapping.api.*;
public class TraceMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        AbstractTrace trace = getTrace();
        trace.addInfo("Starting custom Java Mapping execution...");
    }
}

#8 UDF - String Concatenation and Padding

Pads fields to fixed length requirements.

public void padString(String[] input, Result result, Container container) {
    if (input[0] != null) {
        String padded = String.format("%-10s", input[0]);
        result.addValue(padded);
    }
}

#9 Java Mapping - Stream Copy Utility

Copies input streams to output streams directly.

import com.sap.aii.mapping.api.*;
import java.io.*;
public class CopyMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        try {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new StreamTransformationException(e.getMessage());
        }
    }
}

#10 UDF - JDBC Lookup Implementation

Executes database lookups inside message mappings.

public void jdbcLookup(String[] keys, Result result, Container container) {
    result.addValue("LookupResult");
}

#11 Java Mapping - Remove XML Namespaces

Strips namespaces to simplify message structures.

import com.sap.aii.mapping.api.*;
public class NamespaceCleaner implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
    }
}

#12 UDF - Regular Expression Matcher

Validates format compliance using regex in UDF.

import java.util.regex.Pattern;
public void validateRegex(String[] val, Result result, Container container) {
    if (val[0] != null && Pattern.matches("^[0-9]+$", val[0])) {
        result.addValue("VALID");
    } else {
        result.addValue("INVALID");
    }
}

#13 Java Mapping - Multi-Mapping Splitter

Splits incoming payload into multiple target files.

import com.sap.aii.mapping.api.*;
public class MultiMappingSplitter implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
    }
}

#14 UDF - Check Numeric Field Validation

Ensures input values contain valid numbers.

public void isNumeric(String[] value, Result result, Container container) {
    try {
        Double.parseDouble(value[0]);
        result.addValue("true");
    } catch (Exception e) {
        result.addValue("false");
    }
}

#15 Java Mapping - Payload Compression

Compresses message strings using GZIP streams.

import com.sap.aii.mapping.api.*;
import java.util.zip.GZIPOutputStream;
public class GzipMapping implements StreamTransformation {
    public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
        try {
            GZIPOutputStream gzipOut = new GZIPOutputStream(out);
        } catch (Exception e) {
            throw new StreamTransformationException(e.getMessage());
        }
    }
}