Common code statements in different languages for quick reference and comparison: Java, JavaScript, Kotlin, Objective-C, Python, Ruby, Scala, Swift.
- Intro
- Getting started
- Variables
- Functions and properties
- Strings
- Functions
- Classes and objects
- Snippets
- More
This document shows common code constructions in some popular languages. You can use it as a quick reference or to see languages side by side, to compare their differences and similarities.
If you see something that could be improved, added or fixed please let me know. I will gladly consider your suggestions.
This document was edited using the wonderful StackEdit.
Instructions to install language interpreter and write a minimal runnable program.
To edit files you may use editors like Brackets, Sublime Text or Atom.
Java
- Install Java JDK.
- Create
HelloWorld.java
file with the content shown below. - From the command line, compile the file with
javac HelloWorld.java
(a file calledHelloWorld.class
will be created. - Execute the compiled file with
java HelloWorld
(note you don't add the file extension there, just the class name).
In a Java program you need at least to declare a class and a function called main
(which is the program entry point). Any statement must go inside a function. And any function must go inside a class.
public class HelloWorld {
public static void main(String... args) {
System.out.println("Hello world!");
}
// More functions here
}
JavaScript
You may execute JavaScript from the console of your browser. Find out how to open the console in your favourite browser. In Chrome it's Alt+Cmd+J
.
You can include JavaScript files from an HTML file. When the HTML is loaded by the browser, the JavaScript files will be executed.
You can also execute scripts from the command line. To do that:
- Install node.js.
- Create
hello_world.js
file with the content below. - Execute the script with
node hello_world.js
.
"use strict" // start your scripts with this to avoid bad practices
console.log("Hello world!"); // semicolon is not mandatory but recommended
Kotlin
Kotlin can be used standalone or (most probably) integrated in a Java project inside Eclipse or IntelliJ IDEA. You can also try it here online.
For a standalone program you could create a HelloWorld.kt
file with:
fun main(args: Array<String>) {
println("Hello world!")
}
Objective-C
Read about how to use Xcode to create iOS apps. Consider also using Swift instead of Objective-C, since it's a clearer and more modern language, and also easier to use from the command line.
Python
- Download and install Python.
- Create a file
hello_world.py
with content below. - Execute the script with
python hello_world.py
.
print "Hello world!"
Ruby
- Download and install Ruby.
- Create a file
hello_world.rb
with content below. - Execute the script with
ruby hello_world.rb
.
puts "Hello world!"
Scala
- Download and install Scala.
- Create a file
HelloWorld.scala
with content below. - Execute the script with
scala HelloWorld.scala
.
println("Hello world!")
Swift
Read about how to use Xcode to create iOS apps. If you installed Xcode, you may also run Swift code from the command line:
- Create a file
HelloWorld.swift
with content below. - Execute the script with
swift HelloWorld.swift
.
// You usually need to import Foundation.
// Or import UIKit if you want to use UI classes.
import Foundation
print("Hello world!")
Basic variable declaration and initialization using some common types (numbers, strings, booleans). Here you can also see name conventions (camelCase
, snake_case
) and line comments.
Some languages are statically typed:; every variable has a permanent type, specified when it's declared. In some languages like Kotlin, Scala or Swift you don't need to specify the type; it is inferred from the value you assign to it in the initialization.
Java
int age = 18;
final String name = "John Smith"; // Constant (final)
double height = 1.75;
boolean hasChildren = false;
String none = null;
JavaScript
let age = 18; // `let` from ES6, previously `var`
const name = "John Smith"; // Constant. Strings also with ''.
let height = 1.75;
let hasChildren = false;
let none = null;
let none2 = undefined; // not the same as null
Kotlin
var age = 18
val name = "John Smith" // Constant (val)
var height : Double = 1.75 // Explicit type is optional
var hasChildren = false
var none = null
Objective-C
int age = 18;
NSString* name = @"John Smith";
double height = 1.75;
BOOL hasChildren = NO; // also `false`
NSString* none = nil
Python
age = 18
name = "John Smith" # Also with ''
height = 1.75
has_children = False
none = None
Ruby
age = 18
name = 'John Smith' # With "" you can interpolate
height = 1.75
has_children = false
none = nil
Scala
var age = 18
val name = "John Smith" // Constant (val)
var height : Double = 1.75 // Explicit type is optional
var hasChildren = false
var none = null
Swift
var age = 18
let name = "John Smith" // Constant (let)
var height : Double = 1.75 // Explicit type is optional
var hasChildren = false
var none = nil
Basic usage of functions and properties. I added this section as an introduction for the following ones.
Java
User user = database.find(email, pwd);
System.out.println("Hello " + user.getName());
JavaScript
let user = database.find(email, pwd);
console.log("Hello " + user.name);
Kotlin
var user = database.find(email, pwd)
println("Hello " + user.name)
Objective-C
User* user = [database find:email pass:pwd]; // Call syntax is quite Weird
NSLog(@"Hello %@", user.name); // Sometimes you use this C-style syntax
Python
user = database.find(email, pwd)
print "Hello " + user.name
Ruby
user = database.find(email, pwd)
puts "Hello #{user.name}"
Scala
val user = database.find(email, pwd)
println("Hello " + user.name)
Swift
// From 2nd parameter you write `parameter:argument`
let user = database.find(email, pass:pwd)
print("Hello \(user.name)")
Common operations using strings.
Java
int length = name.length(); // Length
String text = name + " is " + age; // Concatenate
boolean b = name.contains("Smith"); // Find
b = name.indexOf("Smith") >= 0; // Index
String first = name.substring(0, 4); // Substring
char c = name.charAt(4); // Char at
String[] parts = text.split(" "); // Split
JavaScript
let length = name.length(); // Length
let text = name + " is " + age; // Concatenate
let b = name.indexOf("Smith") >= 0; // Find/Index
let first = name.substring(0, 4); // Substring
let c = name[4]; // Char at
let parts = text.split(" "); // Split
Kotlin
val length = name.length // Length
var text = "$name is $age" // Interpolate
text += ", height: " + height // Concatenate
var found = name.contains("Smith") // Find
found = name.indexOf(" ") >= 0 // Index
val firstName = name.substring(0, 4) // Substring
val c = name(4) // Char at
val parts = text.split("\\s".toRegex()) // Split (explicit regex)
text = parts.joinToString(" ") // Join
Objective-C
int lenght = [name length]; // Length
NSString* text = [NSString stringWithFormat:
@"%@ is %@", name, @(age)]; // Interpolate
text = [text stringByAppendingString:@" years old"]; // Concatenate
BOOL b = [name rangeOfString:@"Smith"].location != NSNotFound; // Find/Index
NSString* first = [name substringToIndex:4]; // Substring
NSString* last = [name substringWithRange:NSMakeRange(5, 10)]; // Substring
NSArray<NSString*>* parts = [text componentsSeparatedByString:@" "]; // Split
Python
length = len(name) # length
text = name + " is " + str(age) # Concatenate
found = "Smith" in name # Find
found = name.find(" ") >= 0 # Index
first_name = name[0:4] # Substring (also `name[:4]`)
last_name = name[-5:] # Substring
c = name[4] # Char at
parts = text.split(" ") # Split
Ruby
length = name.length # length
text = "#{name} is #{age}" # Interpolate
text += ", height: " + height.to_s # Concatenate
found = name.include? "Smith" # Find
index = name.index(" ") # Index (truthy if found)
first_name = name[0...4] # Substring
last_name = name[-5..-1] # Substring
c = name[4] # Char at
parts = text.split(" ") # Split
text = parts.join(" ") # Join
Scala
val length = name.length // Length
var text = s"$name is $age" // Interpolate
text += ", height: " + height // Concatenate
var found = name.contains("Smith") // Find
found = name.indexOf(" ") >= 0 // Index
val firstName = name.substring(0, 4) // Substring
val c = name(4) // Char at
val parts = text.split(" ") // Split
text = parts.mkString(" ") // Join
Swift
In the snippets section there's a String
extension that is used in this code.
let count = name.characters.count // Length
var text = "\(name) is \(age)" // Interpolate
text = String(format: "%@ is %@", name, String(age)) // Interpolate
text += ", height: " + String(height) // Concatenate
let range = string.rangeOfString("Smith") // Index
let found = range != nil // Find
// These lines are using the extension mentioned above
let length = name.length() // Length
let firstName = name.substring(0, 4) // Substring
let parts = text.split(" ") // Split
How to declare and call functions.
Java
double triangleArea(double base, double height) {
return base * height / 2;
}
void sayHello() {
System.out.println("Hello!");
}
// This code would be placed into some method
double area = triangleArea(10, 15);
sayHello();
JavaScript
function triangleArea(base, height) {
return base * height / 2;
}
function sayHello() {
console.log("Hello!");
}
let area = triangleArea(10, 15);
sayHello();
Kotlin
fun triangleArea(base: Double, height: Double): Double {
return base * height / 2
}
fun sayHello(): Unit {
println("Hello!")
}
fun main(args: Array<String>) {
val area = triangleArea(10.0, 15.0)
sayHello()
}
Shorter way to define functions:
// For one-liners, return type is inferred
fun triangleArea(base: Double, height: Double) = base * height / 2
// If return type is Unit you can omit it
fun sayHello() {
println("Hello!")
}
Objective-C
In Objective-C you call functions using the identifiers to the left of the colons (i.e. triangleAreaWithBase
and height
), and inside the function you refer to the arguments using the identifiers to the right of the colons (i.e. b
an h
).
+ (double) triangleAreaWithBase:(double)b height:(double)h {
return b * h / 2;
}
+ (void) sayHello {
NSLog(@"Hello!");
}
// This code would be placed into some method
double area = [self triangleAreaWithBase:10 height:15];
[self sayHello];
Python
Blocks of code in python are recognised by indentation. There's no end
keyword or { }
symbols to delimit them.
def triangleArea(base, height):
return base * height / 2
def sayHello():
print "Hello!"
area = triangleArea(10, 15)
sayHello()
Ruby
In Ruby parenthesis for functions are optional. Even for declaring or calling functions with multiple parameters. Anyway, we have used parenthesis in this example.
def triangleArea(base, height)
return base * height / 2
end
def sayHello
puts 'Hello!'
end
area = triangleArea(10, 15)
sayHello
Scala
def triangleArea(base: Double, height: Double): Double = {
return base * height / 2
}
def sayHello(): Unit = {
println("Hello!")
}
val area = triangleArea(10, 15)
sayHello()
Shorter way to define functions:
// For one-liners, return type is inferred
def triangleArea(base: Double, height: Double) = base * height / 2
// If return type is Unit you can omit it
def sayHello() {
println("Hello!")
}
Swift
func triangleArea(base: Double, height: Double) -> Double {
return base * height / 2
}
func sayHello() {
print("Hello!")
}
let area = triangleArea(10, height:15)
sayHello()
When calling a function in Swift, you need to specify the name of all parameters except for the first one. This is the default, but it's configurable:
// Here we declare external parameter names
func triangleAreaExplicit(b base: Double, h height: Double) -> Double {
return base * height / 2
}
// Here the call will be similar to other languages
func triangleAreaImplicit(base: Double, _ height: Double) -> Double {
return base * height / 2
}
let area2 = triangleAreaExplicit(b: 10, h:15)
let area3 = triangleAreaImplicit(10, 15)
Java
import java.util.*; // For collections, except arrays
// arrays are created with a specific size, which can't change
int n = 10;
int[] array = new int[n]; // array with n slots
array[0] = 5;
array[1] = 10;
int length = array.length; // 10
int a0 = array[0] // 5
int a2 = array[2] // 0 (default value for `int`)
// In type parameters we can't use primitive types like `int`
List<Integer> list = new ArrayList<>(); // empty list
list.add(5);
list.add(10);
num size = list.size(); // 2
int b0 = list.get(0); // 5
int b3 = list.get(3); // IndexOutOfBoundsException
JavaScript
let array = [5, 10]; // can be initially empty or not
array.push(15); // add
array.push("text"); // mix types
array.push(null);
let a0 = array[0]; // 5
let a3 = array[3]; // "text"
let a4 = array[4]; // null
let a5 = array[5]; // undefined
int length = array.length; // 5
Python
array = [5, 10] # can be initially empty or not
array.append(15) # add
array.append("text") # mix types
array.append(None)
a0 = array[0] # 5
a3 = array[3] # "text"
a4 = array[4] # None
a5 = array[5] # IndexError: list index out of range
length = len(array) # 5
Here you will find useful snippets that are referred in some code examples.
Swift
/**
* Swift string manipulation is somewhat complex.
* This extension methods simplify things.
* NOTE: This might be obsolete due to Swift updates.
*/
extension String {
// http://stackoverflow.com/questions/24044851 - substring and ranges
func substring(range: NSRange) -> String {
return substring(range.location, range.location + range.length)
}
func substring(start:Int, _ end:Int) -> String {
let from = index(start)
let to = index(end)
return self[from..<to]
}
func index(pos: Int) -> Index {
return pos >= 0 ? startIndex.advancedBy(pos) : endIndex.advancedBy(pos)
}
func length() -> Int {
return characters.count
}
func split(separator: String) -> [String] {
return componentsSeparatedByString(separator)
}
}
- conditions and flow control (if/else, while, for)
- Classes and objects
- Maps/dictionaries
- Dates
- Pass functions as arguments
- primitives/classes and wrapping
crack!! 👍