Code Card
The Code Syntax Dictionary
Search
261 cards
Python - For Loop
sequence = range(10)
for x in sequence:
...
Python has one of the simplest types of For Loops of any language. The 'in' operator can be used to easily iterate over any sequence type.
Java - For Loop
for ( int x = 0; x < 10; x++ ) {
...
}
Java uses the traditional For Loop syntax which involves defining an iteration variable, looping condition, and increment.
Javascript - For Loop
for ( var x = 0; x < 10; x++ ) {
...
}
Javascript uses the traditional For Loop syntax which involves defining an iteration variable, looping condition, and increment.
C - For Loop
for ( int x = 0; x < 10; x++ ) {
...
}
C uses the traditional For Loop syntax which involves defining an iteration variable, looping condition, and increment.
PHP - For Loop
for ( $x = 0; $x < 10; $x++ ) {
...
}
PHP uses the traditional For Loop syntax which involves defining an iteration variable, looping condition, and increment.
Python - While Loop
x = 0
while (x < 10):
...
x += 1
Python uses a very clean While Loop syntax. The loop continues running as long as the looping condition remains true. The looping variable can be updated in the loop.
Java - While Loop
int x = 0;
while (x < 10) {
...
x++;
}
Java uses the traditional While Loop syntax. The loop continues running as long as the looping condition remains true. The looping variable can be updated in the loop.
Javascript - While Loop
var x = 0;
while (x < 10) {
...
x++;
}
Javascript uses the traditional While Loop syntax. The loop continues running as long as the looping condition remains true. The looping variable can be updated in the loop.
C - While Loop
int x = 0;
while (x < 10) {
...
x++;
}
C uses the traditional While Loop syntax. The loop continues running as long as the looping condition remains true. The looping variable can be updated in the loop.
PHP - While Loop
$x = 0;
while ($x < 10) {
...
$x++;
}
PHP uses the traditional While Loop syntax. The loop continues running as long as the looping condition remains true. The looping variable can be updated in the loop.
Python - Variable Assignment
a = 0
b = "Hello"
c = ["C", "h", "e", "e", "s", "e"]
d = { 1: "x", 2: "y", 3: "z" }
e = True
Python variables can be assigned on the fly without declaring their types first. Integers, strings, lists, dictionaries, and booleans can all be defined using a single equals sign.
Java - Variable Assignment
int a = 0;
char b = 'b';
String c = "Hello";
String[] d = {"C", "h", "e", "e", "s", "e"};
boolean e = true;
Java variables must have their types declared before assignment. Integers, characters, strings, arrays, and booleans are shown here.
Javascript - Variable Assignment
var a = 0;
var b = "Hello";
var c = ["C", "h", "e", "e", "s", "e"];
var d = { 1: "x", 2: "y", 3: "z" };
var e = true;
Javascript variables can be assigned on the fly without declaring their types first. Integers, strings, lists, objects, and booleans can all be defined using the `var` keyword and an equals sign.
C - Variable Assignment
int a = 0;
char b = 'b';
String c = "Hello";
String[] d = {"C", "h", "e", "e", "s", "e"};
boolean e = true;
C variables must have their types declared before assignment. Integers, characters, strings, arrays, and booleans are shown here.
PHP - Variable Assignment
$a = 0;
$b = "Hello";
$c = ["C", "h", "e", "e", "s", "e"];
$d["1"] = "x"; $d["2"] = "y"; $d["3"] = "z";
$e = true;
PHP variables can be assigned on the fly without declaring their types first. Integers, strings, arrays, and booleans can all be defined using the `$` symbol and an equals sign.
Python - If ... Else
if ( x == 1 ):
...
elif ( x == 2 ):
...
else:
...
Python conditional statements are very simple indeed.
Java - If ... Else
if ( x == 1 ) {
...
} else if ( x == 2 ) {
...
} else {
...
}
Java uses the traditional syntax for conditional statements.
Javascript - If ... Else
if ( x == 1 ) {
...
} else if ( x == 2 ) {
...
} else {
...
}
Javascript uses the traditional syntax for conditional statements.
C - If ... Else
if ( x == 1 ) {
...
} else if ( x == 2 ) {
...
} else {
...
}
C uses the traditional syntax for conditional statements.
PHP - If ... Else
if ( x == 1 ) {
...
} elseif ( x == 2 ) {
...
} else {
...
}
PHP almost uses the traditional syntax for conditional statements, but note that the `elseif` is a single word.
Python - Function
def sum(i, j):
return i + j
Python functions are created using the `def` statement. The return type and parameter types do not need to be specified. All indented lines under the `def` statement make up the function's scope.
Java - Function
int sum(int i, int j) {
return i + j;
}
Java functions must declare the return type before the function name, as well as the parameter types. The function's scope is delineated by curly braces.
Javascript - Function
function sum(i, j) {
return i + j;
}
Javascript functions are defined using the `function` statement. The return type and parameter types do not need to be specified. The function's scope is delineated by curly braces.
C - Function
int sum(int i, int j) {
return i + j;
}
C functions must declare the return type before the function name, as well as the parameter types. The function's scope is delineated by curly braces.
PHP - Function
function sum($i, $j) {
return $i + $j;
}
PHP functions are defined using the `function` statement. The return type and parameter types do not need to be specified. The function's scope is delineated by curly braces.
Python - Class
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "I am " + self.name
Python classes contain member attributes and methods. The `__init__` method defines the constructor. By convention, `self` is the first parameter in each method and represents the instance of the class. Getter and setter methods are not needed since attributes are not private.
Java - Class
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Java classes contain member attributes and methods. Constructors are methods created with the same name as the class itself. Members are private by default, so public getters and setters must be defined for attribute access.
Javascript - Class
class Person {
constructor(name) {
this.name = name;
}
greet() {
return "I am " + this.name;
}
}
Javascript classes are relatively new additions to the language. The `constructor` keyword defines the constructor. Getter and setter methods are not needed since attributes are not private.
C - Class
Gone fishin!
C does not have classes. That's why C++ was created. The closest thing in C is the `struct`, which has it's own card.
PHP - Class
class Person {
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return $this->name;
}
}
PHP classes contain member attributes and methods. The `__construct` method defines the constructor. Getter and setter methods are not needed since attributes are not private.
Python - Try ... Catch / Except
try:
...
except:
...
finally:
...
Python will try to run the code in the `try` block. If an exception occurs the code in the `except` block will run. Specific exceptions can be caught using the `except(Exception1, Exception2, ...)` syntax. The code in the `finally` block will always execute.
Java - Try ... Catch / Except
try {
...
} catch ( Exception e ) {
...
} finally {
...
}
Java will try to run the code in the `try` block. If a matched exception occurs the code in the `catch` block will run. The code in the `finally` block will always execute.
Javascript - Try ... Catch / Except
try {
...
} catch ( e ) {
...
} finally {
...
}
Javascript will try to run the code in the `try` block. If an exception occurs the code in the `catch` block will run. Exception matching must be performed in the `catch` block. The code in the `finally` block will always execute.
C - Try ... Catch / Except
Gone fishin!
C does not directly support exceptions.
PHP - Try ... Catch / Except
try {
...
} catch ( Exception $e ) {
...
} finally {
...
}
PHP will try to run the code in the `try` block. If an exception occurs the code in the `catch` block will run. Specific exceptions can be caught using the `catch(Exception1 | Exception2 $e)` syntax. The code in the `finally` block will always execute.
Python - Switch
Gone fishin!
Python does not have a built-in Switch statement.
Java - Switch
switch( expression ) {
case value1:
...;
break;
case value2:
...;
break;
default:
...;
break;
}
The Java Switch statement accepts any expression or variable that can assume multiple values. Depending on the values, different code can be executed corresponding to each `case` statement. The `default` case is a catchall in the event that none of the explicit cases occur.
Javascript - Switch
switch( expression ) {
case value1:
...;
break;
case value2:
...;
break;
default:
...;
}
The Javascript Switch statement accepts any expression or variable that can assume multiple values. Depending on the values, different code can be executed corresponding to each `case` statement. The `default` case is a catchall in the event that none of the explicit cases occur.
C - Switch
switch( expression ) {
case value1:
...;
break;
case value2:
...;
break;
default:
...;
}
The C Switch statement accepts any expression or variable that can assume multiple values. Depending on the values, different code can be executed corresponding to each `case` statement. The `default` case is a catchall in the event that none of the explicit cases occur.
PHP - Switch
switch( expression ) {
case value1:
...;
break;
case value2:
...;
break;
default:
...;
}
The PHP Switch statement accepts any expression or variable that can assume multiple values. Depending on the values, different code can be executed corresponding to each `case` statement. The `default` case is a catchall in the event that none of the explicit cases occur.
Python - Import / Include
import module1
import module1 as m1
from module1 import object1
from module1 import object1 as o1
from module1 import *
Python imports are used to access external code within modules. The `from` keyword can be used to import a specific object or function from a module. The `as` keyword can be used to rename the imported module or object. An asterisk can be used to import all toplevel objects from a module.
Java - Import / Include
import library.packagename.classname;
import library.packagename.*;
Java imports are used to conveniently reference code from other packages on the classpath. Classes can be imported individually or all classes can be imported from a package using the asterisk.
Javascript - Import / Include
import {obj1, obj2} from './mod.js';
import {obj1 as o1} from './mod.js';
import * as obj from './mod.js';
Javascript imports are used to access objects exported from other modules. Objects can be renamed with the `as` keyword. All objects exported from a module can be imported using an asterisk.
C - Import / Include
#include <header.h>
The #include preprocessing directive is used in C programs to access functions or objects that live in header and user files.
PHP - Import / Include
use \library\package\module;
PHP modules can be imported and accessed with the `use` statement.
Python - Print
print('Hi')
The Python Print function prints a string to the standard output.
Java - Print
System.out.println("Hi");
The `println` function from the `System.out` library is used to print strings to standard output in Java, with a newline added to the end.
Javascript - Print
console.log('Hi');
In Javascript, the `console.log` function is used to print text to the console.
C - Print
printf("%s", "Hi");
In C, the `printf` function is used to print a formatted string to the standard output.
PHP - Print
print "Hi";
echo "Hi";
In PHP, the `print` or `echo` functions can be used to output text.
Python - Arithmetic Operators
a = 8 + 4
b = a - 7
c = a * 8
d = b / a
e = b ** a
r = e % 2
Python uses the familiar set of arithmetic operators to add, subtract, multiply, divide, exponentiate, and modulo.
Java - Arithmetic Operators
int a = 8 + 4;
int b = a - 7;
int c = b * 8;
int d = b / a;
int e = 2 ** 4;
int r = 10 % 3;
Java uses the familiar set of arithmetic operators to add, subtract, multiply, divide, exponentiate, and modulo.
Javascript - Arithmetic Operators
var a = 8 + 4;
var b = a - 7;
var c = a * 8;
var d = b / a;
var e = b ** a;
var r = e % 2;
Javascript uses the familiar set of arithmetic operators to add, subtract, multiply, divide, exponentiate, and modulo.
C - Arithmetic Operators
int a = 8 + 4;
int b = a - 7;
int c = b * 8;
int d = b / a;
int e = 2 ** 4;
int r = 10 % 3;
C uses the familiar set of arithmetic operators to add, subtract, multiply, divide, exponentiate, and modulo.
PHP - Arithmetic Operators
$a = 8 + 4;
$b = $a - 7;
$c = $b * 8;
$d = $b / $a;
$e = 2 ** 4;
$r = $e % 2;
PHP uses the familiar set of arithmetic operators to add, subtract, multiply, divide, exponentiate, and modulo.
Python - Comparison Operators
a == b
b > a
b < a
b <= a
b >= a
b <> a
Python uses the standard set of operators to test equality, greater than, less than, etc. Equality uses two equals signs `==` to distinguish it from the assignment operator `=`. To test inequality, Python uses the `<>` operator. Each conditional expression returns a boolean value, either True or False.
Java - Comparison Operators
a == b
a < b
a > b
a >= b
a <= b
a != b
Java uses the standard set of operators to test equality, greater than, less than, etc. Equality uses two equals signs `==` to distinguish it from the assignment operator `=`. To test inequality, Java uses the '!=' operator. Each conditional expression returns a boolean value.
Javascript - Comparison Operators
a == b
a === b
a < b
a > b
a >= b
a <= b
a != b
a !== b
Javascript uses the standard set of operators to test equality, greater than, less than, etc. Equality uses two equals signs `==` to distinguish it from the assignment operator `=`. To test inequality, Javascript uses the `!=` operator. Notice the `===` and `!==` operators compare value AND type.
C - Comparison Operators
a == b
a < b
a > b
a >= b
a <= b
a != b
C uses the standard set of operators to test equality, greater than, less than, etc. Equality uses two equals signs `==` to distinguish it from the assignment operator '='. To test inequality, C uses the `!=` operator. Each conditional expression returns a boolean value.
PHP - Comparison Operators
$a == $b
$a === $b
$a < $b
$a > $b
$a >= $b
$a <= $b
$a != $b
$a <> $b
$a !== $b
PHP uses the standard set of operators to test equality, greater than, less than, etc. Equality uses two equals signs `==` to distinguish it from the assignment operator `=`. To test inequality, PHP uses `!=` or `<>`. Notice the `===` and `!==` operators compare value AND type.
Python - Logical Operators
a and b
a or b
not a
Python uses english words to represent the logical operators: and, or, not.
Java - Logical Operators
a && b
a || b
!a
Java uses the respective symbols to represent the logical operators: and, or, not.
Javascript - Logical Operators
a && b
a || b
!a
Javascript uses the respective symbols to represent the logical operators: and, or, not.
C - Logical Operators
a && b
a || b
!a
C uses the respective symbols to represent the logical operators: and, or, not.
PHP - Logical Operators
a && b
a and b
a || b
a or b
!a
PHP uses the respective symbols to represent the logical operators: and, or, not.
Python - Break
while a > b:
...
break
Python uses the break statement to break out of the enclosing loop.
Java - Break
for ( int x : numbers ) {
...
break;
}
Java uses the break statement to break out of the enclosing loop.
Javascript - Break
for ( i = 0; i < 5; i++ ) {
...
break;
}
Javascript uses the break statement to break out of the enclosing loop.
C - Break
for ( int i = 0; i < 5; i++ ) {
...
break;
}
C uses the break statement to break out of the enclosing loop.
PHP - Break
for ( $i = 0; $i < 5; $i++ ) {
...
break;
}
PHP uses the break statement to break out of the enclosing loop.
Python - Continue
while a > b:
...
continue
Python uses the continue statement to start the next instruction at the beginning of the enclosing loop.
Java - Continue
for ( int x : numbers ) {
...
continue;
}
Java uses the continue statement to start the next instruction at the beginning of the enclosing loop.
Javascript - Continue
for ( i = 0; i < 5; i++ ) {
...
continue;
}
Javascript uses the continue statement to start the next instruction at the beginning of the enclosing loop.
C - Continue
for ( int i = 0; i < 5; i++ ) {
...
continue;
}
C uses the continue statement to start the next instruction at the beginning of the enclosing loop.
PHP - Continue
for ( $i = 0; $i < 5; $i++ ) {
...
continue;
}
PHP uses the continue statement to start the next instruction at the beginning of the enclosing loop.
Python - Comments
# This is a simple single line comment
"""The triple quote
comment can span many lines"""
Python uses two formats for comments, depending on whether they are single-line or multi-line comments.
Java - Comments
// This is a single line comment
/* This comment can span many lines */
Java uses two formats for comments, depending on whether they are single-line or multi-line comments.
Javascript - Comments
// This is a single line comment
/* This comment can span many lines */
Javascript uses two formats for comments, depending on whether they are single-line or multi-line comments.
C - Comments
/* This comment can span many lines */
// This was not originally supported by C
C was the original language to introduce this multi-line style for comments. However later versions of C started supporting the C++ style single-line comments.
PHP - Comments
# This is a single line comment
// This is also a single line comment
/* This comment can span many lines */
PHP supports shell style comments and both single and multi-line C style comments.
Python - Return
def func( ):
...
return a, b
Python uses the return statement to exit from a function, optionally returning zero, one, more values.
Java - Return
class A {
int fun( ) {
...
return x;
}
}
Java uses the return statement to exit from a function, optionally returning a value.
Javascript - Return
function fun( ) {
...
return x;
}
Javascript uses the return statement to exit from a function, optionally returning a value.
C - Return
int fun( ) {
...
return x;
}
C uses the return statement to exit from a function, optionally returning a value.
PHP - Return
function fun( ) {
...
return $x;
}
PHP uses the return statement to exit from a function, optionally returning a value.
Python - Ternary Operator
x if ( x > 0 ) else y
Python uses a unique syntax for the ternary operator to shorten the traditional if-else clause.
Java - Ternary Operator
( x > 0 ) ? x : y;
Java uses the ternary operator as short hand for the if-else clause. If the condition evaluates to true, the value after the question mark is returned. Otherwise, the value after the colon is returned.
Javascript - Ternary Operator
( x > 0 ) ? x : y;
Javascript uses the ternary operator as short hand for the if-else clause. If the condition evaluates to true, the value after the question mark is returned. Otherwise, the value after the colon is returned.
C - Ternary Operator
( x > 0 ) ? x : y;
C uses the ternary operator as short hand for the if-else clause. If the condition evaluates to true, the value after the question mark is returned. Otherwise, the value after the colon is returned.
PHP - Ternary Operator
( $x > 0 ) ? $x : $y
PHP uses the ternary operator as short hand for the if-else clause. If the condition evaluates to true, the value after the question mark is returned. Otherwise, the value after the colon is returned.
Python - Raise / Throw
if x > 20:
raise Exception("x must be less than 20")
Python uses the raise statement to generate an exception under user-defined conditions.
Java - Raise / Throw
if ( x > 20 ) {
throw new Exception("x must be < 20");
}
Java uses the throw statement to generate an exception under user-defined conditions.
Javascript - Raise / Throw
if ( x > 20 ) {
throw "x must be < 20";
}
Javascript uses the throw statement to generate an exception under user-defined conditions.
C - Raise / Throw
Gone fishin!
C does not support exceptions, one must rely on return values or asserts to handle exceptional conditions.
PHP - Raise / Throw
if ( $x > 20 ) {
throw new Exception("x must be > 20");
}
PHP uses the throw statement to generate an exception under user-defined conditions.
Python - Assert
assert x > b
Python uses the assert statement to terminate a program when an expression is false.
Java - Assert
assert x > 20: "x must be > 20;
Java uses the assert statement to terminate a program when an expression is false.
Javascript - Assert
assert( x > 20 );
Javascript uses the assert statement to terminate a program when an expression is false.
C - Assert
#include <assert.h>
...
void fun() {
...
assert( x > 20 );
}
C uses the assert statement to terminate a program when an expression is false.
PHP - Assert
result = assert( $x > 20, "x must be > 20" );
PHP uses the assert statement to terminate a program when an expression is false. The behavior of assert is controlled by assert_options().
Python - Dates
import datetime
n = datetime.datetime.now()
Python uses the datetime module to get the current time.
Java - Dates
Date now = new Date();
Java uses the Date() class to get the current time.
Javascript - Dates
var now = Date.now();
Javascript the Date() class can be used to get the current time.
C - Dates
#include <time.h>
...
time_t now = time(NULL);
C uses the time library to get the current date and time.
PHP - Dates
$now = date("Y/m/d");
PHP uses the date function with a format string to get the current date and time.
Python - Open File
f1 = open( "f.txt", "r" )
f2 = open( "f.txt", "w" )
f3 = open( "f.txt", "a" )
Python can open a file for reading, writing, or appending, using the respective file mode as the second argument to the `open` function.
Java - Open File
import java.io.File;
...
File file = new File( "f.txt" );
Java can open a file for reading or writing.
Javascript - Open File
var f1 = fopen( "f.txt", 0 );
var f2 = fopen( "f.txt", 3 );
Javascript can open a file for reading or writing, depending on the value of the second argument to the `fopen` function. 0 is for reading, 3 is for writing.
C - Open File
#include <stdio.h>
...
FILE *f1 = fopen( "f.txt", "r" );
FILE *f2 = fopen( "f.txt", "w" );
FILE *f3 = fopen( "f.txt", "a" );
C can open a file for reading, writing, or appending, using the respective file mode as the second argument to the `open` function.
PHP - Open File
$f1 = fopen( "f.txt", "r" );
$f2 = fopen( "f.txt", "w" );
PHP can open a file for reading or writing using the respective file mode as the second argument to the `fopen` function.
Python - Read from File
f = open( "f.txt", "r" )
content = f.read()
Python can read all data from a file object that was opened in read mode using the `read()` method.
Java - Read from File
import java.io.File;
import java.util.Scanner;
...
File f = new File( "f.txt" );
Scanner s = new Scanner(f);
while ( s.hasNextLine() ) {
String l = s.nextLine();
System.out.println(l);
}
Java can use the scanner class to read from a file, line by line.
Javascript - Read from File
var f = fopen( "f.txt", 0 );
var content = fread( f, len );
Javascript can read the content of an open file using the `fread()` function. The second argument to `fread()` specifies the length of content to read.
C - Read from File
FILE *f = fopen( "f.txt", "r" );
char c = fgetc(f);
while ( c != EOF ) {
printf("%c", c);
c = fgets(f);
}
C can use the `fgetc()` function to read characters from a file one by one.
PHP - Read from File
$f = fopen( "f.txt", "r" );
$s = filesize("f.txt");
$c = fread( $f, $s );
PHP can read a file with the `fread()` function. The second argument is the filesize. The `filesize()` function can be used to get the size of the entire file.
Python - Write to File
f = open( "f.txt", "w" )
f.write( "text" )
Python can write to an open file object using the `write` method.
Java - Write to File
import java.io.FileWriter;
...
FileWriter fw = new FileWriter( "f.txt" );
fw.write( "text" );
Java can write to a file using the FileWriter object and its `write` method.
Javascript - Write to File
var f = fopen( "f.txt", 3 );
fwrite( f, "text" );
Javascript can write to an open file using the `fwrite` function.
C - Write to File
FILE *f = fopen( "f.txt", "w" );
fprintf(f, "%s", "text");
C can write to an open file using the `fprintf()` function.
PHP - Write to File
$f = fopen( "f.txt", "w" );
fwrite( $f, "text" );
PHP can write to an open file using the `fwrite()` function.
Python - Close File
f.close()
Python uses the `close()` method to close files.
Java - Close File
Gone fishin!
Java doesn't have a close function since a file opened with `new File('f.txt')` represents a path and not the file itself. Java utilities to read and write from files handle the closing process.
Javascript - Close File
fclose(f);
Javascript uses the `fclose()` function to close files.
C - Close File
fclose(f);
C uses the `fclose()` function to close files.
PHP - Close File
fclose($f);
PHP uses the `fclose()` function to close files.
Python - User Input
x = input("Type input: ")
Python uses the `input()` function prompt the user for input.
Java - User Input
import java.util.Scanner;
Scanner s = new Scanner(System.in);
System.out.println("Type input: ");
String i = s.nextLine();
Java uses a Scanner object combined with the standard input to read values from the user.
Javascript - User Input
var i = prompt("Type input: ");
Javascript uses the `prompt()` function to display a prompt dialog to the user.
C - User Input
#include <stdio.h>
...
char s[10];
printf("Type input: ");
fgets(s, 10, stdin);
C uses the `fgets()` function to accept input from an input stream. In this case we specify that `fgets` accepts 10 characters of input from the standard input.
PHP - User Input
echo "Type input: ";
$f = fopen( "php://stdin", "r" );
$line = fgets($f);
PHP uses the `fopen()` with the standard input stdin and `fgets()` to read input from a user.
Python - Anonymous / Lambda Function
lambda x : 2 * x
Python uses the lambda keyword to create anonymous functions.
Java - Anonymous / Lambda Function
(int x) -> 2 * x;
Java uses the arrow operator to map a function expression to a return value and create an anonymous function.
Javascript - Anonymous / Lambda Function
function() {
alert("Hi");
}
Javascript creates an anonymous function any time the `function` statement is used without specifying a function name.
C - Anonymous / Lambda Function
Gone fishin!
C does not support anonymous functions.
PHP - Anonymous / Lambda Function
function() {
echo "Hi.";
}
PHP creates an anonymous function any time the `function` statement is used without specifying a function name.
Python - Inheritance
class ChildClass( ParentClass ):
pass
Python implements inheritance by allowing the user to specify a superclass as an argument in the subclass definition.
Java - Inheritance
class ChildClass extends ParentClass {
...
}
Java implements inheritance via the `extends` keyword.
Javascript - Inheritance
function ChildClass( x, y ) {
ParentClass.call( this, x );
this.y = y;
}
ChildClass.prototype = new ParentClass();
Javascript allows creating an inheritance model by calling the constructor of the superclass and passing any required parameters. Note the last line where we set the prototype of the subclass to a new empty instance of the superclass.
C - Inheritance
Gone fishin!
C does not support inheritance.
PHP - Inheritance
class ChildClass extends ParentClass {
...
}
PHP implements inheritance via the `extends` keyword.
Python - Null / None / Undefined
x = None
Python uses the `None` keyword to represent null values.
Java - Null / None / Undefined
String x = null;
Java uses the `null` keyword to represent null values.
Javascript - Null / None / Undefined
var x = null;
var y = undefined;
Javascript uses the `null` or `undefined` keyword to represent null values.
C - Null / None / Undefined
char *x = NULL;
C uses a macro to define NULL as the actual null value '\0', or the NULL byte.
PHP - Null / None / Undefined
$val = NULL;
PHP uses the `NULL` keyword to represent null values.
Python - Pass
if True:
pass
Python uses pass to represent a placeholder statement that does nothing. The reason Python needs this statement is that brackets aren't used to identify the end of an empty scoped block.
Java - Pass
if ( true ) { }
Java uses empty brackets to represent a placeholder statement that does nothing.
Javascript - Pass
if ( true ) { }
Javascript uses empty brackets to represent a placeholder statement that does nothing.
C - Pass
if ( 1 ) { }
C uses empty brackets to represent a placeholder statement that does nothing.
PHP - Pass
if ( true ) { }
PHP uses empty brackets to represent a placeholder statement that does nothing.
Python - Advanced Assignment
a += 5
a -= 5
a *= 5
a /= 5
a %= 5
Python combines a logical operation (add, subtract, multiply, divide and modulo) with an equals sign, subsequently assigning the result of the operation to the left operand.
Java - Advanced Assignment
int a += 5;
int a -= 5;
int a *= 5;
int a /= 5;
int a %= 5;
Java combines a logical operation (add, subtract, multiply, divide and modulo) with an equals sign, subsequently assigning the result of the operation to the left operand.
Javascript - Advanced Assignment
var a += 5;
var a -= 5;
var a *= 5;
var a /= 5;
var a %= 5;
Javascript combines a logical operation (add, subtract, multiply, divide and modulo) with an equals sign, subsequently assigning the result of the operation to the left operand.
C - Advanced Assignment
int a += 5;
int a -= 5;
int a *= 5;
int a /= 5;
int a %= 5;
C combines a logical operation (add, subtract, multiply, divide and modulo) with an equals sign, subsequently assigning the result of the operation to the left operand.
PHP - Advanced Assignment
$a += 5;
$a -= 5;
$a *= 5;
$a /= 5;
$a %= 5;
PHP combines a logical operation (add, subtract, multiply, divide and modulo) with an equals sign, subsequently assigning the result of the operation to the left operand.
Python - Casting
w = 1;
x = str(w)
y = int(x)
z = float(y)
Python uses a set of type functions for casting.
Java - Casting
int w = 1;
String x = (String) w;
int y = (int) x;
float z = (float) y;
Java uses the type wrapped in parenthesis before the variable for casting.
Javascript - Casting
var w = 1;
var x = String(w);
var y = Number(x);
Javascript uses a set of type functions and built-in object methods for casting.
C - Casting
int w = 1;
long x = (long) w;
float y = (float) x;
double z = (double) y;
C uses the type wrapped in parenthesis before the variable for casting.
PHP - Casting
$w = 1;
$x = (string) w;
$y = (int) x;
$z = (float) y;
PHP uses the type wrapped in parenthesis before the variable for casting.
Python - Bitwise Operators
b = a & 0x1001
b = a | 0x1001
b = ~a
b = a ^ 0x4
b = a << 2
b = a >> 2
Python supports the respective bitwise operations: and, or, not, xor, shift right and shift left.
Java - Bitwise Operators
int b = a & 0x1001;
int b = a | 0x1001;
int b = ~a;
int b = a ^ 0x4;
int b = a << 2;
int b = a >> 2;
Java supports the respective bitwise operations: and, or, not, xor, shift right and shift left.
Javascript - Bitwise Operators
var b = a & 0x1001;
var b = a | 0x1001;
var b = ~a;
var b = a ^ 0x4;
var b = a << 2;
var b = a >> 2;
Javascript supports the respective bitwise operations: and, or, not, xor, shift right and shift left.
C - Bitwise Operators
int b = a & 0x1001;
int b = a | 0x1001;
int b = ~a;
int b = a ^ 0x4;
int b = a << 2;
int b = a >> 2;
C supports the respective bitwise operations: and, or, not, xor, shift right and shift left.
PHP - Bitwise Operators
$b = $a & 0x1001;
$b = $a | 0x1001;
$b = ~$a;
$b = $a ^ 0x4;
$b = $a << 2;
$b = $a >> 2;
PHP supports the respective bitwise operations: and, or, not, xor, shift right and shift left.
Python - Constructor
class Fake():
def __init__(self, x):
this.x = x
Python uses the special `__init__()` method with the conventional `self` argument to define the class constructor. `self` represents the instance of the class being referenced.
Java - Constructor
class Fake {
public Fake(String x) {
this.x = x;
}
}
Java implements constructors by recognizing methods that have the same name as the class. `this` represents the instance of the class being referenced.
Javascript - Constructor
class Fake {
constructor(x) {
this.x = x;
}
}
Javascript defines constructors using the `constructor()` method. `this` represents the instance of the class being referenced.
C - Constructor
Gone fishin!
C does not supports classes and therefore does not support constructors.
PHP - Constructor
class Fake {
function __construct($x) {
$this->x = $x;
}
}
PHP defines constructors using the `__construct()` method. `$this` represents the instance of the class being referenced.
Python - Create Instance
f = Fake("Hi")
Python will instantiate an object from a class definition by calling it with parenthesis and the respective arguments. Arguments will be passed to the class constructor.
Java - Create Instance
Fake f = new Fake("Hi");
Java will instantiate an object from a class definition using the `new` keyword. Arguments will be passed to the class constructor.
Javascript - Create Instance
var f = new Fake("Hi");
Javascript will instantiate an object from a class definition using the `new` keyword. Arguments will be passed to the class constructor.
C - Create Instance
Gone fishin!
C does not support classes and therefore does not support instance creation.
PHP - Create Instance
$f = new Fake("Hi");
PHP will instantiate an object from a class definition using the `new` keyword. Arguments will be passed to the class constructor.
Python - List / Array Length
len(list)
The Python `len()` function returns the length of a list.
Java - List / Array Length
arr.length;
Java arrays have the `length` property which can be used to return their length.
Javascript - List / Array Length
arr.length;
Javascript arrays have the `length` property which can be used to return their length.
C - List / Array Length
sizeof(arr) / sizeof(arr[0]);
C uses the `sizeof()` function to get the size of data types including arrays. Since size returns the total size or the array, we divide it by the size of an array item to get the the length.
PHP - List / Array Length
count($array);
PHP uses the `count()` function to get the length of an array.
Python - String Length
len("string")
The Python `len()` function returns the length of a string.
Java - String Length
str.length();
The Java String class provides the `length()` method.
Javascript - String Length
str.length;
Javascript strings have the length property.
C - String Length
#include<string.h>
strlen("string");
C uses the `strlen()` function to get the length of strings.
PHP - String Length
strlen("string");
PHP uses the `strlen()` function to get the length of strings.
Python - Index List / Array
list[0]
Python uses square brackets to get a list index.
Java - Index List / Array
arr[0];
Java uses square brackets to get an array index.
Javascript - Index List / Array
arr[0];
Javascript uses square brackets to get an array index.
C - Index List / Array
arr[0];
C uses square brackets to get an array index.
PHP - Index List / Array
arr[0];
PHP uses square brackets to to get an array index.
Python - Add to List / Array
list.append(x)
Python uses the `append()` method to add elements to a list.
Java - Add to List / Array
ArrayList<String> arr = new ArrayList<String>();
arr.add(x);
The Java `ArrayList` class provides the `add()` method to append an element to an array.
Javascript - Add to List / Array
arr.push(x);
Javascript uses the `push()` method to add elements to an array.
C - Add to List / Array
arr[i] = element;
C uses direct index assignment to modify values in an array.
PHP - Add to List / Array
array_push( $arr, $newItem );
$arr[] = $newItem;
PHP provides the `array_push()` function or direct item assignment to an empty index to add elements to an array.
Python - Remove from List / Array
list.pop()
Python uses the `pop()` method to remove (and return) the last element from a list.
Java - Remove from List / Array
ArrayList<String> arr = new ArrayList<String>();
arr.remove(i);
The Java ArrayList class provides the `remove()` method to remove an array element at the specified index.
Javascript - Remove from List / Array
arr.pop();
Javascript uses the `pop()` method to remove (and return) the last element from an array.
C - Remove from List / Array
arr[i] = NULL;
C uses direct item assignment to nullify an array element.
PHP - Remove from List / Array
array_pop($arr);
PHP uses the `array_pop()` function to remove (and return) the last element from an array.
Python - Sort List / Array
l = [2, 3, 1]
l.sort()
nl = sorted(l)
Python lists are sorted in-place with the `.sort()` method. To return a new sorted list instead of sorting in-place, use the built-in `sorted()` function instead.
Java - Sort List / Array
import java.util.ArrayList;
import java.util.Collections;
...
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(1);
Collections.sort(a);
Java ArrayLists can be sorted in-place using the the `Collections.sort()` method.
Javascript - Sort List / Array
var a = [2, 3, 1];
a.sort();
Javascript arrays are sorted in-place with the `.sort()` method.
C - Sort List / Array
#include <stdio.h>
#include <stdlib.h>
...
int compare( const void* x, const void* y) {
int int_x = *((int*)x);
int int_y = *((int*)y);
if (int_x == int_y) return 0;
else if (int_x < int_y) return -1;
else return 1;
}
int a[] = {2, 3, 1};
qsort( a, 3, sizeof(int), compare );
C arrays can be sorted using the `qsort()` function along with a custom defined comparison function.
PHP - Sort List / Array
$a = [2, 3, 1];
sort($a);
PHP arrays can be sorted in-place using the `sort()` function.
Python - Replace List / Array Item
l = [ "a", "b", "z" ]
l[2] = "c"
Python uses index assignment to replace existing list items.
Java - Replace List / Array Item
import java.util.ArrayList;
...
ArrayList<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("z");
a.set(2, "c");
Java uses the `.set()` method to replace an item in an ArrayList.
Javascript - Replace List / Array Item
a = [ "a", "b", "z" ];
a[2] = "c";
Javascript uses index assignment to replace existing list items.
C - Replace List / Array Item
char a[] = {'a', 'b', 'z'};
a[2] = 'c';
C uses index assignment to replace existing list items.
PHP - Replace List / Array Item
$a = [ "a", "b", "z" ];
$a[2] = "c";
PHP uses index assignment to replace existing list items.
Python - Slice List / Array
l = ["a", "b", "c", "d", "e"]
b = l[0:3]
Python uses the `:` operator to get a slice of a list. The number before the colon is the index of the first element of the slice, inclusive. The number after the colon is the index of the the last item of the slice, exclusive. This example slice will return ['a', 'b', 'c'].
Java - Slice List / Array
import java.util.List;
import java.util.ArrayList;
...
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
a.add("d");
a.add("e");
List<String> b = a.subList(0, 3);
Java uses `.subList()` method to get an array slice. The first argument is the index of the first element of the slice, inclusive. The second argument is the index of the the last item of the slice, exclusive. This example slice will return ['a', 'b', 'c'].
Javascript - Slice List / Array
var a = ["a", "b", "c", "d", "e"];
b = a.slice(0, 3);
Javascript uses `.slice()` method to get an array slice. The first argument is the index of the first element of the slice, inclusive. The second argument is the index of the the last item of the slice, exclusive. This example slice will return ['a', 'b', 'c'].
C - Slice List / Array
char a[5] = {'a', 'b', 'c', 'd', 'e'};
char b[2];
memcpy(b, a, 3 * sizeof(*x));
C can effectively slice an array using the `memcpy()` function. The first argument is the array to copy the slice to. The second argument is the array to copy the slice from. The third argument is the size of the desired number of elements to slice. This example slice will return ['a', 'b', 'c'].
PHP - Slice List / Array
$a = ["a", "b", "c", "d", "e"];
$b = array_slice($a, 0, 3);
PHP uses uses `array_slice()` function to get an array slice. The first argument is the index of the first element of the slice, inclusive. The second argument is the index of the the last item of the slice, exclusive. This example slice will return ['a', 'b', 'c'].
Python - Replace Array Slice
l = ["a", "b", "c", "d", "e"]
l[0:3] = "x"
Python allows assignments to slices which will have the effect of replacing the slice. In this example the final list will be ['x', 'd', 'e']
Java - Replace Array Slice
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
a.add("d");
a.add("e");
a = a.subList(3, 5);
a.add(0, "x");
Java can use a combination of the `.sublist()` method, reassignment, and the `.add()` method to replace slices. In this example the final array will be ['x', 'd', 'e']
Javascript - Replace Array Slice
var a = ["a", "b", "c", "d", "e"];
a = ["x"].concat(a.slice(3, 5));
Javascript can use the `.concat()` method along with the `.slice()` method to redefine an array based on the desired slices. In this example the final array will be ['x', 'd', 'e']
C - Replace Array Slice
#include <stdio.h>
...
char x[5] = {'a', 'b', 'c', 'd', 'e'};
char *n = 'x';
char *nl = '