{"id":44641668,"url":"https://github.com/reshinto/programming_language_syntax_comparison","last_synced_at":"2026-02-14T18:34:33.766Z","repository":{"id":101049592,"uuid":"171147762","full_name":"reshinto/programming_language_syntax_comparison","owner":"reshinto","description":"Compare syntax differences between programming languages (python, javascript, ruby, java, c#, c/c++). This would be deprecated soon. Moving to https://www.terencekong.net/docs/documentation","archived":false,"fork":false,"pushed_at":"2025-03-11T19:55:50.000Z","size":8098,"stargazers_count":87,"open_issues_count":0,"forks_count":22,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-11T20:33:38.413Z","etag":null,"topics":["c-plus-plus","csharp","java","javascript","python","ruby"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reshinto.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-17T17:00:41.000Z","updated_at":"2025-03-11T19:55:54.000Z","dependencies_parsed_at":"2023-05-30T15:30:23.103Z","dependency_job_id":null,"html_url":"https://github.com/reshinto/programming_language_syntax_comparison","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/reshinto/programming_language_syntax_comparison","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reshinto%2Fprogramming_language_syntax_comparison","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reshinto%2Fprogramming_language_syntax_comparison/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reshinto%2Fprogramming_language_syntax_comparison/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reshinto%2Fprogramming_language_syntax_comparison/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reshinto","download_url":"https://codeload.github.com/reshinto/programming_language_syntax_comparison/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reshinto%2Fprogramming_language_syntax_comparison/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29452371,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T15:52:44.973Z","status":"ssl_error","status_checked_at":"2026-02-14T15:52:11.208Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-plus-plus","csharp","java","javascript","python","ruby"],"created_at":"2026-02-14T18:34:33.621Z","updated_at":"2026-02-14T18:34:33.735Z","avatar_url":"https://github.com/reshinto.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# PROGRAMMING LANGUAGE SYNTAX COMPARISON\n\n\u003e A syntax summary, which also compares the differences between each programming language.\n\n- List of languages\n  - Python, Javascript (Typescript), Ruby, Kotlin, Java, C#, C/C++, Groovy\n\n## Table of Contents\n\n- [Interpreted Language](#interpreted-language)\n- [Compiled Language](#compiled-language)\n- [Both Interpreted And Compiled Language](#both-interpreted-and-compiled-language)\n- [Hello World](#hello-world)\n- [Comments](#comments)\n- [Data types](#data-types)\n- [Variable declaration int](#variable-declaration-int)\n- [Variable declaration float](#variable-declaration-float)\n- [Variable declaration None](#variable-declaration-none)\n- [Strings](#strings)\n- [Boolean](#boolean)\n- [Arithmetic Operators](#arithmetic-operators)\n- [Comparison Operators](#comparison-operators)\n- [Logical Operators](#logical-operators)\n- [Getting Input](#getting-input)\n- [Bitwise Operators](#bitwise-operators)\n- [Increment](#increment)\n- [Arrays and Lists](#arrays-and-lists)\n- [Conditional Statement](#conditional-statement)\n- [Loops](#loops)\n- [Instantiation](#instantiation)\n- [Functions](#functions)\n- [Higher order functions](#higher-order-functions)\n- [Hash Tables](#hash-tables)\n- [Destructuring](#destructuring)\n- [Spread Operator](#spread-operator)\n- [Rest parameters](#rest-parameters)\n- [Class](#class)\n- [Importing Libraries](#importing-libraries)\n- [Type Conversions](#type-conversions)\n- [Find Data Type](#find-data-type)\n- [String Concatenation](#string-concatenation)\n- [JSON](#json)\n- [Program Entry Point](#program-entry-point)\n- [Swapping values](#swapping-values)\n- [Error Handling](#error-handling)\n- [Custom Error](#custom-error)\n- [Asynchronous](#asynchronous)\n- [Math](#math)\n- [Date and Time](#date-and-time)\n- [Access modifier](#access-modifier)\n- [File System](#file-system)\n- [Iterators](#iterators)\n- [Generators](#generators)\n- [Fetching Web Data](#fetching-web-data)\n- [Enum](#enum)\n- [Language Specific](#language-specific)\n\n## Interpreted Language\n\n### Dynamically-typed Language: resolution of types, members, properties, methods are done at run-time\n\n#### lose compile-time checking, have to write more unit tests to ensure app behaves properly at run-time\n\n- Python\n- Javascript\n  - Features\n    - based on ECMAScript standard\n    - not compiled, interpreted at runtime\n    - no native function calls in browser\n    - runtime differ between environments\n    - restricted to browser sandbox\n    - managed memory access\n    - prototype-based inheritance\n- Ruby\n\n## Compiled Language\n\n### Statically-typed Language: resolution of types, members, properties, methods are done at compile-time\n\n#### trying to access a method that is not defined in an object when compiling the app will get an immediate error feedback\n\n- Java: compiled to bytecode then interpreted by Java virtual machine into machine code\n  - Features\n    - not compatible with other languages\n    - calls to native functions go through Java Native Interface (JNI)\n    - write once, run anywhere\n    - runs in a protected Java Virtual Machine (JVM)\n    - managed memory access\n    - limited to single inheritance\n    - class-based inheritance\n  - Types\n    - Java Platform, Standard Edition (SE)\n      - Core language and Java Runtime Environment (JRE)\n    - Java Platform, Enterprise Edition (EE)\n      - Recommendation for industrial-strength web applications\n    - Java Platform, Micro Edition (ME)\n      - Microcontrollers, sensors, mobile devices, telephone sim cards\n      - A subset of Java SE\n    - Java FX\n      - Desktop appication framework (windows, mac, linux)\n  - Automatic memory management\n    - memory for objects are allocated automatically\n    - local variables \u0026 function calls are stored in stack\n    - objects \u0026 member variables are stored in heap\n    - objects are retained in memory until dereferenced\n    - object is eligible for collection when all references expire\n      - when do references expire\n        - variables local to methods or code blocks expire with scope\n        ```java\n        void changeString() {\n          String localVar = \"Won't be around for long!\";\n          System.out.println(\"In function: \" + localVar);\n        }\n        ```\n        - explicitly dereference variables with null keyword\n        ```java\n        void changeString() {\n          String localVar = \"Won't be around for long!\";\n          tempVar = null;\n        }\n        ```\n    - when Java Virtual Machine runs out of memory for a newly requested object\n      - the system throws `OutOfMemoryError`\n      - Tips for managing memory\n        - minimize the number of objects created\n        - find out how much memory is available \u0026 is currently in used in the virtual machine\n          - `Runtime.maxMemory()` \u0026 `Runtime.totalMemory()`\n        - setting available memory\n          - use command line options to manage amount of available heap memory\n            - set inital heap size `java -Xms256s HelloWord`\n            - set max heap size `java -Xmx256m HelloWord`\n            - set heap size for new objects `java -Xmn256n HelloWord`\n  - Java Garbage Collector\n    - runs in its own thread\n    - allocates \u0026 deallocates memory\n    - can destroy dereferenced objects, but not required\n    - garbage collection is managed by the Virtual Machine\n    - cannot force garbage collection as it is an automatic process\n      - Can run System methods to call garbage collection\n        - Methods `System.gc()` \u0026 `Runtime.gc()` can request garbage collection\n          - but there is no guarantee it will happen\n  - Identifiers and Keywords\n    - Keywords can't be used as class or other identifiers\n    - class, method, field, and other names are identifiers\n    - identifiers must start with alpha character or underscore\n  - Identifier conventions\n  - classes are always Pascal case `class MyClass {}`\n  - methods and variables are Camel case `void doSomething(String withThis) {}`\n  - constants are all uppercase `public static final String FIRSTNAME=\"Myname\";`\n    - `final` means once it has been set, it can't be changed\n- C#: compiled to an Intermediate Language (IL), which is then translated by the Common Language Runtime (CLR) into machine code\n  - from .NET 4, dynamic capability was added to improve interoperability with COM \u0026 Dynamic languages\n- C++: compiled into native machine language\n\n  - what it is\n    - it is a **standardized, compiled, statically typed, multi-paradigm systems language** built to deliver **high performance with strong abstraction mechanisms**.\n    - Its design centers on **zero-overhead abstractions**, **deterministic resource management (RAII)**, a **formal concurrency/memory model**, and a rich **standard library** that has evolved substantially in **C++20/23** (concepts, modules, coroutines, ranges, expected, mdspan).\n    - It interoperates with C but is not a strict superset, and it remains a foundational tool for building complex, performance-critical software.\n\n  - Design goals \u0026 principles\n    - C++ is designed to give **efficient low-level control** together with **high-level abstractions**, guided by the **zero-overhead principle** (“you don’t pay for what you don’t use,” and used abstractions are as efficient as hand-written code).\n    - These principles explain C++’s emphasis on performance with abstractions like classes, templates, and RAII.\n\n  -  Standardization \u0026 versions\n      - C++ is maintained via ISO standards with regular releases (e.g., **C++11, C++14, C++17, C++20, C++23**, and ongoing work toward **C++26**).\n      - C++20 introduced **concepts**, **modules**, **coroutines**, and the **ranges** library; `C++23` added new library types such as **`std::expected`** and **`std::mdspan`**.\n      - Compiler support tables are tracked publicly.\n  - Compilation model\n    - C++ is primarily **ahead-of-time (AOT) compiled** to native code.\n    - Traditional organization is by **translation units** and headers; **C++20 modules** add a language mechanism to publish/import interfaces, improving build times and isolation.\n  - Type system \u0026 object model\n    - C++ has a **static** and **nominal** type system with fundamental types (integers, floating-point, `bool`, character types, pointer/reference types), user-defined types (enums, classes/structs, unions), function and array types, and **cv-qualification** (`const`/`volatile`).\n    - Objects have precise lifetimes and storage durations; initialization and destruction semantics are part of the core model.\n  - Programming paradigms\n    - C++ is **multi-paradigm**:\n    - **Procedural** (free functions, control flow)\n    - **Object-oriented** (encapsulation, virtual dispatch, class hierarchies)\n    - **Generic programming \u0026 templates** (compile-time polymorphism; concepts in C++20)\n    - **Functional style** (lambdas, higher-order algorithms)\n    - **Metaprogramming** (`constexpr`, template metaprogramming)\n  - Resource management \u0026 safety model\n    - C++ emphasizes **deterministic destruction** and **RAII** (Resource Acquisition Is Initialization):\n      - acquire resources in constructors, release them in destructors.\n    - Modern guidelines recommend using **resource handles** and **smart pointers** to avoid leaks and dangling resources.\n    - C++ deliberately leaves some behavior **undefined** to enable aggressive optimization (e.g., out-of-bounds access, data races, signed-overflow).\n    - Understanding and avoiding **undefined behavior** is part of writing correct and portable C++.\n  - Error handling\n    - C++ supports **exceptions** (with zero-overhead when absent, but runtime cost when used) and non-exception patterns such as returning status objects.\n    - **`std::expected\u003cT,E\u003e`** (C++23) is a standard vocabulary type for functions that return either a value or an error.\n  - Concurrency \u0026 memory model\n    - C++ defines a **formal memory model** and provides **threads**, **atomics**, and **memory orderings** for writing correct concurrent code, including lock-free algorithms when possible.\n    - **Coroutines (C++20)** provide a language mechanism for asynchronous workflows.\n  - Standard library\n    - The C++ Standard Library supplies containers, iterators, algorithms, strings, time utilities, I/O, numerics, concurrency primitives, ranges (C++20), multi-dimensional views (`mdspan`, C++23), and more.\n    - It also exposes C compatibility headers for interop.\n  - Interoperability with C (and ABIs)\n    - C++ interoperates with C at the **linkage** level using `extern \"C\"` for C function names (no C++ name mangling).\n    - C and C++ are **closely related but different languages**;\n    - C is **not a subset** of C++, and some valid C code is ill-formed or behaves differently in C++.\n    - C++ compilers don’t share a single universal ABI; platforms commonly use ABIs like the Itanium C++ ABI for cross-compiler compatibility.\n  - Typical domains\n    - Because it combines **close-to-the-metal control** with **high-level abstractions**, C++ is widely used for **systems software, embedded, game engines, high-performance computing, finance/low-latency, browsers, databases**, and other performance-critical infrastructure.\n    - (For a concise perspective from the language’s creator on these aims and domains, see Stroustrup’s writings on C++ as an “invisible foundation.”)\n\n## Both Interpreted And Compiled Language\n\n- Groovy\n  - it is a Java-syntax-compatible object-oriented programming language for the Java platform\n  - is both a static and dynamic language with features similar to those of Python\n  - can be used as both a programming language and a scripting language for the Java Platform, is compiled to Java virtual machine (JVM) bytecode\n    - interoperates seamlessly with other Java code and libraries\n  - allows optionally-typed dynamic capabilities\n    - do not need to spell out the type of field\n  - allows advance programming\n    - metaprogramming, functional programming, closures\n  - supports authoring of domain-sepcific languages\n    - jenkins file: to create a built pipeline with jenkins\n    - gradle build script\n  - requires installation of Java Development Kit (JDK) to work\n  - allows duck typing: provides the option to use the `def` keyword to determine the type at runtime\n  - can also have a variable assign a concrete type\n    - can tell groovy compiler to enforce static typing if needed\n  - auto generates getter and setter methods at runtime for class members\n  - contains Abstract Syntax Tree (AST) transformations: provides annotations for generating methods at runtime\n    - such as defining contructors, equals, hashCode, toString methods\n  - automatically imports commonly-used packages\n    - like `java.util.*` and `java.io.*`\n  - makes the default modifier as public, leading to less verbose code\n  - semicolons are optional, only required if want to define more than 1 statement on a single line\n\n## Hello World\n\n### python 2\n\n```python\nprint \"Hello World\"\n```\n\n### python 3\n\n```python\nprint(\"Hello World\")  # \"Hello World\\n\"\nprint(\"Hello\", \"World\", sep=\"/\")  # \"Hello/World\"\nprint(\"Hello World\", end=\"\")  # \"Hello World\"\n```\n\n### javascript\n\n```javascript\nconsole.log(\"Hello World\"); // \"Hello World\"\nconsole.log(\"Hello\", \"World\"); // \"Hello World\"\n```\n\n### ruby\n\n```ruby\nprint \"Hello World\"  # takes whatever you give it and prints it to the screen\nputs \"Hello World\"  # adds a new (blank) line after the thing you want it to print\np \"Hello World\"  # same as puts\n```\n\n### kotlin\n\n```kotlin\n// fun for function declaration\nfun main() {  // main method, a must to have\n    println(\"Hello, world\")  // adds new line after printing\n}\n```\n\n### java\n\n- java classes are typically organized into packages\n  - package is a global unique string that usually starts with your domain name in reverse domain order\n    - ensures globally unique identifiers (e.g.: Main)\n      - if there are more than 1 class named Main in an app\n        - can be distinguished by using the package\n- each source code file will contain 1 public class\n- `public` visible to all classes\n- `protected` visible to class they belong and any subclasses\n- `private` (most restricted): visible only to class they belong\n- `static` can be accessed without creating a class instance\n- `final` constant value, value cannot be changed\n- `void` means that the method doesn't return any value\n\n```java\npackage com.example;  // package declaration\n\n// class declaration\npublic class HelloWorld {\n  // main method: always have the 3 keywords (public, static, void)\n  // must also receive an array of strings as an argument\n  public static void main(String[] args) {\n    // executable code\n    System.out.println(\"Hello World\");  // adds new line after printing\n    System.out.print(\"Hello World\");  // no new line is added after\n  }\n}\n```\n\n### c#\n\n```c#\npublic class HelloWorld {\n  public static void Main() {\n    System.Console.WriteLine(\"Hello World\");  // adds new line after printing\n    System.Console.Write(\"Hello World\");  // no new line is added after printing\n  }\n}\n```\n\n### c++\n\n```c++\n#include \u003ciostream\u003e // required for printing\n\nint main()\n{\n    std::cout \u003c\u003c \"Hello, World!\";\n    return 0;\n}\n```\n\n### groovy\n\n- using dynamic type method\n\n```groovy\nprintln \"Hello World\"\n```\n\n- using static type method\n\n```groovy\nclass HelloWorld {\n  static void main(String[] args) {\n    println(\"Hello World\");\n  }\n}\n```\n\n### assembly\n\n```assembly\n; x86 32 bit Mac OSX\n; to run file, compile and run with the following command\n; nasm -f macho hello_world32.asm \u0026\u0026 ld -macosx_version_min 10.7.0 -o hello_world32 hello_world32.o \u0026\u0026 ./hello_world32\n\nglobal start\n\nsection .text\nstart:\n    push    dword msg.len\n    push    dword msg\n    push    dword 1\n    mov     eax, 4\n    sub     esp, 4\n    int     0x80\n    add     esp, 16\n\n    push    dword 0\n    mov     eax, 1\n    sub     esp, 12\n    int     0x80\n\nsection .data\n\nmsg:    db      \"Hello, world!\", 10\n.len:   equ     $ - msg\n```\n\n```assembly\n; x86_64 64 bit Mac OSX\n; to run file, compile and run with the following command\n; nasm -f macho64 hello_world64.asm \u0026\u0026 ld -macosx_version_min 10.7.0 -lSystem -o hello_world64 hello_world64.o \u0026\u0026 ./hello_world64\n\nglobal start\n\nsection .text\n\nstart:\n    mov     rax, 0x2000004 ; write\n    mov     rdi, 1 ; stdout\n    mov     rsi, msg\n    mov     rdx, msg.len\n    syscall\n\n    mov     rax, 0x2000001 ; exit\n    mov     rdi, 0\n    syscall\n\nsection .data\n\nmsg:    db      \"Hello, world!\", 10\n.len:   equ     $ - msg\n```\n\n[back to top](#table-of-contents)\n\n## Comments\n\n### python 2 \u0026 3\n\n```python\n# Single line comment\n\n\"\"\"\nmulti-line comments\n\"\"\"\n```\n\n### javascript\n\n```javascript\n// Single line comment\n\n/*\nmulti-line comments\n*/\n```\n\n### ruby\n\n```ruby\n# Single line comment\n\n=begin\nmulti-line comments\n=end\n```\n\n### java\n\n```java\n// Single line comment\n\n/*\nmulti-line comments\n*/\n\n/**\n * javadoc \u003cb\u003ecomments\u003c/b\u003e for classes, javadocs can be used to auto generate documentation documents for code commented with javadocs\n */\n\n /**\n * javadoc \u003cb\u003ecomments\u003c/b\u003e for methods with parameters - example main method\n * @param args - an array of string values\n */\n```\n\n### c#\n\n```c#\n// Single line comment\n\n/*\nmulti-line comments\n*/\n```\n\n### c++\n\n```c++\n// Single line comment\n\n/*\nmulti-line comments\n*/\n```\n\n### assembly\n\n```assembly\n; Single line comment\n```\n\n[back to top](#table-of-contents)\n\n## Data types\n\n### python\n\n#### 8 main data types\n\n- Text type\n  - `str`, `x = \"Hello World\"\t`, `x = str(\"Hello World\")`\n- Numeric types\n  - `int`, `x = 20\t`, `x = int(20)`\n  - `float`, `x = 20.5`, `x = float(20.5)`\n  - `complex`, `x = 1j`, `x = complex(1j)`\n- Sequence types\n  - `list`, `x = [\"apple\", \"banana\", \"cherry\"]`, `x = list((\"apple\", \"banana\", \"cherry\"))`\n  - `tuple`, `x = (\"apple\", \"banana\", \"cherry\")`, `x = tuple((\"apple\", \"banana\", \"cherry\"))`\n  - `range`, `x = range(6)`, `x = range(6)`\n- Mapping type\n  - `dict`, `x = {\"name\" : \"John\", \"age\" : 36}`, `x = dict(name=\"John\", age=36)`\n- Set types\n  - `set`, `x = {\"apple\", \"banana\", \"cherry\"}`, `x = set((\"apple\", \"banana\", \"cherry\"))`\n  - frozenset`, `x = frozenset({\"apple\", \"banana\", \"cherry\"})`, `x = frozenset((\"apple\", \"banana\", \"cherry\"))```\n- Boolean type\n  - `bool`, `x = True`, `x = bool(5)`\n- Binary types\n  - `bytes`, `x = b\"Hello\"`, `x = bytes(5)`\n  - `bytearray`, `x = bytearray(5)`, `x = bytearray(5)`\n  - `memoryview`, `x = memoryview(bytes(5))`, `x = memoryview(bytes(5))`\n- None type\n  - `None`, `x = None`\n\n### javascript\n\n#### 1 primitive structural root\n\n- null\n  - unknown values – a standalone type that has a single value null\n\n#### 2 Structual types\n\n- object\n  - for more complex data structures\n  - new Object, new Array, new Map, new Set, new WeakMap, new Date, new ...\n\n#### 6 basic primitive data types\n\n- number\n  - for numbers of any kind: integer or floating-point, integers are limited by ±(2^53-1) === ±9007199254740991\n  - contain\n    - regular numbers\n      ```javascript\n      let n = 123;\n      ```\n    - floats\n      ```javascript\n      let n = 1.23;\n      ```\n    - special numeric values\n      - Infinity\n        ```javascript\n        let n = 1 / 0;\n        let n2 = Infinity;\n        ```\n      - -Infinity\n      - NaN\n        ```javascript\n        let n = \"not a number\" / 2; // NaN\n        ```\n- bigint\n  - no maximum limit to a BigInt\n  ```javascript\n  let bigInt = 1234567890123456789012345678901234567890n; // ends with n\n  ```\n- string\n  - may have zero or more characters, there’s no separate single-character type\n- boolean\n  - true / false.\n- undefined\n  - unassigned values – a standalone type that has a single value undefined\n- symbol\n\n  - for unique identifiers\n\n  ```javascript\n  // id is a new symbol\n  let id = Symbol();\n\n  // can give symbol a description (also called a symbol name), mostly useful for debugging purposes\n  let _id = Symbol(\"id2\");\n\n  // symbol in an object literal\n  let obj = {\n    [_id]: 123, // not \"id\": 123\n  };\n\n  // guaranteed to be unique\n  let id1 = Symbol(\"id\");\n  let id2 = Symbol(\"id\");\n  console.log(id1 == id2); // false\n\n  // convert symbol to string\n  id1.toString(); // \"Symbol(id)\"\n\n  // get symbol description\n  id1.description; // \"id\"\n  ```\n\n  - Symbols allow us to create “hidden” properties of an object, that no other part of code can accidentally access or overwrite\n\n  ```javascript\n  let user = {\n    // belongs to another code\n    name: \"John\",\n  };\n\n  let id = Symbol(\"id\");\n  user[id] = 1;\n  console.log(user[id]); // 1\n  console.log(user); // { name: 'John', [Symbol(id)]: 1 }\n  ```\n\n  - benefit of using symbol over string\n    - objects belongs to another code, and that code also works with them, we shouldn’t just add any fields to it\n    - symbol cannot be accessed accidentally, the third-party code probably won’t even see it\n  - Symbols are skipped by for...in loop\n\n  ```javascript\n  let id = Symbol(\"id\");\n  let user = {\n    name: \"John\",\n    age: 30,\n    [id]: 123,\n  };\n\n  for (let key in user) console.log(key); // name age undefined\n  ```\n\n  - Symbol can be cloned with Object.assign\n\n  ```javascript\n  let id = Symbol(\"id\");\n  let user = {\n    [id]: 123,\n  };\n\n  let clone = Object.assign({}, user);\n  console.log(clone); // { [Symbol(id)]: 123 }\n  ```\n\n  - global symbols\n    - use if want same-named symbols to be same entities\n\n  ```javascript\n  // get symbol by name\n  let id1 = Symbol.for(\"id\");\n  let id2 = Symbol.for(\"id\");\n\n  console.log(id1 === id2); // true\n\n  // get name by symbol, can only use for global symbol\n  console.log(Symbol.keyFor(id1)); // \"id\"\n  ```\n\n### java 8\n\n#### 2 major data types\n\n1. Primitive data types\n\n   - stored in fastest available memory\n   - names are all camel case\n   - Java class library includes helper classes for each primitive\n     - helper classes support conversion and formatting tools\n     - `import java.lang.Byte;` import not required from java.lang libraries\n   - all primitive numeric variables default to 0\n\n   ```java\n   public class Main {\n     private static int myInt;  // must be declared as static of a class to have default value\n\n     public static void main(String args[]) {\n       System.out.println(myInt);  // 0\n     }\n   }\n   ```\n\n   - data types\n     - numbers\n       - byte\n         - 8 bits\n         - -128 to 127\n         - default value `0`\n         - helper class `Byte`\n       - short\n         - 16 bits\n         - -32,768 to 32,767\n         - default value `0`\n         - helper class `Short`\n       - int\n         - 32 bits\n         - -2,147,483,648 to 2,147,483,647\n         - default value `0`\n         - helper class `Integer`\n       - long\n         - 64 bits\n         - -9.22337E+18 to 9.22337E+18\n         - default value `0L`\n         - helper class `Long`\n       - float\n         - 32 bits\n         - default value `0.0f` or `0.0F` or `.0f` or `.0F`\n         - helper class `Float`\n       - double\n         - 64 bits\n         - default value `0.0d` or `0.0D` or `.0d` or `.0D`\n         - helper class `Double`\n         ```java\n         double doubleValue = 156.5d;\n         Double doubleObj = new Double(doubleValue);  // declare instance of the double class\n         int intValue = doubleObj.intValue();  // 156, use helper object to convert to desired numeric data type\n         ```\n     - characters\n       - '\\u0000' (or 0) to '\\uffff' (or 65,535 inclusive)\n       - default value `'\\u0000'`\n     - booleans\n       - default value `false`\n\n2. Objects\n   - an object is an instance of a class\n   - nonprimitive variables are references to objects\n   - objects can have multiple references\n   - Object data types\n     - String\n       - a complex object\n       - is an instance of the string class\n       - is an array of characters\n       - string objects are immutable\n       - reasigning the string value creates a new object\n         - the old object can be cleared from memory thrown garbage collection process\n       - helper class is `java.lang.String`, thus import not required\n       ```java\n       String string1 = new String(\"Hello\");\n       ```\n\n### c++\n- it is a strict data typed language\n- the data type can be changed implicitly or explicitly\n- implicit happens when you have compatible data types\n- can assign a short variable to an integer variable\n- a float can be assigned to a double value\n- must go from smaller to larger for data integrity\n- a bool variable can be assigned to an int\n- a character can also be assigned to an int\n- ``static_cast\u003c\u003e` can be used to change a data type\n```c++\ndouble x{45.765};\nint y = static_cast\u003ciint\u003e(x);  // 45\nint b = true;  // 1\nint c = 'c';  // 97\n```\n\n#### Fundamental Data Types\n- The Microsoft C++ 32-bit and 64-bit compilers recognize the types below.  \n- If a type name begins with `__`, it is **non-standard**.  \n\n#### Recognized integral type names\n\n`int (unsigned int)`, `__int8 (unsigned __int8)`, `__int16 (unsigned __int16)`, `__int32 (unsigned __int32)`, `__int64 (unsigned __int64)`, `short (unsigned short)`, `long (unsigned long)`, `long long (unsigned long long)`\n\n| Type Name              | Bytes | Other Names                                      | Range of Values                                                                 |\n|------------------------|:-----:|--------------------------------------------------|----------------------------------------------------------------------------------|\n| `int`                  | 4     | `signed`                                         | −2,147,483,648 to 2,147,483,647                                                 |\n| `unsigned int`         | 4     | `unsigned`                                       | 0 to 4,294,967,295                                                               |\n| `__int8`               | 1     | `char`                                           | −128 to 127                                                                      |\n| `unsigned __int8`      | 1     | `unsigned char`                                  | 0 to 255                                                                         |\n| `__int16`              | 2     | `short`, `short int`, `signed short int`         | −32,768 to 32,767                                                                |\n| `unsigned __int16`     | 2     | `unsigned short`, `unsigned short int`           | 0 to 65,535                                                                      |\n| `__int32`              | 4     | `signed`, `signed int`, `int`                    | −2,147,483,648 to 2,147,483,647                                                 |\n| `unsigned __int32`     | 4     | `unsigned`, `unsigned int`                       | 0 to 4,294,967,295                                                               |\n| `__int64`              | 8     | `long long`, `signed long long`                  | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807                         |\n| `unsigned __int64`     | 8     | `unsigned long long`                             | 0 to 18,446,744,073,709,551,615                                                  |\n| `bool`                 | 1     | —                                                | `false` or `true`                                                                |\n| `char`                 | 1     | —                                                | −128 to 127 (default) \u003cbr\u003e **0 to 255 when compiled with `/J`**                  |\n| `signed char`          | 1     | —                                                | −128 to 127                                                                      |\n| `unsigned char`        | 1     | —                                                | 0 to 255                                                                         |\n| `short`                | 2     | `short int`, `signed short int`                  | −32,768 to 32,767                                                                |\n| `unsigned short`       | 2     | `unsigned short int`                             | 0 to 65,535                                                                      |\n| `long`                 | 4     | `long int`, `signed long int`                    | −2,147,483,648 to 2,147,483,647                                                 |\n| `unsigned long`        | 4     | `unsigned long int`                              | 0 to 4,294,967,295                                                               |\n| `long long`            | 8     | — (equivalent to `__int64`)                      | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807                         |\n| `unsigned long long`   | 8     | — (equivalent to `unsigned __int64`)             | 0 to 18,446,744,073,709,551,615                                                  |\n| `enum`                 | varies| —                                                | implementation-dependent                                                         |\n| `float`                | 4     | —                                                | approx. 3.4E ± 38 (seven digits)                                                |\n| `double`               | 8     | —                                                | approx. 1.7E ± 308 (fifteen digits)                                             |\n| `long double`          | 8     | —                                                | approx. 1.7E ± 308 (fifteen digits)                                             |\n| `wchar_t`              | 2     | `__wchar_t`                                      | 0 to 65,535                                                                      |\n\n#### Notes\n- `signed`/`unsigned` modifiers apply to any integral type **except** `bool`.  \n- `char`, `signed char`, and `unsigned char` are **three distinct types** (affects overloading/templates).  \n- On MSVC, `int`/`unsigned int` are 4 bytes; avoid assuming `int` size in portable code.  \n- MSVC also supports sized integer types: `__int8`, `__int16`, `__int32`, `__int64`.  \n- For precise limits in code, use `\u003climits\u003e` (`std::numeric_limits\u003cT\u003e`).  \n- `__wchar_t`/`wchar_t`: use the `L` prefix for wide character/string literals.\n\n#### Others\n- `\u0026` a reference value (address of)\n- `*` identifies a point value\n\n#### Compoimd Types\n- string `#include\u003cstring\u003e`\n    - A string is an array of characters\n- vector `#include\u003cvector\u003e`\n- array `#include\u003carray\u003e`\n- list `#include\u003clist\u003e`\n\n[back to top](#table-of-contents)\n\n## Variable declaration int\n\n- integer ...-2, -1, 0, 1, 2...\n\n### python 2\n\n```python\n# int: -2147483648 ~ 2147483647\ninteger_name = 123\n# long: -9223372036854775808L ~ 9223372036854775807L\nlong_name = 123L  # int beyond int size will automatically be converted to long\n```\n\n### python 3\n\n```python\n# python 3: int and long are combined into int\ninteger_name = 123\n```\n\n### javascript ES5\n\n```javascript\n// method 1\nvar integer_name;\ninteger_name = 123; // accessible within the function\n\n// method 2\nvar integer_name = 123;\n```\n\n### javascript ES6\n\n```javascript\n// method 1\nlet integer_name;\ninteger_name = 123; // accessible only within the block {}\n\n// method 2\nlet integer_name = 123;\n\n// method 3\nconst integer_name = 123; // variable value cannot be reassigned\n```\n\n### typescript\n\n```typescript\nlet integer_name: number = 123; // method 1\nlet integer_name2 = 123; // method 2, not required to declare type if assigning to value\nlet integer_name3: number; // must declare the value type\ninteger_name3 = 123;\n\nlet decimal: number = 6;\nlet hex: number = 0xf00d;\nlet binary: number = 0b1010;\nlet octal: number = 0o744;\n```\n\n### ruby\n\n```ruby\ninteger_name = 123\n```\n\n### java\n\n```java\n// public/private/protected static final byte/short/int/long integerName = 123;\n/*\npublic: visible to all classes\nprotected: visible to class they belong and any subclasses\nprivate (most restricted): visible only to class they belong\nstatic: can be accessed without creating a class instance\nfinal: constant value, value cannot be changed\n*/\n\n// byte: -128 ~ 127, 8 bits\nbyte byteName = 123;\n\n// short: -32768 ~ 32767, 16 bits\nshort shortName = 123;\n\n// int: -2147483648 ~ 2147483647, -2_147_483_648 ~ 2_147_483_647, 32 bits\nint integerName; integerName = 123;\nint integerName2 = 123;  // default is visible within the same package\n\n// long: -9223372036854775808L ~ 9223372036854775807L, can use _ same as int, 64 bits\nlong longName1 = 123l;  // 123\nlong longName2 = 123L;  // 123\nlong longName3 = 10_000;  // 10000, introduced in java 7, just makes it easier to read\n```\n\n### c#\n\n```c#\n// var can be used to handle declarations when the data type is unknown\n// once a variable is declared with var, the variable cannot be reassigned to a different data type\nvar variableName = 123;\nvariableName = \"123\";  // error CS0029: Cannot implicitly convert type `string' to `int'\n\n// byte: -128 ~ 127, 8 bits\nbyte byteName = 123;  // type Byte\nSystem.Byte byteName2 = 123;\n\n// short: -32768 ~ 32767, 16 bits\nshort shortName = 123;  // type Int16\nSystem.Int16 shortName2 = 123;\n\n// int: -2,147,483,648 ~ 2,147,483,647\nint integerName1 = 123;  // type Int32\nint integerName2 = int.MaxValue;  // 2147483647\nSystem.Int32 integerName3 = 123;\n\n// Add const before variable declaration to make it a constant\nconst int integerName3 = 123;\n\n// long: -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807\nlong longName1 = 123;  // type Int64\nlong longName2 = long.MaxValue;  // 9223372036854775807\nSystem.Int64 longName3 = 123;\n\n// decimal: max value 79,228,162,514,264,337,593,543,950,335\ndecimal decimalName1 = 123;  // type Decimal\ndecimal decimalName2 = 123m;\ndecimal decimalName3 = decimal.MaxValue;  // 79228162514264337593543950335\nSystem.Decimal decimalName4 = 123;\n\n// use System.Numerics.BigInteger for larger values (need add references to System.Numerics.dll)\n```\n\n### c++\n\n```c++\n// const unsigned char/short/int/long/long long integer_name = 123;\n/*\nconst: constant value, value cannot be changed\ninteger are signed by default: can assign both positive \u0026 negative values\nunsigned integer (use when dealing with bit values): 0 ~ ...\n  e.g. char: -128 ~ 127\n  e.g. unsigned char: 0 ~ 255  // 128 + 127 = 255\n*/\n\n// char: 1 byte, -128 ~ 127, use C code to print \"#include＜stdio.h＞ printf(\"%d\", char_name);\"\n// 1 char has 8 bits\nchar char_name;\nchar_name = 123;\n\n// similar to the rest of int variable declaration\n\n// short/short int: 16 bits, 2 bytes, -32768 ~ 32767\nshort short_name;\nshort_name = 123;\n\nshort int short_name; short_name = 123;\n\n// similar to the rest of int variable declaration\n\n// int: 16 bits, 4 bytes, -2147483648 ~ 2147483647\nint integer_name;\ninteger_name = 123;  // uninitialized\n\nint integer_name = 123;  // C-like initialization\n\nint integer_name (123);  // Constructor initialization\n\nint age {123};  // C++11 list initialization syntax\n\n// long/long int: 32 bits, 4 bytes, -2147483648 ~ 2147483647 bytes\nlong long_name;\nlong_name = 123;\n\nlong int long_name;\nlong_name = 123;\n\n// similar to the rest of int variable declaration\n\n// long long/long long int: 64 bits, 8 bytes, -9223372036854775808 ~ 9223372036854775807\nlong long long_name;\nlong_name = 123;\n\nlong long int long_name; long_name = 123;\n\n// similar to the rest of int variable declaration\n```\n\n[back to top](#table-of-contents)\n\n## Variable declaration float\n\n- float, double\n\n### python 2 \u0026 3\n\n```python\nfloat_name = 1.123\nfloat_name = 0.1123e1  # equals to 1.123\nfloat_name = 0.1123E1  # equals to 1.123\nfloat_name = 1123e-3  # equals to 1.123\nfloat_name = 1123E-3  # equals to 1.123\n```\n\n- float have inaccurate values\n\n```python\nprint(.1 + .2 + .3)  # 0.6000000000000001\n# use the decimal library to make it accurate\nfrom decimal import *\n\n# do not do this\nDecimal(.1) + Decimal(.2) + Decimal(.3)  # Decimal('0.6000000000000000055511151231')\n\n# do this: convert float to a string first\nx = Decimal(\".1\") + Decimal(\".2\") + Decimal(\".3\")  # Decimal('0.6')\nf\"{x}\"  # \"0.6\nprint(type(x))  # \u003cclass 'decimal.Decimal'\u003e\n```\n\n### javascript ES5\n\n```javascript\nvar float_name = 1.123;\n```\n\n### javascript ES6\n\n```javascript\nlet float_name = 1.123;\nconst float_name = 1.123;\n```\n\n### typescript\n\n```typescript\nlet float_name: number = 1.123;\n```\n\n### ruby\n\n### java:\n\n```java\n// float: 32 bits, 4 bytes\nfloat float_name = 1.123f;  // 1.123, have 7 decimal digits\nfloat float_name = (float) 1.123;\n\n// double: 64 bits, 8 bytes\ndouble double_name = 1.123d;  // 1.123, have 16 decimal digits\ndouble double_name = 1.123;\n\n// using BigDecimal math class\nimport java.math.BigDecimal;\n\npublic class Main {\n\n  public static void main(String[] args) {\n    double value = .012;\n    double pSum = value + value + value;\n    System.out.println(pSum);  // 0.036000000000000004\n\n    String strValue = Double.toString(value);\n    System.out.println(strValue);  // 0.012\n\n    BigDecimal bigValue1 = new BigDecimal(value);\n    BigDecimal bSum1 = bigValue1.add(bigValue1).add(bigValue1);\n    System.out.println(bSum1.toString());  // 0.0360000000000000007494005416219806647859513759613037109375\n\n    BigDecimal bigValue2 = new BigDecimal(strValue);\n    BigDecimal bSum2 = bigValue2.add(bigValue2).add(bigValue2);\n    System.out.println(bSum2.toString());  // 0.036\n  }\n}\n\n```\n\n### c#\n\n```c#\n// float: 32 bit max value with 7 decimals of precision 3.402823E+38\nfloat floatName1 = 1.123f;  // type Single\nfloat floatName2 = float.MaxValue;  // 3.402823E+38\nSystem.Single floatName3 = 1.123f;\n\n// double: 64 bit max value with 15 decimals of precision 1.79769313486232E+308\ndouble doubleName1 = 1.123d;  // type Double\ndouble doubleName2 = 1.123;  // all floats are double by default\ndouble doubleName3 = double.MaxValue;  // 1.79769313486232E+308\nSystem.Double doubleName4 = 1.123;\n```\n\n### c++\n\n```c++\n// float: 4 bytes\nfloat float_name;\nfloat_name = 1.123;  // have 7 decimal digits\n\n// similar to the rest of int variable declaration\n\n// double: 8 bytes\ndouble double_name;\ndouble_name = 1.123;  // have 15 decimal digits\n\n// similar to the rest of int variable declaration\n\n// long double: 12 bytes\nlong double double_name;\ndouble_name = 1.123;  // have 19 decimal digits\n\n// similar to the rest of int variable declaration\n```\n\n[back to top](#table-of-contents)\n\n## Variable declaration None\n\n### python 2 \u0026 3\n\n```python\nvariable_name = None\n\n# nan in python\nimport math\nmath.inf - math.inf  # nan\n```\n\n### javascript\n\n```javascript\n// undefined is reserved for variables whose values have not yet been set.\nlet variable_name; // undefined\n\n//null is reserved for variables whose values are explicitly nothing — instead of just “not yet defined.”\nlet variable_name2 = null;\n\n// NaN is a special numeric value meaning “Not a Number”\nlet variable_name3 = NaN;\n```\n\n### typescript\n\n```typescript\nlet variable_name: void = undefined; // method 1\nlet variable_name2 = undefined; // method 2\nlet variable_name: undefined; // method 3\n\nlet variable_name2: void = null;\nlet variable_name3: number = NaN;\n```\n\n### ruby\n\n```ruby\nvariable_name = nil  # nil is returned when no values are assigned, but nothing is displayed on screen\n```\n\n### java\n\n```java\nString stringName = null;\n\n// NaN is produced if a floating point operation\nfloat floatName = Float.NaN;  // NaN\ndouble doubleName = Double.NaN;  // NaN\n\nDouble x = new Double(-2.0/0.0);  // -Infinity\nDouble y = new Double(0.0/0.0);  // NaN\nx.isNaN();  // false\ny.isNaN();  // true\n\nSystem.out.println(2.0 / 0);  // Infinity\n\n// set infinity value\ndouble inf = Double.POSITIVE_INFINITY;  // Infinity\ndouble inf = Double.NEGATIVE_INFINITY;  // -Infinty\n```\n\n### c#\n\n```c#\nstring stringName = null;\nstring stringName2 = String.Empty;\n\n// method 1: use the nullable method\nNullable\u003cint\u003e integerName1 = null;\n\n// method 2: value type requires ? during declaration\nint? integerName2 = null;\n```\n\n### c++\n\n```c++\n#include \u003ciostream\u003e\n\nint main() {\n    int* raw = nullptr;  // explicit \"no object\"\n    if (raw == nullptr) std::cout \u003c\u003c \"raw is null\\n\";\n}\n```\n\n[back to top](#table-of-contents)\n\n## Strings\n\n### python 2 \u0026 3\n\n```python\nstring_name = \"string\"\nstring_name = 'string'\n# back slash not required, but will produce a new line if not given\nstring_name = \"\"\"multi-line \\\nstring\\\n\"\"\"\n\n# raw strings (ignore escape characters)\nstring_name = r\"\\n raw string\"  # \"\\n raw string\"\n\nlen(string_name)  # 6\n\n# Character unicode point\n# only accepts 1 character\nord(\"b\")  # 98\n\n# reverse string\nstring_name = string_name[::-1]  # \"gnirts\"\n\nstring_name = \"Gnirts\"\nstring_name = string_name.swapcase()  # \"gNIRTS\"\nstring_name = string_name.upper()  # \"GNIRTS\"\nstring_name = string_name.lower()  # \"gnirts\"\n\n# casefold: it is more aggressive than lower(), it removes all case distinctions even in unicode\nstring_name_casefold = \"Hello World ß\"\nstring_name_casefold.casefold()  # \"hello world ss\"\n\n# capitalize string\nstring_name_caps = \"test me\"\nstring_name_caps.title()  # \"Test Me\"\nstring_name_caps.capitalize()  # \"Test me\"\n\n# Replace string in string, string_name.replace(old, new, max)\nstring_name = string_name.replace(\"g\", \"xxx\")  # \"xxxnirts\"\nstring_name = string_name.replace(\"x\", \"g\", 1)  # \"gxxnirts\"\n\n# Find character or string in string and return the index of the 1st character, return -1 if not found\nstring_name.find(\"x\")  # 1\nstring_name.find(\"v\")  # -1\n\n# string slicing\n# extract characters from a string, from start position to but not including end position\nnew_string_name = string_name[1:4]  # \"xxn\"\n\n# Split strings, string_name.split(separator, max)\nstring_name = string_name.split()  # [\"gxxnirts\"]  only works for string without spaces\nstring_name = \"test string\"\nstring_name1 = string_name.split()  # [\"test\", \"string\"]\nstring_name2 = string_name.split(\"s\")  # [\"te\", \"t \", \"tring\"]\nstring_name3 = string_name.split(\"s\", 1)  # [\"te\", \"t string\"]\n\n# Split string into an array of letters\nstring_name4 = list(string_name)  # ['t', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']\n\n# Remove empty spaces\nstring_name = \"    string    \"\n# remove all left spaces\nstring_name1 = string_name.lstrip()  # \"string    \"\n# remove all right spaces\nstring_name2 = string_name.rstrip()  # \"    string\"\n# remove all spaces\nstring_name3 = string_name.strip()  # \"string\"\n\n# Check if string has alphabet and integer characters\nstring_name3.isalnum()  # False\nstring_name = \"123\"\nstring_name.isalnum()  # True\nstring_name = \"s 123\"\nstring_name.isalnum()  # False\nstring_name = \"s123\"\nstring_name.isalnum()  # True\n\n# Check if string has all alphabet characters\nstring_name3.isalpha()  # True\nstring_name = \"A e\"\nstring_name.isalpha()  # False\nstring_name = \"a2\"\nstring_name.isalpha()  # False\n\n# Check if string has all digit characters\nstring_name = \"123\"\nstring_name.isdigit()  # True\nstring_name = \"12 3\"\nstring_name.isdigit()  # False\nstring_name = \"12d\"\nstring_name.isdigit()  # False\n\n# Join an array of string elements\narr = [\"a\", \"b\"]\n\"_\".join(arr)  # \"a_b\"\n```\n\n### javascript ES5\n\n```javascript\nvar stringName = \"string\";\nvar stringName = \"string\";\n// back slash required\nvar stringName =\n  \"multi-line \\\nstring\";\n\nstringName.length; // 6\n\n// Character unicode point\nstring.charCodeAt(stringIndex);\n\"abc\".charCodeAt(1); // 98\n\n// reverse string\nstringName.split(\"\").reverse().join(\"\"); // \"gnirts\"\n\nstringName = stringName.toUpperCase(); // \"GNIRTS\"\nstringName = stringName.toLowerCase(); // \"gnirts\"\n\n// capitalize string\nstringName = stringName.charAt(0).toUpperCase() + stringName.slice(1); // \"Gnirts\"\n\n// replace 1 string occurance with string, stringName.replace(old, new)\nstringName = stringName.replace(\"G\", \"xxx\"); // \"xxxnirts\"\n\nlet stringName0 = \"test_test_123\";\n// replace all string occurances with string, stringName.replaceAll(old, new)\nstringName0 = stringName0.replaceAll(\"_\", \" \"); // \"test test 123\"\n\n// extract characters from a string, from start position to but not including end position\nnewStringName = stringName.substring(1, 4); // \"xxn\"\n\n// Split string into arrays\nstringName = \"test string\";\nstringName1 = stringName.split(); // [\"test string\"]\nstringName2 = stringName.split(\"\"); // ['t', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']\nstringName3 = stringName.split(\"s\"); // [\"te\", \"t \", \"tring\"]\n```\n\n### javascript ES6 // Almost all of ES5 are included in ES6\n\n```javascript\n// back slash not required, but will produce a new line if not given\nvar stringName = `multi-line \\\nstring`;\nlet stringName = \"string\";\nconst stringName = \"string\";\n\n// raw strings (ignore escape characters)\nString.raw`\\n raw string`; // \"\\n raw string\"\n```\n\n### typescript\n\n```typescript\nlet stringName: string = \"string\";\n\n// declare string and/or other types\nlet strOrNum: string | number;\nstrOrNum = \"abc\";\nstrOrNum = 123; // can be reassigned to a declared type\n```\n\n### ruby\n\n```ruby\nstring_name = \u003c\u003cEOM\nthis is a\n  multi line string\nEOM\nstring_name = \u003c\u003ceom\nthis is a\n  multi line string\neom\nstring_name = 'string'\nstring_name = \"string\"\n\nstring_name.length  # 6\n\nstring_name = string_name.reverse  # \"gnirts\"\n\nstring_name = string_name.upcase  # \"GNIRTS\"\nstring_name = string_name.swapcase  # \"gnirts\"\nstring_name = string_name.swapcase  # \"GNIRTS\"\nstring_name = string_name.downcase  # \"gnirts\"\n\n\nstring_name = string_name.capitalize  # \"Gnirts\"\n\n# replace string in string, string_name.gsub!(/old/, new)\nstring_name = string_name.gsub!(/G/, \"xxx\")  # \"xxxnirts\"\n\n# Split strings into an array\nstring_name = string_name.split(\"i\")  # [\"xxxn\", \"rts\"]\nstring_name = \"string\"\nstring_name = string_name.split(\"\")  # [\"s\", \"t\", \"r\", \"i\", \"n\", \"g\"]\n\n# check if a string exists within a string\nnameExist = \"full name\"\nnameExist.include?(\"name\")  # returns true\n\n# search and count the total number of declared alphabets that exist in the string\nnameExist.count(\"l\")  # returns 2\nnameExist.count(\"ln\")  # (l + l + n) therefore returns 3\n\n# search and count the total number of the opposite of the declared alphabets that exist in the string\nnameExist.count(\"^l\")  # returns everything except \"l\", therefore returns 7\n\n# check if a string that starts with the declared string exists\nnameExist.start_with?(\"ful\")  # returns true\nnameExist.start_with?(\"nam\")  # returns false\n\n# find the index of a searched string, returns the index of the first searched letter\nnameExist.index(\"ll\")  # returns 2\n\n# remove empty spaces from string\nremoveStr = \"   string   \"\nremoveStr.lstrip  # \"string   \"\nremoveStr.rstrip  # \"   string\"\nremoveStr.strip  # \"string\"\n\n# format string\nmoveString = \"string\"\nmoveString.rjust(10, \".\")  # \"....string\"\nmoveString.ljust(10, \".\")  # \"string....\"\nmoveString.center(10, \".\")  # \"..string..\"\n\n# Slice end of string\nnewStr = \"string\"\nnewStr.chop  # \"strin\"\n# state the last letters to remove from string\nnewStr.chomp(\"ng\")  # \"stri\"\n\n# remove all listed letters from string\nremoveStr = \"sstring\"\nremoveStr.delete(\"si\")  # \"trng\"\n\n# SYMBOLS: strings that are immutable, must use letters or underscores (_)\n# used mainly for memory conservation or speed string comparison\n# use a symbol if need a string to be immutable and not need to access string methods\n# commonly used in hashed for keys\nvariable_name = :symbolStringWithoutQuotes\nputs variable_name  # symbolStringWithoutQuotes\n```\n\n### java\n\n```java\n// character: 16 bits, 2 bytes, only 1 letter or symbol, must use single quotes ''\nchar charName1 = 'a';\nchar charName2 = '\\u0061';  // unicode character for the letter a\n\n// modify character cases\nCharacter.toUpperCase(charName1);  // 'A'\nCharacter.toLowerCase(charName1);  // 'a'\n\n// convert Char Array to a string\nchar[] chars = {'H', 'e', 'l', 'l', 'o'};\nString s = new String(chars);  // \"Hello\"\n\n// convert string to char array\nchar[] chars2 = s.toCharArray();\nfor (char c : chars2) {  // for each loop\n  System.out.print(c);  // \"Hello\"\n}\n\n// convert primitive values to string\nint intValue = 42;\nString fromInt = Integer.toString(intValue);  // \"42\"\n\nboolean boolValue = true;\nString fromBool = Boolean.toString(boolValue);  // \"true\"\n\n\n// strings: must use double quotes \"\"\nString stringName = new String(\"Hello\");  // method 1\nString stringName1 = \"string\";  // method 2\nString stringName2 = \"multi-line \" +\n                     \"string\";\n\n\n// get character of string with index\nchar indexChar = stringName1.charAt(0);  // 's'\n\n\n// modify string cases\nString stringName3 = stringName1.toUpperCase();  // \"STRING\"\nString stringName4 = stringName3.toLowerCase();  // \"string\"\n\n\n// get length of string\nstringName4.length();  // 6\n\n// get index of substring\nint index = stringName4.indexOf(\"ng\");  // 4\n\n// get substring with index\nString sub1 = stringName4.substring(4);  // \"ng\"\nString sub2 = stringName4.substring(4, 6);  // \"ng\" from starting index to but exclude last index\n\n// trim whitespaces from beginning and ending of string\nString trimStr = \"  test  \";\nString newStr = trimStr.trim();  // \"test\"\n\n\n// toString method: convert primitive numeric values to string\ndouble doubleValue = .5d;\nString stringName5 = Double.toString(doubleValue);  // \"0.5\"\n\n// comparing strings\nString str1 = \"Hello\";  // object 1\nString str2 = \"Hello\";  // str2 points to str1, thus is still object 1\nstr1 == str2;  // true\n\nString part1 = \"Hello \";\nString part2 = \"World\";\nString str3 = part1 + part2;  // object 1\nString str4 = \"Hello World\";  // object 2\nstr3 == str4;  // false\n// need to use .equals()\nstr3.equals(str4);  // true\n```\n\n### c#\n\n- Strings (immutable)\n  - each operation that appears to be modifying a string is actually creating a new string\n  - modifying a string repeatedly can cause a significant performance penalty\n  - when to use string\n    - when number of changes that your app will make to a string is small\n      - string builder might offer negligible or no performance improvement\n    - when performing a fixed number of concatenation operations is required\n      - compiler might combine the concatenation operations into a single operation\n    - when performing extensive search operations while building a string is required\n      - string builder lacks search methods (IndexOf, StartsWith)\n      - thus will need to convert string builder to a string for these operations\n      - this can negate the performance benefit from using string builder\n\n```c#\n// character: 16 bits\nchar charName1 = 'a';  // type Char\nchar charName2 = '\\u0061';  // unicode character for the letter a\nSystem.Char charName3 = 'a';\n\n// strings\nstring stringName = \"string\";  // type String\nSystem.String stringName2 = \"string\";\n\n// multiline strings\n// method 1\nstring multilineString1 = \"multi-line\\n\"\n+ \"string\";\n// method 2\nstring multilineString2 = @\"multi-line\nstring\";\n// method 3\nstring multilineString3 = System.String.Join(\n  System.Environment.NewLine,\n  \"multi-line\",\n  \"string\"\n);\n\n\n// raw strings (ignore escape characters\nstring rawString = @\"\\n raw string\";  // \"\\n raw string\"\n\n\n// check if string is empty\nString.IsNullOrEmpty(stringName);  // False\nString.IsNullOrEmpty(\"\");  // True\n\n// check for white space or empty\nString.IsNullOrWhiteSpace(stringName); // False\nString.IsNullOrWhiteSpace(\"  \"); // True\nString.IsNullOrWhiteSpace(\"\"); // True\nString.IsNullOrWhiteSpace(\" test \"); // False\n\n\n// get length of a string\nstringName.Length;  // 6\n\n\n// get index of the 1st character or word in a string\nstringName.IndexOf(\"s\");  // 0\nstringName.IndexOf(\"unknown\");  // -1\n\n\n// convert string to uppercase\nstringName.ToUpper();  // \"STRING\"\n\n\n// convert string to lowercase\nstringName.ToLower();  // \"string\"\n\n\n// split string to an array of characters\nstringName.ToCharArray();  // ['s', 't', 'r', 'i', 'n', 'g']\n\n\n// split string into an array of strings (must have separator)\nstringName.Split('r');  // [\"st\", \"ing\"]\n\n\n// get substring from a string (if length is not declared, the entire string from startIndex onwards will be returned)\nint startIndex = 0;\nint length = 2;\nstringName.Substring(startIndex, length);  // \"str\"\n\n\n// replace string with another string, stringName.Replace(old, new);\nstringName.Replace(\"test\", \"newTest\");  // \"  newTest  \"\n\n\n// comparing strings\nstring s1 = \"test\";\nstring s2 = \"test\";\nstring s3 = \"test1\".Substring(0, 4);\nobject s4 = s3;\nConsole.WriteLine(\"{0} {1} {2}\", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));  // True True True\nConsole.WriteLine(\"{0} {1} {2}\", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));  // False True True\nConsole.WriteLine(\"{0} {1} {2}\", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));  // False False True\n\n\n// check if a string starts with a character or words\nstring sampleString = \"some random words\";\nsampleString.StartsWith(\"some\");  // True\n\n// check if a string ends with a character or words\nsampleString.EndsWith(\"words\");  // True\n\n\n// remove white spaces from both left and right\nstring stringName3 = \"  test  \";\nstringName3.Trim();  // \"test\"\n// remove white spaces from left\nstringName3.TrimStart();  // \"test  \"\n// remove white spaces from right\nstringName3.TrimEnd();  // \"  test\"\n\n\n// string slicing from start index\n// count is the number of characters to delete from the start index\nint startIndex = 3;\nint count = 3;\nstringName.Remove(startIndex, count);  // \"str\"\nstringName.Remove(startIndex);  // \"str\"\nstringName.Remove(startIndex, 2);  // \"strg\"\n```\n\n- String builder (muttable)\n  - maintains a buffer to accommodate expansions to the string\n  - new data is appended to the buffer if room is available\n    - otherwise, a larger buffer is allocated\n    - data from the original buffer is copied to the new buffer\n    - then the new data is appended to the new buffer\n  - when to use string builder\n    - when expecting an unknown number of changes to a string at design time (when using a loop to concatenate a random number of strings that contain user input)\n    - when expecting to make a significant number of changes to a string\n\n```c#\n// Declaration\n// method 1\nSystem.Text.StringBuilder builder = new System.Text.StringBuilder();  // ''\n// method 2\nusing System.Text;  // import the prefix\nvar builder2 = new StringBuilder();  // ''\n// method 3\nvar builder3 = new StringBuilder(\"starting string\");  // \"starting string\"\n\n\n// check if string builder is empty\n// method 1\nif (builder == 0) System.Console.WriteLine(\"true\");  // \"true\"\n// method 2\nif (System.String.IsNullOrEmpty(builder.ToString()))\n  System.Console.WriteLine(\"true\");  // \"true\"\n\n\n// append an array of similar characters\nbuilder.Append('-', 3);  // \"---\"\n\n// append a new line in string\nbuilder.AppendLine();  // new line is counted as 1 character\n\n// append a string\nbuilder.Append(\"Header\");\n/*\n\"---\nHeader\"\n*/\n\n\n// replace a character with a new character or a string with new string\nbuilder.Replace('-', '+');\nbuilder.Replace(\"er\", \"ing\");\n/*\n\"+++\nHeading\"\n*/\n\n\n// remove characters from startIndex for totalCharacters\nint startIndex = 0;\nint totalCharacters = 3;\nbuilder.Remove(startIndex, totalCharacters);\n/*\n\"\nHeading\"\n*/\n\n\n// insert an array of similar characters at index\nbuilder.Insert(startIndex, new string('+', 4));\n/*\n\"++++\nHeading\"\n*/\n\n\n// get character of string builder at index\nbuilder[0];  // '+'\n```\n\n### c++\n\ncharacter: only have 1 character, must use single quotes ''\n```c++\nchar charName;\ncharName = 'a';\n\nchar charName = 'a';\nchar charName ('a');\nchar charName {'a'};\n\nchar charName = \"A\";  // error: invalid conversion from 'const char*' to 'char' [-fpermissive]\nchar charName = 'AB';  // warning: multi-character character constant [-Wmultichar] error\n\n#include \u003ciostream\u003e\nsigned char sc = -1;\nstd::cout \u003c\u003c sc;  // �\nstd::cout \u003c\u003c int(sc);  // -1\n\nunsigned char uc = 255;\ncout \u003c\u003c uc;  // �\ncout \u003c\u003c int(uc);  // 255\n\nchar16_t u = u'字';\nchar32_t U = U'𐀀';\nchar8_t e = u8'é';\n\n```\nstrings\n- C-style strings: an ARRAY of characters, must use double quotes \"\"\n    - THIS IS NOT A TRUE STRING, IT IS AN ARRAY OF CHARACTERS!!!!!!!\n```c++\nchar * stringName = \"string\";\nconst char * stringName = \"string\";  // const is normally used\nchar stringName[] = \"string\";  // creates array of 7 chars, last char is null \"\\0\"\nchar stringName[7] = \"string\";  // need give 7 slots for chars and null char\nchar stringName[7] = {'s', 't', 'r', 'i', 'n', 'g', 0};  // no 0 = error\nchar stringName[7] = {'s', 't', 'r', 'i', 'n', 'g', '\\0'};  // no '\\0' = error\n\n// C++ strings: must add at the top \"#include＜string＞\", must use double quotes \"\"\n#include＜string＞\nstd::string stringName;\nstringName = \"string\";\n\n// back slash not required, but can use if want to\nstd::string stringName = \"multi-line\"\n                         \"string\";\nstd::string stringName (\"string\");\n```\n\n[back to top](#table-of-contents)\n\n## Boolean\n\n### python 2 \u0026 3\n\n```python\nboolean_name = True\nboolean_name = False\nnot True  # False\nnot False  # True\n```\n\n### javascript ES5\n\n```javascript\nvar boolean_name;\nboolean_name = true;\nvar boolean_name = false;\n!true; // false\n!false; // true\n```\n\n- truthy: \"xxx\", 1, -1, 2.5, true\n- falsey: false, 0, \"\", null, undefined, NaN\n\n### javascript ES6\n\n```javascript\nlet boolean_name;\nboolean_name = true;\nlet boolean_name = false;\nconst boolean_name = true;\n```\n\n### typescript\n\n```typescript\nlet isDone: boolean = false;\n```\n\n### ruby\n\n```ruby\nboolean_name = true\nboolean_name = false\n```\n\n- truthy: true, 0, 1, -1, \"\",\n- falsey: false, nil\n- Check if method exist\n  - obj.respond_to?(:method)\n    - example 1\n      \u003e [1, 2, 3].respond_to?(:push) # true\n    - example 2\n      \u003e 123.respond_to?(:next) # true\n    - example 3: false because array can't be turned into a symbol\n      \u003e [1, 2, 3].respond_to?(:to_sym) # false\n\n### java\n\n```java\nboolean booleanName1 = true;\nboolean booleanName2 = false;\nboolean booleanName3 = !booleanName2;  // true\n\nString sBoolean = \"true\";\nboolean booleanName4 = Boolean.parseBoolean(sBoolean);  // true\n```\n\n### c#\n\n```c#\ntype Boolean\nbool booleanName = true;  // displayed as True when printed\nbool booleanName = false;  // displayed as False when printed\nSystem.Boolean booleanName = false;\n```\n\n### c++: 8 bits\n\n```c++\nbool boolean_name; boolean_name = true;  // produces a 1 output\nbool boolean_name = false;  // produces a 0 output\nbool boolean_name (true);\nbool boolean_name {false};\n```\n\n[back to top](#table-of-contents)\n\n## Arithmetic Operators\n\n### python 2\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `3.0/2  # output 1.5, 3/2 output 1`\n- modulus: `%`\n- exponent: `**`\n- floor division: `3//2  # output 1`\n\n### python 3\n\n- division: `3/2  # output 1.5`\n- floor division: `3//2  # output 1`\n\n### javascript\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `3/2  // output 1.5`\n- modulus: `%`\n- exponent: `**`\n- floor division: `Math.floor(3/2)  // output 1`\n\n### ruby\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `3.0/2  # output 1.5, 3/2 output 1`\n- modulus: `%`\n- exponent: `**`\n- floor division: `3/2.floor`\n\n### java\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `double double_name = 3.0/2;  // output 1.5, 3/2 output 1`\n- modulus: `%`\n- exponent: `Math.pow(3, 2);  // output 9`\n- floor division: `int integer_name = 3/2;  // output 1`\n\n### c#\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `3.0/2;  // output 1.5, 3/2 output 1`\n- modulus: `%`\n- exponent: `Math.Pow(3, 2);  // output 9`\n- floor division: `3/2;  // output 1`\n\n### c++\n\n- addition: `+`\n- subtraction: `-`\n- multiplication: `*`\n- division: `double double_name = 3.0/2  // output 1.5, 3/2 output 1`\n- modulus: `%`\n- exponent:\n  - must add this to the top `#include＜cmath＞`\n  - `int integer_name = pow(3, 2);  // output 9`\n- floor division: `3/2  // output 1`\n\n[back to top](#table-of-contents)\n\n## Comparison Operators\n\n### python 2 \u0026 3\n\n- `==` condition is True if both operand have equal contents\n\n```python\nlist1 = []\nlist2 = []\nlist1 == list2  # True\n```\n\n- `is` condition is True if both operand points to the same identical object\n\n```python\nlist1 = []\nlist2 = []\nlist1 is list2  # False\n\nlist1 = None\nlist2 = None\nlist1 is list2  # True\n```\n\n- `!=` condition is True if both operand do not have equal contents\n- `is not` condition is True if both operand do not points to the same identical object\n- `\u003c\u003e` py2 only, condition is True if both operands do not equal contents\n- `\u003e` condition is True if right operand is less than left operand\n- `\u003c` condition is True if left operand is less than right operand\n- `\u003e=` condition is True if right operand is less than or equal to left operand\n- `\u003c=` condition is True is left operand is less than or equal to right operand\n\n### javascript\n\n- `==` not type-safe, e.g.: string or int will be automatically converted before comparison, only checks the value\n\n```javascript\nvar x = 5;\nx == 5; // is true\nx == \"5\"; // is also true\n```\n\n- `===` string or int will NOT be converted before comparison, checks both the value and type\n  - NaN and NaN comparison are not equal\n  - +0 and -0 are equal\n\n```javascript\nvar x = 5;\nx === 5; // is true\nx === \"5\"; // is false\n```\n\n- `Object.is(var1, var2);` similar to `===`\n  - NaN and NaN comparison are equal\n  - +0 and -0 are not equal\n- `!=`\n- `!==`\n- `\u003e`\n- `\u003c`\n- `\u003e=`\n- `\u003c=`\n- `??` Nullish coalescing operator: returns right-hand side operand when left-hand side operand is null or undefined, and otherwise returns its left-hand side operand\n\n```javascript\nconst foo = null ?? \"default string\";\nconsole.log(foo);\n// expected output: \"default string\"\n\nconst baz = 0 ?? 42;\nconsole.log(baz);\n// expected output: 0\n```\n\n### ruby\n\n- `==`\n- `!=`\n- `\u003e`\n- `\u003c`\n- `\u003e=`\n- `\u003c=`\n- `\u003c=\u003e` Combined Comparison Operator\n- `object1.equal?object2`\n\n```ruby\nstring1 = \"string\"\nstring2 = \"string\"\nstring1 == string2  # returns true\nstring1.equal?string2  # returns false\nstring1.equal?string1  # returns true\n\nnum1 = 2\nnum2 = 5\nputs num1 \u003c=\u003e num2  # -1\nputs num2 \u003c=\u003e num1  # 1\nnum1 = 3\nnum2 = 3\nputs num1 \u003c=\u003e num2 # 0\n\nstring1 = \"b\"  # looks at only the 1st letter, \"bz\" will not change the outcome, unless both strings start with the same 1st letter\nstring2 = \"e\"\nputs string1 \u003c=\u003e string2  # -1\nputs string2 \u003c=\u003e string1  # 1\nstring1 = \"c\"\nstring2 = \"c\"\nputs string1 \u003c=\u003e string2  # 0\n```\n\n### java\n\n- `==`\n  - reference comparison\n  ```java\n  String s1 = new String(\"string value\");\n  String s2 = new String(\"string value\");\n  System.out.println(s1 == s2);  // false\n  ```\n  - use equals method to compare string values\n  ```java\n  String s1 = new String(\"string value\");\n  String s2 = new String(\"string value\");\n  System.out.println(s1.equals(s2));  // true\n  ```\n- `!=`\n- `\u003e`\n- `\u003c`\n- `\u003e=`\n- `\u003c=`\n- `instanceof` class membership\n\n```java\nString s = \"Hello\";\nif (s instanceof java.lang.String) {\n  System.out.println(true);\n}\n```\n\n### c#\n\n- `==`\n- `!=`\n- `\u003e`\n- `\u003c`\n- `\u003e=`\n- `\u003c=`\n\n### c++\n\n- `==`\n- `!=`\n- `\u003e`\n- `\u003c`\n- `\u003e=`\n- `\u003c=`\n\n[back to top](#table-of-contents)\n\n## Logical Operators\n\n### python 2 \u0026 3\n\n- `and`\n- `or`\n- `not`\n\n### javascript\n\n- `\u0026\u0026` and\n- `||` or\n- `!` not\n- truthy and falsey examples\n  - `truthy1 \u0026\u0026 truthy2` truthy2\n  - `falsey \u0026\u0026 truthy` falsey\n  - `truthy \u0026\u0026 falsey` falsey\n  - `falsey1 \u0026\u0026 falsey2` falsey1\n  - `truthy1 || truthy2` truthy1\n  - `truthy || falsey` truthy\n  - `falsey1 || falsey2` falsey2\n\n### ruby\n\n- `\u0026\u0026` and\n- `||` or\n- `!` not\n\n### java\n\n- `\u0026\u0026` and\n- `||` or\n- `^` exclusive or\n- `!` not\n\n### c#\n\n- `\u0026\u0026` and\n- `||` or\n- `^` exclusive or\n- `!` not\n\n### c++\n\n- `\u0026\u0026` and\n- `||` or\n- `!` not\n\n[back to top](#table-of-contents)\n\n## Getting Input\n\n### python 2\n\n```python\nraw_input(\"What's your name?\")\n\n# input must be the same data type as xxx else return an error\ninput(xxx)\n```\n\n### python 3\n\n```python\ninput(\"What's your name?\")\n```\n\n### javascript\n\n```javascript\n// install readline-sync package locally via npm i readline-sync\nvar readlineSync = require(\"readline-sync\"); // import package\nvar getInput = readlineSync.question(\"What's your name?\");\n```\n\n### ruby\n\n```ruby\n# print question\nprint \"What's your name?\"\n# get input\nname = gets.chomp\n```\n\n### java\n\n- must import scanner library\n\n```java\nimport java.util.Scanner;\n```\n\n```java\n// print question\nSystem.out.println(\"What's your name?\");\n\n// get raw input\nScanner scanner = new Scanner(System.in);\n// convert raw value to string type\n// can read the input only till the space\n// It can't read two words separated by a space\n// places the cursor in the same line after reading the input\nString input = scanner.next();\n// reads input including space between the words till the end of line \\n\n// Once the input is read, positions the cursor in the next line\nString input1 = scanner.nextLine();\n// convert raw value to int type\nInt input2 = scanner.nextInt();\n```\n\n### c#\n\n```c#\n// print question\nSystem.Console.WriteLine(\"What's your name?\");\n// get input\nstring name = System.Console.ReadLine();\n```\n\n### c++\n\n[back to top](#table-of-contents)\n\n## Bitwise Operators\n\n### python 2 \u0026 3\n\n```python\n# Each digit is 1 bit, all bitwise operators converts to signed 32-bit integers, except for zero-fill right shift which results to unsigned 32 bit integer\na = 60  # 60 = ...0011 1100\nb = 13  # 13 = ...0000 1101\nc = 9  # 9 = ...0000 1001\n# \u0026 is binary AND, return 1 if both a and b are 1\na \u0026 b  # 12 = ...0000 1100\n\n# | is binary OR, return 1 if either a and or b HAVE a 1\na | b  # 61 = ...0011 1101\n\n# ^ is binary XOR, return 1 if both a and b are not 1 or 0\na ^ b  # 49 = ...0011 0001\n\n# ~ is binary ones complement, invert everything, 1 change to 0 and vice versa\n~a  # -61 = ...1100 0011\n\n# \u003c\u003c is binary left shift, shift everything to the left by n digit(s)\na \u003c\u003c 2  # 240 = ...1111 0000\n\n# \u003e\u003e is binary right shift, shift everything to the right by n digit(s)\na \u003e\u003e 2  # 15 = ...0000 1111\nc \u003e\u003e 2  # 3 = ...0000 0010, count the 1s\nc = -9  # -9 = ...1111 0111\nc \u003e\u003e 2  # -3 = ...1111 1101, count the 0s\n\n# Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s\ndef zero_fill_right_shift(val, n):\n    return (val \u003e\u003e n) if val \u003e= 0 else ((val + 0x100000000) \u003e\u003e n)\nzero_fill_right_shift(9, 2)  # 2 = ...0000 0010, count the 1s\nc = -9  # -9 = ...1111 0111\nzero_fill_right_shift(-9, 2)  # 1073741821 = 0011...1111 1101, count the 0s\n```\n\n### javascript\n\n```javascript\n// Each digit is 1 bit, all bitwise operators converts to signed 32-bit integers, except for zero-fill right shift which results to unsigned 32 bit integer\nlet a = 60; // 60 = ...0011 1100\nlet b = 13; // 13 = ...0000 1101\nlet c = 9; // 9 = ...0000 1001\n// \u0026 is binary AND, return 1 if both a and b are 1, count the 1s\na \u0026 b; // 12 = ...0000 1100\n\n// | is binary OR, return 1 if either a and or b HAVE a 1\na | b; // 61 = ...0011 1101\n\n// ^ is binary XOR, return 1 if both a and b are not 1 or 0\na ^ b; // 49 = ...0011 0001\n\n// ~ is binary ones complement, invert everything, 1 change to 0 and vice versa, count the 0s\n~a; // -61 = ...1100 0011\n\n// \u003c\u003c is binary left shift, shift everything to the left by n digit(s)\na \u003c\u003c 2; // 240 = ...1111 0000\n\n// \u003e\u003e is Sign-propagating right shift, a binary right shift, shift everything to the right by n digit(s)\na \u003e\u003e 2; // 15 = ...0000 1111\nc \u003e\u003e 2; // 3 = ...0000 0010, count the 1s\nc = -9; // -9 = ...1111 0111\nc \u003e\u003e 2; // -3 = ...1111 1101, count the 0s\n\n// \u003e\u003e\u003e is Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s\nc \u003e\u003e\u003e 2; // 2 = ...0000 0010, count the 1s\nc = -9; // -9 = ...1111 0111\nc \u003e\u003e\u003e 2; // 1073741821 = 0011...1111 1101, count the 0s\n```\n\n### ruby\n\n### java\n\n```java\n// \u0026 is binary AND, return 1 if both a and b are 1, count the 1s\na \u0026 b  // 12 = ...0000 1100\n\n// | is binary OR, return 1 if either a and or b HAVE a 1\na | b  // 61 = ...0011 1101\n\n// ^ is binary XOR, return 1 if both a and b are not 1 or 0\na ^ b  // 49 = ...0011 0001\n\n// ~ is binary ones complement, invert everything, 1 change to 0 and vice versa, count the 0s\n~a  // -61 = ...1100 0011\n\n// \u003c\u003c is binary left shift, shift everything to the left by n digit(s)\na \u003c\u003c 2  // 240 = ...1111 0000\n\n// \u003e\u003e is Sign-propagating right shift, a binary right shift, shift everything to the right by n digit(s)\na \u003e\u003e 2  // 15 = ...0000 1111\nc \u003e\u003e 2  // 3 = ...0000 0010, count the 1s\nc = -9  // -9 = ...1111 0111\nc \u003e\u003e 2  // -3 = ...1111 1101, count the 0s\n\n// \u003e\u003e\u003e is Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s\nc \u003e\u003e\u003e 2  // 2 = ...0000 0010, count the 1s\nc = -9  // -9 = ...1111 0111\nc \u003e\u003e\u003e 2  // 1073741821 = 0011...1111 1101, count the 0s\n```\n\n### c#\n\n```c#\n// \u0026 is binary AND, return 1 if both a and b are 1, count the 1s\na \u0026 b  // 12 = ...0000 1100\n\n// | is binary OR, return 1 if either a and or b HAVE a 1\na | b  // 61 = ...0011 1101\n```\n\n### c++\n\n[back to top](#table-of-contents)\n\n## Increment\n\n### python 2 \u0026 3\n\n- `x = x + 1` increment\n- `x += 1`\n\n### javascript\n\n- `x = x + 1;` add 1 now\n- `x += 1;` add 1 now\n- `++x;` preincrement, add 1 now\n- `x++;` postincrement, display without addition now then add 1 later when called again\n\n### ruby\n\n- `x = x + 1` increment\n- `x += 1`\n\n### java\n\n- `x = x + 1;`\n- `x += 1;`\n- `++x;` preincrement, add 1 now\n- `x++;` postincrement, display without addition now then add 1 later when called again\n\n### c#\n\n- `x = x + 1;`\n- `x += 1;`\n- `++x;` preincrement, add 1 now\n- `x++;` postincrement, display without addition now then add 1 later when called again\n\n### c++\n\n- `x = x + 1;`\n- `x += 1;`\n- `++x;` preincrement, add 1 now\n- `x++;` postincrement, display without addition now then add 1 later when called again\n\n[back to top](#table-of-contents)\n\n## Arrays and Lists\n\n### python 2 \u0026 3\n\n```python\n# Empty list\nlist_name = []\n# List with elements\nlist_name = [1, \"one\", True]\n# Nested lists\nlist_name = [1, [\"two\", 3]]\n\n\n# Find list size\nlen(list_name)\n\n\n# Get index of element, return ValueError if element does not exist\nlist_name.index(element)\n\n\n# Add element to list (left to right)\nlist_name.append(element)\n\n# Add element to list at index\nlist_name.insert(index, element)\n\n# Extends list by appending elements from the iterable\nlist_name = [1, 2]\nlist_name.extend([3, 4])  # [1, 2, 3, 4]\n\n\n# Access an element\nlist_name[index]\n\n# Modify an element\nlist_name[index] = element\n\n\n# Remove element from list (right to left)\nlist_name.pop()\n\n# Remove element from list at index\nlist_name.pop(index)\n\n# Remove any element from list at element\nlist_name.remove(element)\n\n# Method 1: remove all elements\ndel list_name[:]\n# Method 2: remove all elements\nlist_name = []\n# Method 3: remove all elements, only in python 3\nlist_name.clear()\n\n\nSlice notation\n# items start through stop-1\nlist_name[start:stop]\n\n# items start through the rest of the array\nlist_name[start:]\n\n# items from the beginning through stop-1\nlist_name[:stop]\n\n# a copy of the whole array\nlist_name[:]\n\n# start through not past stop, by step\nlist_name[start:stop:step]\nlist_name = [1, 2, 3, 4, 5]\nlist_name[::2]  # [1, 3, 5]\n\n# last item in the array\nlist_name[-1]\n\n# last two items in the array\nlist_name[-2:]\n\n# everything except the last two items\nlist_name[:-2]\n\n# all items in the array, reversed\nlist_name[::-1]\n\n# the first two items, reversed\nlist_name[1::-1]\n\n# the last two items, reversed\nlist_name[:-3:-1]\n\n# everything except the last two items, reversed\nlist_name[-3::-1]\n\n\n# Reverse an array\nlist_name.reverse()\n\n\n# Merge 2 or more arrays together\nnew_list = list_name + list_name2\n\n\n# Sort an array in ascending order\nlist_name = [2, 3, 1, 4]\n# method 1\nlist_name2 = sorted(list_name)  # [1, 2, 3, 4]\n# method 2\nlist_name.sort()  # [1, 2, 3, 4]\n\n# sort an array of dictionaries in ascending order\ndict_name = [{\"key_name\": value1}, {\"key_name\": value2}]\n# sort by value\ndict_name2 = sorted(dict_name, key=lambda k: k[\"key_name\"])\n\n\n# Sort an array in descending order\n# method 1\nlist_name2 = sorted(list_name2, reverse=True)  # [4, 3, 2, 1]\n# method 2\nlist_name.sort(reverse=True)  # [4, 3, 2, 1]\n\n# sort an array of dictionaries in descending order\n# sort by value\ndict_name2 = sorted(dict_name, key=lambda k: k[\"key_name\"], reverse=True)\n\n# Join array into a string\nlist_name = [\"a\", \"b\", \"c\"]\nx = \", \".join(list_name)\nprint(x)  # \"a, b, c\"\n\n# Split string into an array\ny = x.split(\", \")\nprint(y)  # ['a', 'b', 'c']\n\n```\n\n### javascript\n\n```javascript\n// Method 1: empty list\nvar list_name = [];\n// Method 2: empty list\nvar list_name = new Array();\n// create list of empty elements\nvar list_name = new Array(3); // [undefined, undefined, undefined]\nvar list_name = Array.from({ length: 3});  // [undefined, undefined, undefined]\n// List with elements\nvar list_name = [1, \"one\", true];\nvar list_name = new Array(3).fill(\"-\") // [\"-\", \"-\", \"-\"]\n// Nested lists\nvar list_name = [1, [\"two\", 3]];\nvar list_name = new Array(3).fill(new Array(2).fill(\"-\")) // [[\"-\", \"-\"], [\"-\", \"-\"], [\"-\", \"-\"]]\n\n\n// Modify an element\nlist_name[index] = element;\n\n// Access an element\nlist_name[index];\n\n\n// Remove element from list (right to left)\nlist_name.pop();\n// Remove element from list (left to right)\nlist_name.shift();\n// Remove number of elements (left to right) from index and insert new elements (left to right)\nlist_name.splice(index, number_of_element);\n\n\n// Add element to list (left to right)\nlist_name.push(element);\n// Add element to list (right to left)\nlist_name.unshift(element);\n// Add element to list at index (left to right)\nlist_name.splice(index, 0, new_element1, new_element2...);\n// Add \u0026 Remove elements to \u0026 from list at index (left to right)\nlist_name.splice(index, number_of_element, new_element1, new_element2...);\n\n\n// Return the selected elements in an array, as a new array object\nlist_name.slice();\n// Return the elements starting at the given 1st argument,\n// and ends at, but does not include, the given 2nd argument\nlist_name.slice(1, 3);\nlist_name.slice(1);  // if 1 argument is given, return all elements from array from the 1st argument index\n\n\n// Find list size\nlist_name.length;\n// Remove all elements\nlist_name = [];\n\n\n// Merge 2 or more arrays together\nlist_name1 = [1, 2, 3];\nlist_name2 = [4, 5, 6];\nnew_list = list_name1.concat(list_name2);\n\n\n// Get index of element, return -1 if not present\nlist_name = [\"element1\", \"element2\", \"element1\"]\nlist_name.indexOf(\"element1\")  // returns index of 0\nlist_name.indexOf(\"element1\", 1);  // returns index of 2\nlist_name.indexOf(\"element1\", 2);  // also returns index of 2\nlist_name.indexOf(\"element1\", 0);  // returns index of 0\n\n\n// Sort array in ascending order\nlist_name = [2, 3, 1, 4];\nlist_name.sort();  // [1, 2, 3, 4]  work only only positive integers and strings\n\nlist_name = [2, -1, 4, 3];\nlist_name.sort((a, b) =\u003e a - b);  // [ -1, 2, 3, 4 ] work for negative and positive integers\n\n// Sort array in descending order\nlist_name.sort((a, b) =\u003e (b - a));  // [4, 3, 2, 1] work for negative and positive integers\nlist_nameStr = [\"b\", \"a\", \"c\"];\n// method 1: most optimal\nlist_nameStr.sort().reverse(); // [\"c\", \"b\", \"a\"]\n// method 2\nlist_nameStr.sort((a, b) =\u003e (a \u003e b ? -1 : 1));\n// method 3\nlist_nameStr.sort((a, b) =\u003e b.localeCompare(a));\n\n\n// Determine whether an array contains a specified element\nlist_name = [\"a\", \"b\", \"c\", \"a\"]\nconsole.log(list_name.includes(\"b\"))  // true\n\n// Determine whether an array contains a specified element from starting index\nconsole.log(list_name.includes(\"b\", 2)  // false\nconsole.log(list_name.includes(\"a\", 2)  // true\n\n// Flatten nested arrays\nlist_name = [1, 2, [3, 4]];\nlist_name.flat() // [1, 2, 3, 4]\n\n// Check if all elements in array pass the conditional check\nfunction helper(currentValue) {\n return currentValue \u003c 3;\n}\nlist_name = [1, 2, 3, 4];\nlist_name.every(helper); // false\nlist_name = [1, 2];\nlist_name.every(helper); // true\n```\n\n### typescript\n\n```typescript\n// method 1\nlet numArr: number[] = [1, 2, 3];\nlet strArr: string[] = [\"a\", \"bc\", \"def\"];\n\n// method 2\nlet numArr2: Array\u003cnumber\u003e = [1, 2, 3];\nlet strArr2: Array\u003cstring\u003e = [\"a\", \"bc\", \"def\"];\n\n// declare more than 1 type\n// with tuples\nlet strOrNumArr1: [string, number] = [\"a\", 1]; // must follow and limited to declared format\n// with union\nlet strOrNumArr2: (string | number)[]; // allows unlimited mixture of number and/or string values in 1 array\n```\n\n### ruby\n\n```ruby\n# Empty list\nlist_name = []  # method 1\nlist_name = Array.new  # method 2\n# List with elements\nlist_name = [1, \"one\", True]\nlist_name = Array.new(3)  # creates 3 slots of nil in array [nil, nil, nil]\nlist_name = Array.new(3, \"new\")  # creates 3 slots of object in array [\"new\", \"new\", \"new\"]\n# Nested lists\nlist_name = [1, [\"two\", 3]]\n\n# join elements in array at index into a string (to join all elements, all indexes must be listed)\nlist_name.values_at(0, 1).join(\", \")  # \"1, two, 3\"\n\n# join all elements in array into a string\nlist_name.join(\", \")  # \"1, two, 3\"\n\n# Add element to list (left to right)\n# method 1\nlist_name.push(element);\n# method 2\nlist_name \u003c\u003c element;\n\n# Add element to list (right to left)\nlist_name.unshift(\"new\")  # [\"new\", 1, [\"two\", 3]]\n\n# delete element from list (right to left)\nlist_name.pop()  # [\"new\", 1]\n\n# delete element from list (left to right)\nlist_name.shift()  # [1]\n\n# concat 2 arrays\n# method 1\n[1] + [2]  # [1, 2]\n# method 2\n[1].concat([2])  # [1, 2]\n\n# find length of array\n[1, 2].size  # 2\n\n# check if element exist in array\n[1, 2].include?(1)  # true\n\n# count how many similar elements are in the array\n[1, 2, 1].count(1)  # 2\n\n# check if array is empty\n[1, 2].empty?  # false\n\n# Add 0 to 10 to an array\n(0..10).to_a  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# Add 0 to 10 excluding 10 to an array\n(0...10).to_a  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# Access an elment\nlist_name[index]\n\n# Sort an array in ascending\nlist_name = [3, 4, 1, 2]\n# method 1\nlist_name1 = list_name.sort  # [1, 2, 3, 4]\n# method 2\nlist_name.sort!  # [1, 2, 3, 4]\n# Reverse sort an array, only works on already sorted array\n# arrays that are not sorted will be reversed without sorting\n# method 1 (modify list_name temporarily)\nlist_name1 = list_name.reverse  # [4, 3, 2, 1]\n# method 2 (directly modify list_name)\nlist_name.reverse!\n\n# Modifies every value in an array\n# (modify list_name temporarily)\n# method 1\nlist_name2 = list_name.collect {|num| num * 2}  # [8, 6, 4, 2]\n# method 2\nlist_name2 = list_name.map {|num| num * 2}  # [8, 6, 4, 2]\n# (directly modify list_name)\n# method 1\nlist_name.collect! {|num| num * 2}  # [8, 6, 4, 2]\n# method 2\nlist_name.map! {|num| num / 2}  # [4, 3, 2, 1]\n```\n\n### java\n\n```java\n// Arrays: can only have 1 data type: string, int, etc.\n// printing this only shows the memory\n// Empty string array of desired array size\nString[] string_array = new String[length_of_desired_array];\n// New string array with elements inside\nString [] string_array = new String [] {string1, string2,...};  // Method 1\nString[] string_array = {string1, string2,...};  // Method 2\n\n// Add string array element, limited to array size\n// Modify string array element value\nstring_array[index] = element;\n\n// Access an element\nstring_array[index];\n\n// Find array size\nstring_array.length;\n\n// Sort array, can sort numbers, strings, etc.\n// must import\n// import java.util.Arrays;\nString[] sourceArr = {\"orange\", \"apple\", \"pear\"};\nArrays.sort(sourceArr);  // {\"apple\", \"orange\", \"pear\"}\n\n// Copy array\nint sourceArrStartingIndex = 1;\nint destinationArrStartingIndex = 0;\nint copiedArrLen = 2;\nString[] copiedArr = new String[copiedArrLen];\nSystem.arraycopy(sourceArr, sourceArrStartingIndex, copiedArr, destinationArrStartingIndex, copiedArrLen);  // {\"apple\", \"pear\"}\n\n// multidimensional array\nString[][] states = new String[3][2];\nstates[0][0] = \"Japan\";\nstates[0][1] = \"Tokyo\";\n\n\n// Arraylists: it is a class, extends the AbstractList class and implements List interface\n// can be instantiated\n// used to create a dynamic array that contains objects\n// creates an array of objects where the array can grow dynamically\n// can only have 1 data type: string, int, etc.\n// import java.util.ArrayList;  // Must import to use\n\n// Empty string arrayList\nArrayList\u003cString\u003e arrayList = new ArrayList\u003cString\u003e();\n\n// Add element to string arrayList (left to right)\narrayList.add(element);\n\n// Modify an element at index\narrayList.set(index, element);\n\n// Access an element\narrayList.get(index);\n\n// Remove element from arrayList at index\narrayList.remove(index);\n\n// Find arrayList size\narrayList.size();\n\n// Remove all elements\narrayList.clear();\n\n\n// List: it is an interface, extends the Collection framework\n// cannot be instantiated\n// used to create a list of elements(objects) which are associated with their index numbers\n// creates a collection of elements that are stored in a sequence and they are identified and accessed using the index\n// print this shows the actual array\n// import java.util.List;  // must import to use\n// import java.util.ArrayList;  // Must import to use\nList\u003cString\u003e list = new ArrayList\u003c\u003e();  // from java 7 onwards redundent \u003cString\u003e is not required, can just use \u003c\u003e\n\n// Add element to string List (left to right)\nlist.add(element);\n\n// Remove element from list at index\nlist.remove(index);\n\n// Access an element\nlist.get(index);\n\n// Find index of an element\nlist.indexOf(element);\n```\n\n### c#\n\n- Arrays: can only have 1 data type: string, int, etc. (size cannot be modified after declaration)\n\n```c#\n// Empty string array of desired array size\nstring[] stringArray = new string[lengthOfDesiredArray];\n// New string array with elements inside\nstring [] stringArray2 = new string [] {string1, string2, ...};  // Method 1, size is determined by number of elements declared\nstring [] stringArray2 = new string [2] {string1, string2};  // Method 2, size is determined by the array size declared\nstring[] stringArray3 = {string1, string2, ...};  // Method 3, size is determined by number of elements declared\nstring[] stringArray5 = new[] {string1, string2, ...};  // Method 4\nvar stringArray6 = new[] {string1, string2, ...};  // Method 5, use var to auto determine data type\n\n// Multi-dimensional Rectangular Arrays\nint[] rectArray = new int[3, 5];\nint[] rectArray2 = new int[3, 5] {\n  {1, 2, 3, 4, 5},\n  {6, 7, 8, 9, 10},\n  {11, 12, 13, 14, 15}\n};\n\n// Multi-dimensional Jagged Arrays\nint[] jaggedArray = new int[3][];  // create an array of 3 empty arrays\njaggedArray[0] = new int[4];  // create an array of size 4\njaggedArray[1] = new int[5];  // create an array of size 5\njaggedArray[2] = new int[3];  // create an array of size 3\n\n// Add string array element, limited to array size\n// Modify string array element value\nstringArray[index] = element;\n\n\n// Access an element\nstringArray[index];\nrectArray2[index1, index2];\njaggedArray[0][0];\n\n\n// Find array size\nstring[] strArr = {\"a\", \"b\", \"c\"};\nstrArr.Length;  // 3\n\n\n// Find index of an element in an array\nstring element = \"a\";\nint index = System.Array.IndexOf(strArr, element);  // 0\n\n\n// Clear the element in the array (0 for int, false for bool, null for other objects), exclude the endIndex value\nint startIndex = 0;\nint endIndex = 1;\nSystem.Array.Clear(strArr, startIndex, endIndex);\n\n\n// Copy the elements into a new array\nint firstFewElem = 3;\nstring[] copiedStrArr = new string[3];\nSystem.Array.Copy(strArr, copiedStrArr, firstFewElem);\n\n\n// Sort (ascending order)\nSystem.Array.Sort(strArr);\n\n\n// Reverse (only works on sorted arrays)\nSystem.Array.Reverse(strArr);  // [\"c\", \"b\", \"a\"]\nSystem.Array.Reverse(strArr);  // [\"a\", \"b\", \"c\"]\n\n\n// Join elements of an array into a string\nSystem.String.Join(\"\", strArr);  // \"abc\"\nSystem.String.Join(\",\", strArr);  // \"a,b,c\"\n```\n\n- List (dynamic array)\n\n```c#\n// Empty int array of desired array size\nSystem.Collections.Generic.List\u003cint\u003e intList = new System.Collections.Generic.List\u003cint\u003e();  // empty list\nSystem.Collections.Generic.List\u003cint\u003e intList2 = new System.Collections.Generic.List\u003cint\u003e() {1, 2, 3, 4};  // list with values\n// import to write less code when declaring\nusing System.Collections.Generic;\nList\u003cint\u003e intList3 = new List\u003cint\u003e();  // empty list\nList\u003cint\u003e intList4 = new List\u003cint\u003e() {1, 2, 3, 4};  // list with values\n\n\n// Add 1 new element to the list (left to right)\nintList4.Add(5);  // [1, 2, 3, 4, 5]\n\n// Add a range of elements to the list with an array\nintList4.AddRange(new int[3] {6, 7, 8});  // [1, 2, 3, 4, 5, 6, 7, 8]\n\n\n// Find index of an element in a list (return -1 if element is not found)\nintList4.IndexOf(2);  // 1\n\n// Find last index of elements with similar values in a list\nint[] intList5 = new List\u003cint\u003e() {1, 2, 1, 3};\nintList5.LastIndexOf(1);  // 2\n\n\n// Get length of list\nintList4.Count;  // 8\n\n\n// Remove an element at element in list\nintList4.Remove(2);  // [1, 3, 4, 5, 6, 7, 8]\n\n\n// Remove an element at index of list\nintList4.RemoveAt(0);  // [3, 4, 5, 6, 7, 8]\n\n\n// Remove all elements from the list\nintList4.Clear();  // [];\n```\n\n- ArrayList (dynamic list of multiple data types, does not offer the best performance)\n\n```c#\n// Empty array list\nSystem.Collections.ArrayList list = new System.Collections.ArrayList();  // empty list\n\n\n// Add 1 new element to the list (left to right)\nlist.Add(1);  // [1]\nlist.Add(\"abc\")  // [1, \"abc\"]\n\n// methods are similar to List\n```\n\n### c++\n\n```c++\n// Arrays\n// Empty int array of desired array size\nint int_array[length_of_desired_array];\n// New int array with elements inside\nint int_array [length_of_desired_array] {element1, element2,...};  // size declared\nint int_array[] = {element1, element2,...};  // size automatically calculated\n\n// Assign int element, limited to array size\n// Modify int element value\nint_array[index] = element;\n\n// Access an element\nint_array[index];\n\n// Find array size: size of array (bytes) / size of an element of an array (bytes)\nsizeof(int_array) / sizeof(int_array[0]);\n\n\n// Vectors: a type of dynamic array\n#include \u003cvector\u003e  // Must import to use\n\n// Empty int vector of desired vector size, each element of 0 value will automatically be included\nstd::vector \u003cint\u003e int_vector (length_of_desired_array);\n// New int vector with elements inside\nstd::vector \u003cint\u003e int_vector {element1, element2,...};\n// New int vector with length of desired array and all value in parameter\n// Method 1\nstd::vector \u003cint\u003e int_vector (length_of_desired_array, constant_value_for_all_elements);\n// Method 2\nstd::vector \u003cint\u003e int_vector;\nint_vector.assign(length_of_desired_array, constant_value_for_all_elements);\n\n// Assign int element\nint_vector[index] = element;\n\n// Access an element\nint_vector[index];\nint_vector.at(index);\n\n// Add element to vector (left to right), vector size will automatically increase\nint_vector.push_back(element);\n// Add element to vector at index\nstd::vector\u003cint\u003e::iterator it;  // Must create iterator for inserting or emplacing to work\nit = int_vector.begin()  // Set it at index 0\n// insert method: copies or moves the elements into the container by calling copy constructor or move constructor\nint_vector.insert(it + index, element);  // Add element at index\n// emplace method: elements are constructed in place, no copy or move operations are performed (better performance)\nint_vector.emplace(it + index, element);  // Add element at index\n\n// Remove element from vector at index\nstd::vector\u003cint\u003e::iterator it;  // Must create iterator for erase to work\nit = int_vector.begin()  // Set it at index 0\nint_vector.erase(it + index)  // Remove element at index\nint_vector.erase(it + index, it + index)  // Remove a range of elements in the vector\n// Remove element from vector (right to left)\nint_vector.pop_back();  // does not return value\n\n// Find vector size\nint_vector.size();\n\n// Resize vector\nint_vector.resize(length_of_desired_array);\n\n// Remove all elements\nint_vector.clear();\n```\n\n[back to top](#table-of-contents)\n\n## Conditional Statement\n\n### python 2 \u0026 3\n\n```python\n# If else statement\nif condition_a:\n    do_A\nelif condition_b:\n    do_B\nelse:\n    do_something_else\n\n\n# Ternary operator\ndo_A if condition_a else do_B\n\n\n# Switch Statement is not available in python, but can create similar function\ndef switch(choice):\n    case = {\n        1: do_A,\n        2: do_B,\n    }\n    case.get(choice, do_something_else)\n\n\n# comparing between 2 objects (array, dictionaries, etc.) is allowed\nx = [1, 2, 3]\ny = [1, 2, 3]\nx == y  # returns True\n```\n\n### javascript\n\n```javascript\n// If else statement\nif (condition_a) {\n  do_A;\n} else if (condition_b) {\n  do_B;\n} else {\n  do_something_else;\n}\n\n// Ternary operator\ncondition_a ? do_A : do_B;\n\n// Switch statement\nswitch (choice) {\n  case choice_A:\n    do_A;\n    break;\n  case choice_B:\n    do_B;\n    break;\n  default:\n    do_something_else;\n}\n\n// comparing between 2 objects (array, object, etc.) is NOT allowed\nvar x = [1, 2, 3];\nvar y = [1, 2, 3];\nx === y ? true : false; // returns false\n// solution: use JSON.stringify()\nJSON.stringify(x) === JSON.stringify(y) ? true : false; // return true\n```\n\n### ruby\n\n```ruby\n# If else statement\nif condition_a\n    do_A\nelsif condition_b\n    do_B\nelse\n    do_something_else\nend\n\n\n# Unless statement\ncondition_variable = boolValue\ndo_A unless condition_variable\n\n# Unless else statement\n# Check if something is false\nunless condition_a\n    do_A\nelse\n    do_something_else\nend\n\n\n# check if a string exist in a string\nif word.include? alphabet\n    do_something\nend\n\n\n# check if value is nil, if not nil return false\nobject.nil?  # if object != nil returns false, else returns true\n\n# check if array, hash, set, string is empty, return true if empty else false\nobject.empty?  # if object == [] or {} or \"\" or Set.new, return true\n\n\n# Ternary operator\ncondition_a ? (do_A) : (do_B);\n# example 1\nputs true ? \"yes\" : \"no\"\n# example 2\ntrue ? (puts \"yes\") : (puts \"no\")\n\n# Simpler if\ndo_A if condition_a\n\n# One line Unless\ndo_A unless condition_a  # do_A if condition_a is false\n\n\n# Case expression (similar to switch statement)\ncase choice\nwhen choice_A:\n    do_A;\nwhen choice_B:\n    do_B;\nelse\n    do_something_else\nend\n\n\n# Conditional Assignment: assign only if variable is nil\nfavorite_book = nil\nfavorite_book ||= \"book 1\"\nputs favorite_book # \"book 1\"\nfavorite_book ||= \"book 2\"\nputs favorite_book # \"book 1\"\n```\n\n### java\n\n```java\n// If else statement\nif (condition_a) {\n    do_A;\n} else if (condition_b) {\n    do_B;\n} else {\n    do_something_else;\n}\n\n\n// {} not required if statement is a single line\nif (condition_a)\n    do_A;  // Single line statement\nelse if (condition_b)\n    do_B;  // Single line statement\nelse\n    do_something_else;  // Single line statement\n\n\n// Ternary operator\ncondition_a ? do_A : do_B;\n\n//Using Boolean Value for Return:\nboolean result = condition_a ? true : false;\n\n\n// Switch statement\nswitch(choice) {  // choice value can only be primitive values in java 7, since java 8 strings are also accepted\n    case choice_A:\n        do_A;\n        break;\n    case choice_B:\n        do_B;\n        break;\n    default:\n        do_something_else;\n        break;  // not required, but good to have in Java\n}\n\n\n\n\n\n```\n\n### c#\n\n```c#\n// If else statement\nif (condition_a) {\n    do_A;\n} else if (condition_b) {\n    do_B;\n} else {\n    do_something_else;\n}\n\n\n// Ternary operator\ncondition_a ? do_A : do_B;\n\n\n// Switch statement\nswitch(choice) {\n  case choiceA:\n    doA;\n    break;\n  case choiceB:\n    doB;\n    goto doSomethingSpecial;  // go to a special case that is written outside the switch statement and run it (not advised to use it\n  default:\n    do_something_else;\n    break;\n}\n\ndoSomethingSpecial:\n  doingSomething;\n```\n\n### c++\n\n```c++\n// If else statement\nif (condition_a) {\n    do_A;\n} else if (condition_b) {\n    do_B;\n} else {\n    do_something_else;\n}\n\n\n// {} not required if statement is a single line\nif (condition_a)\n    do_A;  // Single line statement\nelse if (condition_b)\n    do_B;  // Single line statement\nelse\n    do_something_else;  // Single line statement\n\n\n// Ternary operator\ncondition_a ? do_A : do_B;\n\n\n// Null coalescing operator\nreturn_this_variable_value_if_not_null ?? else_return_this_value\n\n\n// Switch statement\nswitch(choice) {\n    case choice_A:\n        do_A;\n        break;\n    case choice_B:\n        do_B;\n        break;\n    default:\n        do_something_else;\n}\n```\n\n[back to top](#table-of-contents)\n\n## Loops\n\n### python 2\n\n```python\n# While loop\n# declare_initial_conditional_value\ni = 0\n# Set condition\nwhile i\u003c5:  # Start from 0 to 4\n    do_this\n    # Include condition_increment_or_decrement\n    i += 1\n    # Can use break, continue, and pass statements to add additional functionality, or not use any\n    break  # Breaks out of the current closest enclosing loop\n    continue  # Goes to the top of the closest enclosing loop\n    pass  # Does nothing at all\n\n\n# For loop\n# range() creates a list in python 2\n# Looping with xrange()\nfor i in xrange(5):  # Starts from 0 to 4 (5 - 1)\n    do_this\n    # Can use break, continue, and pass statements to add additional functionality, or not use any\n    break  # Breaks out of the current closest enclosing loop\n    continue  # Goes to the top of the closest enclosing loop\n    pass  # Does nothing at all\n\n# Looping with xrange() and multiple parameters\nfor i in xrange(0, 5, 2):  # Start from 0 to 4 at every 2 steps (0,2,4)\n    do_this\n\n# Reverse loop\nfor i in xrange(4, -1, -1):  # Start from 4 to 0 at every -1 steps\n    do_this\n\n\n# Looping and getting each value\nfor value in list_name:  # [i1_value, i2_value, i3_value,...]\n    print value\n\n\n# Looping and getting index and value\nfor index, value in enumerate(list_name):\n    print index, value  # output index, value\n```\n\n### python 3\n\n```python\n# For loop\n# Looping with range()\nfor i in range(5):  # Starts from 0 to (5 - 1)\n    do_this\n    # Can use break, continue, and pass statements to add additional functionality, or not use any\n    break  # Breaks out of the current closest enclosing loop\n    continue  # Goes to the top of the closest enclosing loop\n    pass  # Does nothing at all\n\n# Looping with range() and multiple parameters\nfor i in range(0, 5, 2):  # Start from 0 to 4 at every 2 steps (0,2,4)\n    do_this\n\n# Reverse loop\nfor i in range(4, -1, -1):  # Start from 4 to 0 at every -1 steps\n    do_this\n\n\n# Looping and getting each value\nfor value in list_name:  # [value1, value2, value3,...]\n    print(value)\n\n\n# Looping and getting index and value\nfor index, value in enumerate(list_name):\n    print(index, value)  # output index, value\n\n\n# Loops and getting both key and value of a dict\nx = { \"one\": 1, \"two\": 2}\nfor k, v in x.items():\n    print(f\"k: {k}, v: {v}\")\n```\n\n### javascript ES5\n\n```javascript\n// While loop\n// declare_initial_conditional_value\nvar i = 0;\n// Set condition\nwhile (i \u003c 5) {\n  // Start from 0 to 4\n  do_this;\n  // Include condition_increment_or_decrement;\n  i++;\n  // Can use break or continue to add additional functionality, or not use any\n  break; // Breaks out of the current closest enclosing loop\n  continue; // Goes to the top of the closest enclosing loop\n}\n\n// Do While loop\nvar i = 0;\ndo {\n  do_this;\n  i++;\n} while (i \u003c 5);\n\n// For loop\nfor (var i = 0; i \u003c 5; i++) {\n  // Start from 0 to 4\n  do_this;\n  // Can use break or continue to add additional functionality, or not use any\n  break; // Breaks out of the current closest enclosing loop\n  continue; // Goes to the top of the closest enclosing loop\n}\n\n// Reverse loop\nfor (var i = 4; i \u003e= 0; i--) {\n  // Start from 4 to 0\n  do_this;\n}\n\n// forEach loop\n// Looping through a list while calling a function\nlist_name.forEach(function (value, index, list) {\n  // do not need to include all 3 parameters, but must be in order\n  console.log(index, value, list); // outputs index value list\n});\n```\n\n### javascript ES6: Use let in loops when declaring\n\n```javascript\n// For of loop\n// Looping and getting each value\nfor (let value of list_name) {\n  // [value1, value2, value3,...]\n  console.log(value); // output value\n}\n// Looping and getting index and value\nfor (let index_and_value of list_name.entries()) {\n  console.log(index_and_value); // output a list [index, value]\n}\n\n// For in loop\nfor (let index in list_name) {\n  console.log(list_name[index]);\n}\n// For in loop normally used to get values from objects (hash table, dictionaries) than to arrays\n// object = {key1:value1, key2:value2,...}\nfor (let key in object) {\n  console.log(object[key]); // outputs value, normally calling this way will not output value from objects\n}\n```\n\n### ruby\n\n```ruby\n# While loop\n# declare_initial_conditional_value\ni = 0\n# Set condition\nwhile i\u003c5 do  # Start from 0 to 4, do keyword is not mandatory\n    do_this\n    # Include condition_increment_or_decrement\n    i += 1\nend\n\n# Until loop, backward while loop\ni = 0\nuntil i == 4  # Start from 0 to 4\n    i += 1\nend\n\n# For loop, with ... (3 dots)\nfor i in numStart...numEnd  # for i in the range numStart up to but don't include numEnd\n    do_this\nend\n\n# For loop, with .. (2 dots)\nfor i in numStart..numEnd  ## for i in the range numStart up to and include numEnd\n    dot_this\nend\n\n# Loop method, an infinite loop, requireds break to stop loop\ni = 4\nloop do\n    i -= 1\n    break if i ==0  # Breaks out of the current closest enclosing loop\nend\n\n# Next keyword: used to skip over certain steps in loop\nfor i in 0...5\n    next if i % 2 == 0   # do not do anything if i is an even number\n    do_this\nend\n\n# Each Iterator\narray = [1, 2, 3, 4, 5]\narray2 = []\narray.each { |value|  # Method 1: using {}\n    value += 10\n    array2.push(value)\n}\nputs array2  # [11, 12, 13, 14, 15]\n\narray3 = []\narray2.each do |value|  # Method 2: using do keyword\n    value -= 10\n    array3.push(value)\nend\nputs array3  # [1, 2, 3, 4, 5]\n\n# Iterating over Multidimensional Arrays with Each Iterator\nmultiArray = [[1, 2], [3, 4], [5, 6]]\nmultiArray.each {\n    |sub_array| sub_array.each {\n        |value| do_something\n    }\n}\n\n# Times Iterator\nn.times { do_this }  # do_this will repeat n times\n\n# Upto Iterator\n# method 1: number\n0.upto(5) { |num| print num, \" \" }  # 0 1 2 3 4 5\n# method 2: alphabet\n\"A\".upto(\"D\") { |letter| prints letter, \" \" }  # A B C D\n\n# Downto Iterator, \"string\" don't work\n100.downto(95) { |num| print num, \" \" }  # 100 99 98 97 96 95\n```\n\n### java\n\n```java\n// While loop\n// declare_initial_conditional_value\nint i = 0;\n// Set condition\nwhile (i\u003c5) {  // Start from 0 to 4\n    doThis;\n    // Include condition_increment_or_decrement;\n    i++;\n    // Can use break or continue to add additional functionality, or not use any\n    break;  // Breaks out of the current closest enclosing loop\n    continue;  // Goes to the top of the closest enclosing loop\n}\n\n// Do while loop: execute first before setting conditions\n// declare_initial_conditional_value\nint i = 0;\ndo {  // Start from 0 to 4\n    doThis;\n    // Include condition_increment_or_decrement;\n    i++;\n// Set condition\n} while (i\u003c5);\n\n// For loop\nfor (int i=0; i\u003c5; i++) {  // Start from 0 to 4\n    doThis;\n    // Can use break or continue to add additional functionality, or not use any\n    break;  // Breaks out of the current closest enclosing loop\n    continue;  // Goes to the top of the closest enclosing loop\n}\n// Reverse loop\nfor (int i=4; i\u003e=0; i--) {  // Start from 4 to 0\n    doThis;\n}\n\n// for each loop, can also loop collections with iterators\nchar[] chars = {'H', 'e', 'l', 'l', 'o'};  // an array can only have a single data type\nfor (char c : chars) {  // for each element in the array\n  doThis;\n}\n\n\n// some more methods of implementing loops in java while dealing with arrays\nint [] arr={1,2,3,4,5};\nfor(int num:arr)\n{\n  System.out.println(num);\n}\n\n\n```\n\n### c#\n\n```c#\n// While loop\n// declare_initial_conditional_value\nint i = 0;\n// Set condition\nwhile (i\u003c5) {  // Start from 0 to 4\n  do_this;\n  // Include condition_increment_or_decrement;\n  i++;\n  // Can use break or continue to add additional functionality, or not use any\n  break;  // Breaks out of the current closest enclosing loop\n  continue;  // Goes to the top of the closest enclosing loop\n}\n\n\n// Do while loop: execute first before setting conditions\n// declare_initial_conditional_value\nint i = 0;\ndo {  // Start from 0 to 4\n  do_this;\n  // Include condition_increment_or_decrement;\n  i++;\n// Set condition\n} while (i\u003c5);\n\n\n// For loop\nfor (int i=0; i\u003c5; i++) {  // Start from 0 to 4\n  do_this;\n  // Can use break or continue to add additional functionality, or not use any\n  break;  // Breaks out of the current closest enclosing loop\n  continue;  // Goes to the top of the closest enclosing loop\n}\n// Reverse loop\nfor (int i=4; i\u003e=0; i--) {  // Start from 4 to 0\n  do_this;\n}\n\n\n// For each loop: cycles through every item in an array or collection (List)\n// Modifications of an array or collection is no","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freshinto%2Fprogramming_language_syntax_comparison","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freshinto%2Fprogramming_language_syntax_comparison","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freshinto%2Fprogramming_language_syntax_comparison/lists"}