diff --git a/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff b/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff new file mode 100644 index 0000000..9e61285 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf b/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf new file mode 100644 index 0000000..1413fc6 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot b/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot new file mode 100644 index 0000000..b93a495 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 b/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 new file mode 100644 index 0000000..64539b5 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg b/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg new file mode 100644 index 0000000..94fb549 --- /dev/null +++ b/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..58f5a0f --- /dev/null +++ b/index.html @@ -0,0 +1,3965 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+ +
+
+
+

Ruby

+
+
+

Python

+
+
+

String

+

+Create + + + + + +

+
+
+
greeting = 'Hello World!'
+puts greeting
+
+ +
Hello World!
+
+
+
+
greeting = 'Hello World!'
+print(greeting)
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
puts "Don't worry," + ' be happy'
+
+ +
Don't worry, be happy
+
+
+
+
print("Don't worry," + ' be happy')
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+ +
Don't worry, be happy
+
+
+
+
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+ +
Don't worry, be happy
+
+[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+ +
This is funny! I am like him!
+
+
+
+
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
puts 'You should work'.gsub('work', 'rest')
+
+ +
You should rest
+
+
+
+
print('You should work'.replace('work', 'rest'))
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
puts 'I like beer'.split
+
+ +
I
+like
+beer
+
+
+
+
print('I like beer'.split())
+
+ +
['I', 'like', 'beer']
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
puts ' eh? '.strip
+
+ +
eh?
+
+
+
+
print(' eh? '.strip())
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
puts 'string' == 'string'
+puts 'string' != 'string'
+
+ +
true
+false
+
+
+
+
print('string' == 'string')
+print('string' != 'string')
+
+ +
True
+False
+
+
+
+

+Regex + + + + + +

+
+
+
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+ +
nil
+0
+
+
+
+
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+ +
None
+<re.Match object; span=(0, 1), match='a'>
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
i = 9
+i += 1
+puts i
+
+ +
10
+
+
+
+
i = 9
+i += 1
+print(i)
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+ +
true
+true
+false
+
+
+
+
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+ +
True
+True
+False
+
+
+
+

+Random + + + + + +

+
+
+
puts rand(1..2)
+
+ +
1
+
+
+
+
import random
+
+print(random.randint(1, 2))
+
+ +
2
+
+
+
+

+Float + + + + + +

+
+
+
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+ +
4
+4.5
+4
+5
+
+
+
+
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2))  # rounds half to even
+
+ +
4
+4.5
+4
+4
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
puts 'hi'.class
+puts 1.class
+
+ +
String
+Fixnum
+
+
+
+
print(type('hi'))
+print(type(1))
+
+ +
<class 'str'>
+<class 'int'>
+
+
+
+

+Int to Float + + + + + +

+
+
+
puts 10.to_f
+
+ +
10.0
+
+
+
+
print(float(10))
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
puts 10.to_s
+
+ +
10
+
+
+
+
print(str(10))
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
puts '5'.to_i
+
+ +
5
+
+
+
+
print(int('5'))
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
puts '10'.is_a? String
+
+ +
true
+
+
+
+
print(isinstance('10', str))
+
+ +
True
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
def check(label, fn, values)
+  puts label
+  values.each do |value|
+    begin
+      result = fn.call(value) ? 'true' : 'false'
+    rescue NoMethodError => e
+      result = "error: #{e}"
+    end
+    puts format("  %-9p - %s", value, result)
+  end
+  puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+ +
if value:
+  "string"  - true
+  ""        - true
+  [1, 2, 3] - true
+  []        - true
+  5         - true
+  0         - true
+  true      - true
+  false     - false
+  nil       - false
+
+if value.nil?:
+  "string"  - false
+  ""        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  true      - false
+  false     - false
+  nil       - true
+
+if value.empty?:
+  "string"  - false
+  ""        - true
+  [1, 2, 3] - false
+  []        - true
+  5         - error: undefined method `empty?' for 5:Fixnum
+  0         - error: undefined method `empty?' for 0:Fixnum
+  true      - error: undefined method `empty?' for true:TrueClass
+  false     - error: undefined method `empty?' for false:FalseClass
+  nil       - error: undefined method `empty?' for nil:NilClass
+
+
+
+
+
def check(label, fn, values):
+    print(label)
+    for value in values:
+        try:
+            result = 'true' if fn(value) else 'false'
+        except TypeError as e:
+            result = 'error: %s' % e
+        print("  %-9r - %s" % (value, result))
+    print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+ +
if value:
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - true
+  0         - false
+  True      - true
+  False     - false
+  None      - false
+
+if value is None:
+  'string'  - false
+  ''        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  True      - false
+  False     - false
+  None      - true
+
+if len(value):
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - error: object of type 'int' has no len()
+  0         - error: object of type 'int' has no len()
+  True      - error: object of type 'bool' has no len()
+  False     - error: object of type 'bool' has no len()
+  None      - error: object of type 'NoneType' has no len()
+
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
arr = %w(first second)
+puts arr
+
+ +
first
+second
+
+
+
+
arr = ['first', 'second']
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+Add + + + + + +

+
+
+
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+ +
first
+second
+
+
+
+
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+With different types + + + + + +

+
+
+
puts ['first', 1]
+
+ +
first
+1
+
+
+
+
print(['first', 1])
+
+ +
['first', 1]
+
+
+
+

+Include? + + + + + +

+
+
+
puts [1, 2].include? 1
+
+ +
true
+
+
+
+
print(1 in [1, 2])
+
+ +
True
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].each do |num|
+  puts num
+end
+
+ +
1
+2
+
+
+
+
for num in [1, 2]:
+  print(num)
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
%w(one two).each_with_index do |num, i|
+  puts num
+  puts i
+end
+
+ +
one
+0
+two
+1
+
+
+
+
for i, num in enumerate(['one', 'two']):
+  print(num)
+  print(i)
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+ +
one
+two
+
+
+
+
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+ +
10
+
+
+
+
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+ +
10
+20
+
+
+
+
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+ +
[10, 20]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+ +
2
+10
+20
+40
+
+
+
+
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+ +
[2, 10, 20, 40]
+
+
+
+

+Concatenation + + + + + +

+
+
+
puts [1, 2] + [3, 4]
+
+ +
1
+2
+3
+4
+
+
+
+
print([1, 2] + [3, 4])
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Sort + + + + + +

+
+
+
puts [4, 2, 3, 1].sort
+
+ +
1
+2
+3
+4
+
+
+
+
print(sorted([4, 2, 3, 1]))
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+ +
forth
+
+
+
+
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
puts [1, 2, 3].size 
+
+ +
3
+
+
+
+
print(len([1, 2, 3]))
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+ +
2
+
+
+
+
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
puts [1, 2, 3].reduce(:+)
+
+ +
6
+
+
+
+
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3]))  # a more Pythonic example
+
+ +
6
+6
+
+
+
+

+Index of element + + + + + +

+
+
+
puts ['a', 'b', 'c'].index('c')
+
+ +
2
+
+
+
+
print(['a', 'b', 'c'].index('c'))
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+ +
a
+c
+
+
+
+
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+ +
['a', 'c']
+
+
+
+

+Unique + + + + + +

+
+
+
puts %w(a b a).uniq
+
+ +
a
+b
+
+
+
+
print(set(['a', 'b', 'a']))
+
+ +
{'a', 'b'}
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Add + + + + + +

+
+
+
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Iterate + + + + + +

+
+
+
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+  puts key, value
+end
+
+ +
font_size
+10
+font_family
+Arial
+
+
+
+
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+  print(key, value)
+
+ +
font_size 10
+font_family Arial
+
+
+
+

+Include? + + + + + +

+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+ +
true
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+ +
True
+
+
+
+

+Get value + + + + + +

+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+ +
10
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+ +
2
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+ +
Garlic gum is not funny
+
+
+
+
try_it = True
+if try_it:
+    print('Garlic gum is not funny')
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
COST = 100
+COST = 50
+puts COST
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here
+50
+
+
+
+
COST = 100
+COST = 50
+print(COST)
+
+ +
50
+
+
+
+

+Constant list + + + + + +

+
+
+
module Colors
+  RED = '#FF0000'
+  GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+ +
#00FF00
+
+
+
+
class Colors:
+    RED = '#FF0000'
+    GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+ +
#00FF00
+
+
+
+

+Struct + + + + + +

+
+
+
Customer = Struct.new(:name, :address) do
+  def greeting
+    "Hello #{name}!"
+  end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+ +
Hello Dave!
+
+
+
+
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+    def greeting(self):
+        return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+ +
Hello Dave!
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
puts 'Hello' if true
+
+ +
Hello
+
+
+
+
if True:
+    print('Hello')
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
angry = false
+puts 'smile!' unless angry
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+    print('smile!')
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
if true
+  puts 'work'
+else
+  puts 'sleep'
+end
+
+ +
work
+
+
+
+
if True:
+  print('work')
+else:
+  print('sleep')
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
puts 'no' if true && false
+puts 'yes' if true || false
+
+ +
yes
+
+
+
+
if True and False:
+    print('no')
+if True or False:
+    print('yes')
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
foo = 'Hello!'
+case foo
+when 1..5
+  puts "It's between 1 and 5"
+when 10, 20
+  puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+  puts "You passed a string '#{foo}'"
+else
+  puts "You gave me '#{foo}'"
+end
+
+ +
You passed a string 'Hello!'
+
+
+
+
foo = 'Hello!'
+if foo in range(1, 6):
+    print("It's between 1 and 5")
+elif foo in (10, 20):
+    print('10 or 20')
+elif foo == 'And':
+    print('case in one line')
+elif isinstance(foo, str):
+    print("You passed a string %r" % foo)
+else:
+    print("You gave me %r" % foo)
+
+ +
You passed a string 'Hello!'
+
+
+
+

+Switch as else if + + + + + +

+
+
+
score = 76
+grade = case
+        when score < 60 then 'F'
+        when score < 70 then 'D'
+        when score < 80 then 'C'
+        when score < 90 then 'B'
+        else 'A'
+        end
+puts grade
+
+ +
C
+
+
+
+
score = 76
+grades = [
+    (60, 'F'),
+    (70, 'D'),
+    (80, 'C'),
+    (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+ +
C
+
+
+
+

+Ternary + + + + + +

+
+
+
puts false ? 'no' : 'yes'
+
+ +
yes
+
+
+
+
print('no' if False else 'yes')
+
+ +
yes
+
+
+
+

+If assign + + + + + +

+
+
+
result =
+if true
+  'a'
+else
+  'b'
+end
+puts result
+
+
+ +
a
+
+
+
+
result = 'a' if True else 'b'
+print(result)
+
+ +
a
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
(1..3).each do |i|
+  puts "#{i}. Hi"
+end
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
for i in range(1, 4):
+    print('%d. Hi' % i)
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
(0..4).step(2) do |i|
+  puts i
+end
+
+ +
0
+2
+4
+
+
+
+
for i in range(0, 5, 2):
+    print(i)
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
3.times do
+  puts 'Hi'
+end
+
+ +
Hi
+Hi
+Hi
+
+
+
+
for i in range(3):
+  print('Hi')
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
i = 0
+while i < 3
+  i += 1
+end
+puts i
+
+ +
3
+
+
+
+
i = 0
+while i < 3:
+  i += 1
+print(i)
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
i = 0
+i += 1 until i == 3
+puts i
+
+ +
3
+
+
+
+
i = 0
+while i != 3:
+    i += 1
+print(i)
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+
greetings = Array.new(3) do |i|
+  "#{i + 1}. Hello!"
+end
+puts greetings
+
+ +
1. Hello!
+2. Hello!
+3. Hello!
+
+
+
+
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+ +
['1. Hello!', '2. Hello!', '3. Hello!']
+
+
+
+

+Break + + + + + +

+
+
+
3.times do |time|
+  puts "#{time + 1}. Hi"
+  break if time == 1
+end
+
+ +
1. Hi
+2. Hi
+
+
+
+
for time in range(1, 4):
+  print("%d. Hi" % time)
+  if time == 2:
+    break
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
3.times do |time|
+  next if time == 1
+  puts "#{time + 1}. Hi"
+end
+
+ +
1. Hi
+3. Hi
+
+
+
+
for time in range(1, 4):
+  if time == 2:
+      continue
+  print("%d. Hi" % time)
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+ +
1
+3
+
+
+
+
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
puts Math.sqrt(9)
+
+ +
3.0
+
+
+
+
import math
+
+print(math.sqrt(9))
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
begin
+  1 / 0
+rescue
+  puts "Can't divide"
+ensure
+  puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+ +
Can't divide
+But that's ok
+Can't divide
+
+
+
+
try:
+  1 / 0
+except:
+  print("Can't divide")
+finally:
+  print("But that's ok")
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
begin
+  1 / 0
+rescue => e
+  puts e.message
+end
+
+ +
divided by 0
+
+
+
+
try:
+  1 / 0
+except Exception as e:
+  print(e)
+
+ +
division by zero
+
+
+
+

+Method + + + + + +

+
+
+
def divide(num1, num2)
+  num1 / num2
+rescue => e
+  puts e.message
+end
+divide(1, 0)
+
+ +
divided by 0
+
+
+
+
def divide(num1, num2):
+  try:
+    num1 / num2
+  except Exception as e:
+    print(e)
+divide(1, 0)
+
+ +
division by zero
+
+
+
+

+Throw exception + + + + + +

+
+
+
begin
+  fail 'An error!'
+rescue => e
+  puts e.message
+end
+
+ +
An error!
+
+
+
+
try:
+  raise Exception('An error!')
+except Exception as e:
+  print(e)
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+ +
Hello
+World
+
+
+
+
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+    print(f.read())
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+ +

+
+
+
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+    f.write('Some glorious content')
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
puts Dir.getwd
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
import os
+
+print(os.getcwd())
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
puts __FILE__
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb
+
+
+
+
print(__file__)
+
+ +
/Users/evmorov/projects/lang-compare/code/python/file_path.py
+
+
+
+

+Dir path + + + + + +

+
+
+
puts File.dirname(__FILE__)
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+

+Parent dir path + + + + + +

+
+
+
puts File.expand_path File.join(__FILE__, '..', '..')
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+ +
/Users/evmorov/projects/lang-compare/code/php
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
def hey
+  puts 'How are you?'
+end
+hey
+
+ +
How are you?
+
+
+
+
def hey():
+  print('How are you?')
+hey()
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
def sweets(buy, *brands)
+  puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+ +
snickers
+twix
+bounty
+
+
+
+
def sweets(buy, *brands):
+  if buy:
+      print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+ +
('snickers', 'twix', 'bounty')
+
+
+
+

+Default value for argument + + + + + +

+
+
+
def send(abroad = false)
+  puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+ +
Send locally
+Send abroad
+
+
+
+
def send(abroad=False):
+  print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
def multiple(a, b)
+  a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+  return 0 if a == 0
+  a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+ +
6
+0
+nil
+
+
+
+
def multiply(a, b):
+    return a * b
+
+def divide(a, b):
+    return 0 if a == 0 else a / b
+
+def default_value():
+    pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+ +
6
+0
+None
+
+
+
+

+Closure + + + + + +

+
+
+
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+ +
4
+9
+Hello World!
+
+
+
+
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+ +
[4, 9]
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+
def my_select(arr)
+  selected = []
+  arr.each do |a|
+    selected.push a if yield(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+  selected = []
+  arr.each do |a|
+    selected.push a if filter.call(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+ +
1
+5
+1
+5
+
+
+
+
def select(arr):
+    yield from arr
+
+def select_filter(arr, filter):
+    for a in arr:
+        if filter(a):
+            yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+ +
[1, 5]
+[1, 5]
+
+
+
+

+Block binding + + + + + +

+
+
+
class Action
+  def self.say(&sentence)
+    @name = 'Ann'
+    puts sentence.call
+  end
+end
+
+class Person
+  def initialize(name)
+    @name = name
+  end
+
+  def greet
+    Action.say { "My name is #{@name}!" }
+  end
+end
+
+Person.new('Alex').greet
+
+ +
My name is Alex!
+
+
+
+
class Action:
+  name = 'Ann'
+
+  @staticmethod
+  def say(sentence):
+    print(sentence())
+
+
+class Person:
+  def __init__(self, name):
+    self.name = name
+
+  def greet(self):
+    Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+ +
My name is Alex!
+
+
+
+

+Initialize in runtime + + + + + +

+
+
+
class ProccessElements
+  def self.element(el_name)
+    define_method "#{el_name}_element" do |content|
+      "<#{el_name}>#{content}</#{el_name}>"
+    end
+  end
+end
+
+class HtmlELements < ProccessElements
+  element :div
+  element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+ +
<div>hello</div>
+
+
+
+
class ProccessElements:
+  def __init__(self):
+    def element(el_name):
+      def render(content):
+        return '<{0}>{1}</{0}>'.format(el_name, content)
+      return render
+
+    for el_name in self.elements:
+      setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+  elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+ +
<div>hello</div>
+
+
+
+

+Alias + + + + + +

+
+
+
class Greetings
+  def hey
+    puts 'How are you?'
+  end
+  alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+ +
How are you?
+
+
+
+
class Greetings:
+  def hey(self):
+    print('How are you?')
+  hi = hey
+
+Greetings().hi()
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+Animal.new.walk
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+Animal().walk()
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal
+  def initialize(name)
+    @name = name
+  end
+
+  def walk
+    puts "My name is #{@name} and I'm walking"
+  end
+end
+
+Animal.new('Kelya').walk
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+
+  def walk(self):
+    print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal
+  def walk
+    bark
+    guard
+    puts "I'm walking"
+  end
+
+  def bark
+    puts 'Wuf!'
+  end
+
+  private
+
+  def guard
+    puts 'WUUUF!'
+  end
+end
+
+Animal.new.walk
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    self.bark()
+    self._guard()
+    print("I'm walking")
+
+  def bark(self):
+    print('Wuf!')
+
+  # Private by convention
+  def _guard(self):
+    print('WUUUF!')
+
+Animal().walk()
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal
+  def self.feed
+    puts 'Om nom nom'
+  end
+end
+
+Animal.feed
+
+ +
Om nom nom
+
+
+
+
class Animal:
+  @classmethod
+  def feed(cls):
+    print('Om nom nom')
+
+Animal.feed()
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+
class Animal
+  def eat(food)
+    puts 'Om nom nom' if meat? food
+  end
+
+  private
+
+  def meat?(food)
+    food == 'meat'
+  end
+end
+
+Animal.new.eat('meat')
+
+ +
Om nom nom
+
+
+
+
class Animal:
+  def eat(self, food):
+    if self._is_meat(food):
+      print('Om nom nom')
+
+  def _is_meat(self, food):
+    return food == 'meat'
+
+Animal().eat('meat')
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal
+  def initialize(name)
+    @name = name
+    greet
+  end
+
+  private
+
+  def greet
+    puts "Hello! My name is #{@name}"
+  end
+end
+
+Animal.new('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+    self._greet()
+
+  def _greet(self):
+    print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal
+  def take(toy)
+    @toy = toy
+  end
+
+  def play
+    puts "I'm playing with #{@toy}"
+  end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+ +
I'm playing with a ball
+
+
+
+
class Animal:
+  def take(self, toy):
+    self.toy = toy
+
+  def play(self):
+    print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal
+  attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+ +
Kelya
+
+
+
+
class Animal:
+  name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+class Dog < Animal
+  def sing
+    puts 'Bark!'
+  end
+end
+
+Dog.new.walk
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+class Dog(Animal):
+  def sing(self):
+    print('Bark!')
+
+Dog().walk()
+
+ +
I'm walking
+
+
+
+

+Mixin + + + + + +

+
+
+
module Moving
+  def walk
+    puts "#{self.class.name} is walking"
+  end
+end
+
+module Interacting
+  def talk
+    puts "#{self.class.name} is talking"
+  end
+end
+
+class Human
+  include Moving
+  include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+ +
Human is walking
+Human is talking
+
+
+
+
class Moving:
+  def walk(self):
+    print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+  def talk(self):
+    print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+    pass
+
+human = Human()
+human.walk()
+human.talk()
+
+ +
Human is walking
+Human is talking
+
+
+
+

+Has method? + + + + + +

+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+ +
true
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+ +
True
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
# it's a comment
+
+ +

+
+
+
# it's a comment
+
+ +

+
+
+

+Assign value if not exist + + + + + +

+
+
+
speed = 0
+speed ||= 15
+puts speed
+
+ +
0
+
+
+
+
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+ +
0
+
+
+
+

+Safe navigation + + + + + +

+
+
+[ 2.3 ]
class Winner
+  attr_reader :address
+
+  def initialize
+    # @address = Address.new
+  end
+end
+
+class Address
+  attr_reader :zipcode
+
+  def initialize
+    @zipcode = 192187
+  end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+ +
No prize without zipcode
+
+
+
+No easy way to do that +
+
+

+Import another file + + + + + +

+
+
+
# other_file_to_import.rb
+# class Import
+#   def initialize
+#     puts 'I am imported!'
+#   end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+ +
I am imported!
+
+
+
+
# other_file_to_import.py
+# class Import:
+#   def __init__(self):
+#     print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+
one, two = [1, 2]
+puts one, two
+
+ +
1
+2
+
+
+
+
one, two = 1, 2
+print(one, two)
+
+ +
1 2
+
+
+
+

+Date + + + + + +

+
+
+
require 'date'
+puts Date.today
+
+ +
2024-05-28
+
+
+
+
import datetime
+print(datetime.date.today())
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
puts Time.now
+
+ +
2024-05-28 20:17:54 +0200
+
+
+
+
import datetime
+print(datetime.datetime.now())
+
+ +
2024-05-28 20:18:14.644332
+
+
+
+

+Not + + + + + +

+
+
+
angry = false
+puts 'smile!' if !angry
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+  print('smile!')
+
+ +
smile!
+
+
+
+

+Assign this or that + + + + + +

+
+
+
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+ +
bear
+
+
+
+
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+ +
bear
+
+
+
+

+Run command + + + + + +

+
+
+
puts `ruby -v`
+
+ +
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21]
+
+
+
+
import subprocess
+subprocess.call(['python3', '--version'])
+
+ +
Python 3.11.2
+
+
+
+
+ + + + + + + + + + diff --git a/java-java/index.html b/java-java/index.html new file mode 100644 index 0000000..8bead2f --- /dev/null +++ b/java-java/index.html @@ -0,0 +1,4319 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

Java

+
+
+

Java

+
+
+

String

+

+Create + + + + + +

+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+

+Float + + + + + +

+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+

+Int to Float + + + + + +

+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+

+String? + + + + + +

+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+

+With different types + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+

+Concatenation + + + + + +

+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Sort + + + + + +

+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+

+Unique + + + + + +

+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+

+Constant list + + + + + +

+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+

+Ternary + + + + + +

+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+

+Break + + + + + +

+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+

+Throw exception + + + + + +

+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+

+Dir path + + + + + +

+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+

+Parent dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+

+Return + + + + + +

+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+

+Has method? + + + + + +

+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+

+Date + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+

+Not + + + + + +

+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+

+Run command + + + + + +

+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
+ + + + + + + + + + diff --git a/java-javascript/index.html b/java-javascript/index.html new file mode 100644 index 0000000..5f79611 --- /dev/null +++ b/java-javascript/index.html @@ -0,0 +1,3982 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

Java

+
+
+

JavaScript

+
+
+

String

+

+Create + + + + + +

+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+No easy way to do that +
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+

+Float + + + + + +

+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+

+Int to Float + + + + + +

+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+No easy way to do that +
+
+

Array

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+

+With different types + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+

+Concatenation + + + + + +

+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+

+Sort + + + + + +

+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+

+Unique + + + + + +

+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+

+Constant list + + + + + +

+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+

+Ternary + + + + + +

+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+No easy way to do that +
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+

+Break + + + + + +

+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+

+Throw exception + + + + + +

+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+

+Get working dir path + + + + + +

+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+

+Dir path + + + + + +

+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+

+Parent dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+

+Default value for argument + + + + + +

+
+
+No easy way to do that +
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+

+Closure + + + + + +

+
+
+No easy way to do that +
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+No easy way to do that +
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+

+Block binding + + + + + +

+
+
+No easy way to do that +
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+

+Alias + + + + + +

+
+
+No easy way to do that +
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+No easy way to do that +
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+No easy way to do that +
+
+

+Field + + + + + +

+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+

+Has method? + + + + + +

+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+
// it's a comment
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+No easy way to do that +
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+

+Date + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+

+Time + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+

+Not + + + + + +

+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+

+Run command + + + + + +

+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
+ + + + + + + + + + diff --git a/java-php/index.html b/java-php/index.html new file mode 100644 index 0000000..517269e --- /dev/null +++ b/java-php/index.html @@ -0,0 +1,4026 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

Java

+
+
+

PHP

+
+
+

String

+

+Create + + + + + +

+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+ +
Hello World!
+
+
+

+Concatenation + + + + + +

+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+
<?php
+
+echo "Don't worry," . " be happy";
+
+ +
Don't worry, be happy
+
+
+

+Interpolation + + + + + +

+
+
+No easy way to do that +
+
+
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+ +
Don't worry, be happy
+
+
+

+Remove part + + + + + +

+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+ +
This is funny! I am like him!
+
+
+

+Replace + + + + + +

+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+ +
You should rest
+
+
+

+Split + + + + + +

+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+ +
array (
+  0 => 'I',
+  1 => 'like',
+  2 => 'beer',
+)
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+
<?php
+
+echo trim(" eh? ");
+ +
eh?
+
+
+

+Compare + + + + + +

+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+
<?php
+
+var_dump(strcmp("string", "string") == 0);
+ +
bool(true)
+
+
+
+

+Regex + + + + + +

+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+ +
bool(false)
+bool(true)
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+ +
10
+
+
+

+Compare + + + + + +

+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+ +
bool(true)
+bool(true)
+bool(false)
+
+
+
+

+Random + + + + + +

+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+
<?php
+
+echo rand(1, 2);
+ +
1
+
+
+

+Float + + + + + +

+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+ +
float(4.5)
+float(4.5)
+float(4)
+float(5)
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+ +
string
+object
+DateTime
+
+
+
+

+Int to Float + + + + + +

+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+
<?php
+
+var_dump((float)10);
+
+ +
float(10)
+
+
+
+

+Int to String + + + + + +

+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+
<?php
+
+var_dump((string)10);
+
+ +
string(2) "10"
+
+
+
+

+String to Int + + + + + +

+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+
<?php
+
+var_dump((int)"10");
+
+ +
int(10)
+
+
+
+

+String? + + + + + +

+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+ +
bool(true)
+bool(true)
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+ +
bool(false)
+bool(true)
+bool(true)
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+ +
Array
+(
+    [0] => first
+    [1] => second
+)
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+ +
Array
+(
+    [0] => first
+    [1] => second
+)
+
+
+
+

+With different types + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+
<?php
+
+print_r(["first", 1]);
+
+ +
Array
+(
+    [0] => first
+    [1] => 1
+)
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+ +
bool(true)
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+
<?php
+
+foreach ([1, 2] as $num) {
+    var_dump($num);
+}
+ +
int(1)
+int(2)
+
+
+
+

+Iterate with index + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+    echo "$key\n";
+    echo "$value\n";
+}
+ +
fontSize
+10
+fontFamily
+Arial
+
+
+
+

+Get first, last element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+ +
string(3) "one"
+string(3) "two"
+
+
+
+

+Find first + + + + + +

+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+    if ($n % 2 == 0) {
+        $first = $n;
+        break;
+    }
+}
+var_dump($first);
+ +
int(10)
+
+
+
+

+Select (find all) + + + + + +

+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+    return $n % 2 == 0;
+});
+print_r($filtered);
+
+ +
Array
+(
+    [2] => 10
+    [3] => 20
+)
+
+
+
+

+Map (change all) + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+    return $n * 2;
+}, $arr);
+print_r($mapped);
+ +
Array
+(
+    [0] => 2
+    [1] => 10
+    [2] => 20
+    [3] => 40
+)
+
+
+
+

+Concatenation + + + + + +

+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+ +
Array
+(
+    [0] => 1
+    [1] => 2
+    [2] => 3
+    [3] => 4
+)
+
+
+
+

+Sort + + + + + +

+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+ +
Array
+(
+    [0] => 1
+    [1] => 2
+    [2] => 3
+    [3] => 4
+)
+
+
+
+

+Multidimensional + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+ +
string(5) "forth"
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+ +
int(3)
+
+
+
+

+Count + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+    if ($n > 10)
+        $count++;
+var_dump($count);
+ +
int(2)
+
+
+
+

+Reduce + + + + + +

+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+    return $carry + $item;
+});
+print_r($reduced);
+ +
6
+
+
+

+Index of element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+ +
int(2)
+
+
+
+

+Delete element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+ +
Array
+(
+    [0] => a
+    [2] => c
+)
+
+
+
+

+Unique + + + + + +

+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+ +
Array
+(
+    [0] => a
+    [1] => b
+)
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+ +
array(2) {
+  ["fontSize"]=>
+  string(2) "10"
+  ["fontFamily"]=>
+  string(5) "Arial"
+}
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+ +
array(2) {
+  ["fontSize"]=>
+  string(2) "10"
+  ["fontFamily"]=>
+  string(5) "Arial"
+}
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+    echo "$key\n";
+    echo "$value\n";
+}
+ +
fontSize
+10
+fontFamily
+Arial
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+ +
bool(true)
+
+
+
+

+Get value + + + + + +

+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+ +
string(2) "10"
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+ +
2
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+
<?php
+
+$tryIt = true;
+if ($tryIt)
+    echo "Garlic gum is not funny";
+
+ +
Garlic gum is not funny
+
+
+

+Constant + + + + + +

+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+ +
PHP Warning:  Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4
+
+Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4
+100
+
+
+

+Constant list + + + + + +

+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+No easy way to do that +
+
+

Conditional

+

+If + + + + + +

+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+
<?php
+
+if (true)
+    echo "Hello";
+
+ +
Hello
+
+
+

+Unless + + + + + +

+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
<?php
+
+$angry = false;
+if (!$angry)
+    echo "smile!";
+
+ +
smile!
+
+
+

+If/else + + + + + +

+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+
<?php
+
+if (true)
+    echo "work";
+else
+    echo "sleep";
+
+ +
work
+
+
+

+And/Or + + + + + +

+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+
<?php
+
+if (true && false)
+    echo "no";
+if (true || false)
+    echo "yes";
+
+ +
yes
+
+
+

+Switch + + + + + +

+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+
<?php
+
+$s = "Hello!";
+switch ($s) {
+    case "Bye!":
+        echo "wrong";
+        break;
+    case "Hello!":
+        echo "right";
+        break;
+    default:
+        break;
+}
+
+ +
right
+
+
+

+Ternary + + + + + +

+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+ +
yes
+
+
+

Loop

+

+For + + + + + +

+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
<?php
+
+for ($i = 1; $i <= 3; $i++)
+    echo $i . ". Hi\n";
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+    echo $i . "\n";
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++)
+    echo "Hi\n";
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
<?php
+
+$i = 0;
+while ($i < 3)
+    $i++;
+echo $i;
+
+ +
3
+
+
+

+Until + + + + + +

+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
<?php
+
+$i = 0;
+while ($i != 3)
+    $i++;
+echo $i;
+
+ +
3
+
+
+

+Break + + + + + +

+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++) {
+    echo ($i + 1) . ". Hi\n";
+    if ($i == 1)
+        break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++) {
+    if ($i == 1)
+        continue;
+    echo ($i + 1) . ". Hi\n";
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+
<?php
+
+echo sqrt(9);
+
+ +
3
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+
<?php
+
+try {
+    throw new Exception();
+} catch (Exception $e) {
+    echo "Can't divide\n";
+} finally {
+    echo "But that's ok\n";
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+
<?php
+
+try {
+    throw new Exception("An error!");
+} catch (Exception $e) {
+    echo $e->getMessage();
+}
+
+ +
An error!
+
+
+

+Throw exception + + + + + +

+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+
<?php
+
+try {
+    throw new Exception("An error!");
+} catch (Exception $e) {
+    echo $e->getMessage();
+}
+
+ +
An error!
+
+
+

File

+

+Read + + + + + +

+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+ +
Hello
+World
+
+
+
+

+Write + + + + + +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
<?php
+
+echo getcwd();
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+

+File path + + + + + +

+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+
<?php
+
+echo __FILE__;
+
+ +
/Users/evmorov/projects/lang-compare/code/php/FilePath.php
+
+
+

+Dir path + + + + + +

+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+
<?php
+
+echo __DIR__;
+
+ +
/Users/evmorov/projects/lang-compare/code/php
+
+
+

+Parent dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
<?php
+
+echo realpath(__DIR__ . "/..");
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+

+Sister dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+

Method

+

+Declare + + + + + +

+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+
<?php
+
+function hey()
+{
+    echo "How are you?";
+}
+
+hey();
+
+ +
How are you?
+
+
+

+Multiple arguments + + + + + +

+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+    if ($buy)
+        var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+ +
array(3) {
+  [0]=>
+  string(8) "snickers"
+  [1]=>
+  string(4) "twix"
+  [2]=>
+  string(6) "bounty"
+}
+
+
+
+

+Return + + + + + +

+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+
<?php
+
+function divide(int $a, int $b) : float
+{
+    if ($a == 0)
+        return 0;
+    return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+ +
0
+2
+0.5
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
<?php
+
+class AnimalC
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+ +
I'm walking
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+
<?php
+
+class AnimalB
+{
+    private $name;
+
+    public function __construct(string $name)
+    {
+        $this->name = $name;
+    }
+
+    public function walk()
+    {
+        echo "My name is {$this->name} and I'm walking";
+    }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+ +
My name is Kelya and I'm walking
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
<?php
+
+class AnimalH
+{
+    public function walk()
+    {
+        $this->bark();
+        $this->guard();
+        echo "I'm walking\n";
+    }
+
+    public function bark()
+    {
+        echo "Wuf!\n";
+    }
+
+    private function guard()
+    {
+        echo "WUUUF!\n";
+    }
+}
+
+(new AnimalH())->walk();
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+
<?php
+
+class AnimalA
+{
+    public static function feed()
+    {
+        echo "Om nom nom";
+    }
+}
+
+AnimalA::feed();
+
+ +
Om nom nom
+
+
+

+Private method + + + + + +

+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+
<?php
+
+class AnimalI
+{
+    public function eat(string $food)
+    {
+        if ($this->isMeat($food))
+            echo "Om nom nom";
+    }
+
+    private function isMeat(string $food) : bool
+    {
+        return strcmp($food, "meat") == 0;
+    }
+}
+
+(new AnimalI())->eat("meat");
+
+ +
Om nom nom
+
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+
<?php
+
+class AnimalJ
+{
+    private $name;
+
+    public function __construct(string $name)
+    {
+        $this->name = $name;
+        $this->greet();
+    }
+
+    private function greet()
+    {
+        echo "Hello! My name is " . $this->name;
+    }
+}
+
+new AnimalJ("Kelya");
+
+ +
Hello! My name is Kelya
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+
<?php
+
+class AnimalD
+{
+
+    private $toy;
+
+    public function take(string $toy)
+    {
+        $this->toy = $toy;
+    }
+
+    public function play()
+    {
+        echo "I'm playing with " . $this->toy;
+    }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+ +
I'm playing with a ball
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+
<?php
+
+class AnimalE
+{
+    private $name;
+
+    public function setName(string $name)
+    {
+        $this->name = $name;
+    }
+
+    public function getName() : string
+    {
+        return $this->name;
+    }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+ +
Kelya
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
<?php
+
+class AnimalG
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+class Dog extends AnimalG
+{
+    public function sing()
+    {
+        echo "Bark!";
+    }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+ +
I'm walking
+
+
+

+Has method? + + + + + +

+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+
<?php
+
+class AnimalF
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+ +
bool(true)
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+
<?php
+
+// it's a comment
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+ +
I am imported!
+
+
+

+Date + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+ +
2024-05-28
+
+
+

+Time + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+ +
05/28/24 06:22 PM
+
+
+

+Not + + + + + +

+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
<?php
+
+$angry = false;
+if (!$angry)
+    echo "smile!";
+
+ +
smile!
+
+
+

+Run command + + + + + +

+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+ +
PHP 8.2.8 (cli) (built: Jul  6 2023 11:16:57) (NTS)
+
+
+
+ + + + + + + + + + diff --git a/java-python/index.html b/java-python/index.html new file mode 100644 index 0000000..980dd17 --- /dev/null +++ b/java-python/index.html @@ -0,0 +1,4240 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+ +
+
+
+

Java

+
+
+

Python

+
+
+

String

+

+Create + + + + + +

+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+
greeting = 'Hello World!'
+print(greeting)
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+
print("Don't worry," + ' be happy')
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+No easy way to do that +
+
+
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+ +
Don't worry, be happy
+
+[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+
print('You should work'.replace('work', 'rest'))
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+
print('I like beer'.split())
+
+ +
['I', 'like', 'beer']
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+
print(' eh? '.strip())
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+
print('string' == 'string')
+print('string' != 'string')
+
+ +
True
+False
+
+
+
+

+Regex + + + + + +

+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+ +
None
+<re.Match object; span=(0, 1), match='a'>
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+
i = 9
+i += 1
+print(i)
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+ +
True
+True
+False
+
+
+
+

+Random + + + + + +

+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+
import random
+
+print(random.randint(1, 2))
+
+ +
2
+
+
+
+

+Float + + + + + +

+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2))  # rounds half to even
+
+ +
4
+4.5
+4
+4
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+
print(type('hi'))
+print(type(1))
+
+ +
<class 'str'>
+<class 'int'>
+
+
+
+

+Int to Float + + + + + +

+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+
print(float(10))
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+
print(str(10))
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+
print(int('5'))
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+
print(isinstance('10', str))
+
+ +
True
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+
def check(label, fn, values):
+    print(label)
+    for value in values:
+        try:
+            result = 'true' if fn(value) else 'false'
+        except TypeError as e:
+            result = 'error: %s' % e
+        print("  %-9r - %s" % (value, result))
+    print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+ +
if value:
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - true
+  0         - false
+  True      - true
+  False     - false
+  None      - false
+
+if value is None:
+  'string'  - false
+  ''        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  True      - false
+  False     - false
+  None      - true
+
+if len(value):
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - error: object of type 'int' has no len()
+  0         - error: object of type 'int' has no len()
+  True      - error: object of type 'bool' has no len()
+  False     - error: object of type 'bool' has no len()
+  None      - error: object of type 'NoneType' has no len()
+
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
arr = ['first', 'second']
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+With different types + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+
print(['first', 1])
+
+ +
['first', 1]
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+
print(1 in [1, 2])
+
+ +
True
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+
for num in [1, 2]:
+  print(num)
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+
for i, num in enumerate(['one', 'two']):
+  print(num)
+  print(i)
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+ +
[10, 20]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+ +
[2, 10, 20, 40]
+
+
+
+

+Concatenation + + + + + +

+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
print([1, 2] + [3, 4])
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Sort + + + + + +

+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
print(sorted([4, 2, 3, 1]))
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+
print(len([1, 2, 3]))
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3]))  # a more Pythonic example
+
+ +
6
+6
+
+
+
+

+Index of element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+
print(['a', 'b', 'c'].index('c'))
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+ +
['a', 'c']
+
+
+
+

+Unique + + + + + +

+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+
print(set(['a', 'b', 'a']))
+
+ +
{'a', 'b'}
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+  print(key, value)
+
+ +
font_size 10
+font_family Arial
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+ +
True
+
+
+
+

+Get value + + + + + +

+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+
try_it = True
+if try_it:
+    print('Garlic gum is not funny')
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+
COST = 100
+COST = 50
+print(COST)
+
+ +
50
+
+
+
+

+Constant list + + + + + +

+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+
class Colors:
+    RED = '#FF0000'
+    GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+ +
#00FF00
+
+
+
+

+Struct + + + + + +

+
+
+No easy way to do that +
+
+
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+    def greeting(self):
+        return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+ +
Hello Dave!
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+
if True:
+    print('Hello')
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+    print('smile!')
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+
if True:
+  print('work')
+else:
+  print('sleep')
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+
if True and False:
+    print('no')
+if True or False:
+    print('yes')
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+
foo = 'Hello!'
+if foo in range(1, 6):
+    print("It's between 1 and 5")
+elif foo in (10, 20):
+    print('10 or 20')
+elif foo == 'And':
+    print('case in one line')
+elif isinstance(foo, str):
+    print("You passed a string %r" % foo)
+else:
+    print("You gave me %r" % foo)
+
+ +
You passed a string 'Hello!'
+
+
+
+

+Switch as else if + + + + + +

+
+
+No easy way to do that +
+
+
score = 76
+grades = [
+    (60, 'F'),
+    (70, 'D'),
+    (80, 'C'),
+    (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+ +
C
+
+
+
+

+Ternary + + + + + +

+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+
print('no' if False else 'yes')
+
+ +
yes
+
+
+
+

+If assign + + + + + +

+
+
+No easy way to do that +
+
+
result = 'a' if True else 'b'
+print(result)
+
+ +
a
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
for i in range(1, 4):
+    print('%d. Hi' % i)
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+
for i in range(0, 5, 2):
+    print(i)
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
for i in range(3):
+  print('Hi')
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
i = 0
+while i < 3:
+  i += 1
+print(i)
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
i = 0
+while i != 3:
+    i += 1
+print(i)
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+No easy way to do that +
+
+
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+ +
['1. Hello!', '2. Hello!', '3. Hello!']
+
+
+
+

+Break + + + + + +

+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
for time in range(1, 4):
+  print("%d. Hi" % time)
+  if time == 2:
+    break
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
for time in range(1, 4):
+  if time == 2:
+      continue
+  print("%d. Hi" % time)
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+
import math
+
+print(math.sqrt(9))
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+
try:
+  1 / 0
+except:
+  print("Can't divide")
+finally:
+  print("But that's ok")
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+
try:
+  1 / 0
+except Exception as e:
+  print(e)
+
+ +
division by zero
+
+
+
+

+Method + + + + + +

+
+
+No easy way to do that +
+
+
def divide(num1, num2):
+  try:
+    num1 / num2
+  except Exception as e:
+    print(e)
+divide(1, 0)
+
+ +
division by zero
+
+
+
+

+Throw exception + + + + + +

+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+
try:
+  raise Exception('An error!')
+except Exception as e:
+  print(e)
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+    print(f.read())
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+    f.write('Some glorious content')
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
import os
+
+print(os.getcwd())
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+
print(__file__)
+
+ +
/Users/evmorov/projects/lang-compare/code/python/file_path.py
+
+
+
+

+Dir path + + + + + +

+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+

+Parent dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+
def hey():
+  print('How are you?')
+hey()
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+
def sweets(buy, *brands):
+  if buy:
+      print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+ +
('snickers', 'twix', 'bounty')
+
+
+
+

+Default value for argument + + + + + +

+
+
+No easy way to do that +
+
+
def send(abroad=False):
+  print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+
def multiply(a, b):
+    return a * b
+
+def divide(a, b):
+    return 0 if a == 0 else a / b
+
+def default_value():
+    pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+ +
6
+0
+None
+
+
+
+

+Closure + + + + + +

+
+
+No easy way to do that +
+
+
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+ +
[4, 9]
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+No easy way to do that +
+
+
def select(arr):
+    yield from arr
+
+def select_filter(arr, filter):
+    for a in arr:
+        if filter(a):
+            yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+ +
[1, 5]
+[1, 5]
+
+
+
+

+Block binding + + + + + +

+
+
+No easy way to do that +
+
+
class Action:
+  name = 'Ann'
+
+  @staticmethod
+  def say(sentence):
+    print(sentence())
+
+
+class Person:
+  def __init__(self, name):
+    self.name = name
+
+  def greet(self):
+    Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+ +
My name is Alex!
+
+
+
+

+Initialize in runtime + + + + + +

+
+
+No easy way to do that +
+
+
class ProccessElements:
+  def __init__(self):
+    def element(el_name):
+      def render(content):
+        return '<{0}>{1}</{0}>'.format(el_name, content)
+      return render
+
+    for el_name in self.elements:
+      setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+  elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+ +
<div>hello</div>
+
+
+
+

+Alias + + + + + +

+
+
+No easy way to do that +
+
+
class Greetings:
+  def hey(self):
+    print('How are you?')
+  hi = hey
+
+Greetings().hi()
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+Animal().walk()
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+
+  def walk(self):
+    print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    self.bark()
+    self._guard()
+    print("I'm walking")
+
+  def bark(self):
+    print('Wuf!')
+
+  # Private by convention
+  def _guard(self):
+    print('WUUUF!')
+
+Animal().walk()
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal:
+  @classmethod
+  def feed(cls):
+    print('Om nom nom')
+
+Animal.feed()
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal:
+  def eat(self, food):
+    if self._is_meat(food):
+      print('Om nom nom')
+
+  def _is_meat(self, food):
+    return food == 'meat'
+
+Animal().eat('meat')
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+    self._greet()
+
+  def _greet(self):
+    print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+
class Animal:
+  def take(self, toy):
+    self.toy = toy
+
+  def play(self):
+    print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+
class Animal:
+  name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+class Dog(Animal):
+  def sing(self):
+    print('Bark!')
+
+Dog().walk()
+
+ +
I'm walking
+
+
+
+

+Mixin + + + + + +

+
+
+No easy way to do that +
+
+
class Moving:
+  def walk(self):
+    print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+  def talk(self):
+    print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+    pass
+
+human = Human()
+human.walk()
+human.talk()
+
+ +
Human is walking
+Human is talking
+
+
+
+

+Has method? + + + + + +

+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+ +
True
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+
# it's a comment
+
+ +

+
+
+

+Assign value if not exist + + + + + +

+
+
+No easy way to do that +
+
+
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+ +
0
+
+
+
+

+Import another file + + + + + +

+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+
# other_file_to_import.py
+# class Import:
+#   def __init__(self):
+#     print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+No easy way to do that +
+
+
one, two = 1, 2
+print(one, two)
+
+ +
1 2
+
+
+
+

+Date + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+
import datetime
+print(datetime.date.today())
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+
import datetime
+print(datetime.datetime.now())
+
+ +
2024-05-28 20:18:14.644332
+
+
+
+

+Not + + + + + +

+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+  print('smile!')
+
+ +
smile!
+
+
+
+

+Assign this or that + + + + + +

+
+
+No easy way to do that +
+
+
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+ +
bear
+
+
+
+

+Run command + + + + + +

+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
import subprocess
+subprocess.call(['python3', '--version'])
+
+ +
Python 3.11.2
+
+
+
+
+ + + + + + + + + + diff --git a/java-ruby/index.html b/java-ruby/index.html new file mode 100644 index 0000000..89176b5 --- /dev/null +++ b/java-ruby/index.html @@ -0,0 +1,4348 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+ +
+
+
+

Java

+
+
+

Ruby

+
+
+

String

+

+Create + + + + + +

+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+
greeting = 'Hello World!'
+puts greeting
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+
puts "Don't worry," + ' be happy'
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+No easy way to do that +
+
+
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+
puts 'You should work'.gsub('work', 'rest')
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+
puts 'I like beer'.split
+
+ +
I
+like
+beer
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+
puts ' eh? '.strip
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+
puts 'string' == 'string'
+puts 'string' != 'string'
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+ +
nil
+0
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+
i = 9
+i += 1
+puts i
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+
puts rand(1..2)
+
+ +
1
+
+
+
+

+Float + + + + + +

+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+ +
4
+4.5
+4
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+
puts 'hi'.class
+puts 1.class
+
+ +
String
+Fixnum
+
+
+
+

+Int to Float + + + + + +

+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+
puts 10.to_f
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+
puts 10.to_s
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+
puts '5'.to_i
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+
puts '10'.is_a? String
+
+ +
true
+
+
+
+

+Null/True/False? + + + + + +

+
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+
def check(label, fn, values)
+  puts label
+  values.each do |value|
+    begin
+      result = fn.call(value) ? 'true' : 'false'
+    rescue NoMethodError => e
+      result = "error: #{e}"
+    end
+    puts format("  %-9p - %s", value, result)
+  end
+  puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+ +
if value:
+  "string"  - true
+  ""        - true
+  [1, 2, 3] - true
+  []        - true
+  5         - true
+  0         - true
+  true      - true
+  false     - false
+  nil       - false
+
+if value.nil?:
+  "string"  - false
+  ""        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  true      - false
+  false     - false
+  nil       - true
+
+if value.empty?:
+  "string"  - false
+  ""        - true
+  [1, 2, 3] - false
+  []        - true
+  5         - error: undefined method `empty?' for 5:Fixnum
+  0         - error: undefined method `empty?' for 0:Fixnum
+  true      - error: undefined method `empty?' for true:TrueClass
+  false     - error: undefined method `empty?' for false:FalseClass
+  nil       - error: undefined method `empty?' for nil:NilClass
+
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
arr = %w(first second)
+puts arr
+
+ +
first
+second
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+ +
first
+second
+
+
+
+

+With different types + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+
puts ['first', 1]
+
+ +
first
+1
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+
puts [1, 2].include? 1
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+
[1, 2].each do |num|
+  puts num
+end
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+
%w(one two).each_with_index do |num, i|
+  puts num
+  puts i
+end
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+ +
10
+20
+
+
+
+

+Map (change all) + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+ +
2
+10
+20
+40
+
+
+
+

+Concatenation + + + + + +

+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
puts [1, 2] + [3, 4]
+
+ +
1
+2
+3
+4
+
+
+
+

+Sort + + + + + +

+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+
puts [4, 2, 3, 1].sort
+
+ +
1
+2
+3
+4
+
+
+
+

+Multidimensional + + + + + +

+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+
puts [1, 2, 3].size 
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+
puts [1, 2, 3].reduce(:+)
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+
puts ['a', 'b', 'c'].index('c')
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+ +
a
+c
+
+
+
+

+Unique + + + + + +

+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+
puts %w(a b a).uniq
+
+ +
a
+b
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+

+Add + + + + + +

+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+

+Iterate + + + + + +

+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+  puts key, value
+end
+
+ +
font_size
+10
+font_family
+Arial
+
+
+
+

+Include? + + + + + +

+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+
COST = 100
+COST = 50
+puts COST
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here
+50
+
+
+
+

+Constant list + + + + + +

+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+
module Colors
+  RED = '#FF0000'
+  GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+ +
#00FF00
+
+
+
+

+Struct + + + + + +

+
+
+No easy way to do that +
+
+
Customer = Struct.new(:name, :address) do
+  def greeting
+    "Hello #{name}!"
+  end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+ +
Hello Dave!
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+
puts 'Hello' if true
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
angry = false
+puts 'smile!' unless angry
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+
if true
+  puts 'work'
+else
+  puts 'sleep'
+end
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+
puts 'no' if true && false
+puts 'yes' if true || false
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+
foo = 'Hello!'
+case foo
+when 1..5
+  puts "It's between 1 and 5"
+when 10, 20
+  puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+  puts "You passed a string '#{foo}'"
+else
+  puts "You gave me '#{foo}'"
+end
+
+ +
You passed a string 'Hello!'
+
+
+
+

+Switch as else if + + + + + +

+
+
+No easy way to do that +
+
+
score = 76
+grade = case
+        when score < 60 then 'F'
+        when score < 70 then 'D'
+        when score < 80 then 'C'
+        when score < 90 then 'B'
+        else 'A'
+        end
+puts grade
+
+ +
C
+
+
+
+

+Ternary + + + + + +

+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+
puts false ? 'no' : 'yes'
+
+ +
yes
+
+
+
+

+If assign + + + + + +

+
+
+No easy way to do that +
+
+
result =
+if true
+  'a'
+else
+  'b'
+end
+puts result
+
+
+ +
a
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
(1..3).each do |i|
+  puts "#{i}. Hi"
+end
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+
(0..4).step(2) do |i|
+  puts i
+end
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
3.times do
+  puts 'Hi'
+end
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
i = 0
+while i < 3
+  i += 1
+end
+puts i
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+
i = 0
+i += 1 until i == 3
+puts i
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+No easy way to do that +
+
+
greetings = Array.new(3) do |i|
+  "#{i + 1}. Hello!"
+end
+puts greetings
+
+ +
1. Hello!
+2. Hello!
+3. Hello!
+
+
+
+

+Break + + + + + +

+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
3.times do |time|
+  puts "#{time + 1}. Hi"
+  break if time == 1
+end
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
3.times do |time|
+  next if time == 1
+  puts "#{time + 1}. Hi"
+end
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+
puts Math.sqrt(9)
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+
begin
+  1 / 0
+rescue
+  puts "Can't divide"
+ensure
+  puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+ +
Can't divide
+But that's ok
+Can't divide
+
+
+
+

+With a message + + + + + +

+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+
begin
+  1 / 0
+rescue => e
+  puts e.message
+end
+
+ +
divided by 0
+
+
+
+

+Method + + + + + +

+
+
+No easy way to do that +
+
+
def divide(num1, num2)
+  num1 / num2
+rescue => e
+  puts e.message
+end
+divide(1, 0)
+
+ +
divided by 0
+
+
+
+

+Throw exception + + + + + +

+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+
begin
+  fail 'An error!'
+rescue => e
+  puts e.message
+end
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+ +
Hello
+World
+
+
+
+

+Write + + + + + +

+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
puts Dir.getwd
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+
puts __FILE__
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb
+
+
+
+

+Dir path + + + + + +

+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+
puts File.dirname(__FILE__)
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+

+Parent dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
puts File.expand_path File.join(__FILE__, '..', '..')
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+ +
/Users/evmorov/projects/lang-compare/code/php
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+
def hey
+  puts 'How are you?'
+end
+hey
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+
def sweets(buy, *brands)
+  puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+ +
snickers
+twix
+bounty
+
+
+
+

+Default value for argument + + + + + +

+
+
+No easy way to do that +
+
+
def send(abroad = false)
+  puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+
def multiple(a, b)
+  a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+  return 0 if a == 0
+  a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+ +
6
+0
+nil
+
+
+
+

+Closure + + + + + +

+
+
+No easy way to do that +
+
+
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+ +
4
+9
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+No easy way to do that +
+
+
def my_select(arr)
+  selected = []
+  arr.each do |a|
+    selected.push a if yield(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+  selected = []
+  arr.each do |a|
+    selected.push a if filter.call(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+ +
1
+5
+1
+5
+
+
+
+

+Block binding + + + + + +

+
+
+No easy way to do that +
+
+
class Action
+  def self.say(&sentence)
+    @name = 'Ann'
+    puts sentence.call
+  end
+end
+
+class Person
+  def initialize(name)
+    @name = name
+  end
+
+  def greet
+    Action.say { "My name is #{@name}!" }
+  end
+end
+
+Person.new('Alex').greet
+
+ +
My name is Alex!
+
+
+
+

+Initialize in runtime + + + + + +

+
+
+No easy way to do that +
+
+
class ProccessElements
+  def self.element(el_name)
+    define_method "#{el_name}_element" do |content|
+      "<#{el_name}>#{content}</#{el_name}>"
+    end
+  end
+end
+
+class HtmlELements < ProccessElements
+  element :div
+  element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+ +
<div>hello</div>
+
+
+
+

+Alias + + + + + +

+
+
+No easy way to do that +
+
+
class Greetings
+  def hey
+    puts 'How are you?'
+  end
+  alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+Animal.new.walk
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal
+  def initialize(name)
+    @name = name
+  end
+
+  def walk
+    puts "My name is #{@name} and I'm walking"
+  end
+end
+
+Animal.new('Kelya').walk
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+
class Animal
+  def walk
+    bark
+    guard
+    puts "I'm walking"
+  end
+
+  def bark
+    puts 'Wuf!'
+  end
+
+  private
+
+  def guard
+    puts 'WUUUF!'
+  end
+end
+
+Animal.new.walk
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal
+  def self.feed
+    puts 'Om nom nom'
+  end
+end
+
+Animal.feed
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+
class Animal
+  def eat(food)
+    puts 'Om nom nom' if meat? food
+  end
+
+  private
+
+  def meat?(food)
+    food == 'meat'
+  end
+end
+
+Animal.new.eat('meat')
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+
class Animal
+  def initialize(name)
+    @name = name
+    greet
+  end
+
+  private
+
+  def greet
+    puts "Hello! My name is #{@name}"
+  end
+end
+
+Animal.new('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+
class Animal
+  def take(toy)
+    @toy = toy
+  end
+
+  def play
+    puts "I'm playing with #{@toy}"
+  end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+
class Animal
+  attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+class Dog < Animal
+  def sing
+    puts 'Bark!'
+  end
+end
+
+Dog.new.walk
+
+ +
I'm walking
+
+
+
+

+Mixin + + + + + +

+
+
+No easy way to do that +
+
+
module Moving
+  def walk
+    puts "#{self.class.name} is walking"
+  end
+end
+
+module Interacting
+  def talk
+    puts "#{self.class.name} is talking"
+  end
+end
+
+class Human
+  include Moving
+  include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+ +
Human is walking
+Human is talking
+
+
+
+

+Has method? + + + + + +

+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+
# it's a comment
+
+ +

+
+
+

+Assign value if not exist + + + + + +

+
+
+No easy way to do that +
+
+
speed = 0
+speed ||= 15
+puts speed
+
+ +
0
+
+
+
+

+Safe navigation + + + + + +

+
+
+No easy way to do that +
+
+[ 2.3 ]
class Winner
+  attr_reader :address
+
+  def initialize
+    # @address = Address.new
+  end
+end
+
+class Address
+  attr_reader :zipcode
+
+  def initialize
+    @zipcode = 192187
+  end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+ +
No prize without zipcode
+
+
+
+

+Import another file + + + + + +

+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+
# other_file_to_import.rb
+# class Import
+#   def initialize
+#     puts 'I am imported!'
+#   end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+No easy way to do that +
+
+
one, two = [1, 2]
+puts one, two
+
+ +
1
+2
+
+
+
+

+Date + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+
require 'date'
+puts Date.today
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+
puts Time.now
+
+ +
2024-05-28 20:17:54 +0200
+
+
+
+

+Not + + + + + +

+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+
angry = false
+puts 'smile!' if !angry
+
+ +
smile!
+
+
+
+

+Assign this or that + + + + + +

+
+
+No easy way to do that +
+
+
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+ +
bear
+
+
+
+

+Run command + + + + + +

+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
puts `ruby -v`
+
+ +
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21]
+
+
+
+
+ + + + + + + + + + diff --git a/javascript-java/index.html b/javascript-java/index.html new file mode 100644 index 0000000..3502bff --- /dev/null +++ b/javascript-java/index.html @@ -0,0 +1,3982 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

JavaScript

+
+
+

Java

+
+
+

String

+

+Create + + + + + +

+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+
class StringCreate {
+  public static void main(String[] args) {
+    String greeting = "Hello World!";
+    System.out.println(greeting);
+  }
+}
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+
class StringConcat {
+  public static void main(String[] args) {
+    System.out.println("Don't worry," + " be happy");
+  }
+}
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+No easy way to do that +
+
+

+Remove part + + + + + +

+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+
class StringRemove {
+  public static void main(String[] args) {
+    String s = "This is not funny! I am not like him!";
+    System.out.println(s.replaceAll("not ", ""));
+  }
+}
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+
class StringReplace {
+  public static void main(String[] args) {
+    String s = "You should work";
+    System.out.println(s.replaceAll("work", "rest"));
+  }
+}
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+
import java.util.Arrays;
+
+class StringSplit {
+  public static void main(String[] args) {
+    String s = "I like beer";
+    String[] arr = s.split(" ");
+    System.out.println(Arrays.toString(arr));
+  }
+}
+
+ +
[I, like, beer]
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+
class StringRemoveWhitespace {
+  public static void main(String[] args) {
+    System.out.println(" eh? ".trim());
+  }
+}
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+
class StringCompare {
+  public static void main(String[] args) {
+    System.out.println("string".equals("string"));
+    System.out.println(!"string".equals("string"));
+  }
+}
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+
import java.util.regex.*;
+
+class StringRegex {
+  public static void main(String[] args) {
+    System.out.println(Pattern.compile("^b").matcher("apple").find());
+    System.out.println(Pattern.compile("^a").matcher("apple").find());
+  }
+}
+
+ +
false
+true
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+
class NumberIncrement {
+  public static void main(String[] args) {
+    int i = 9;
+    i++;
+    System.out.println(i);
+  }
+}
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+
class NumberCompare {
+  public static void main(String[] args) {
+    System.out.println(1 < 2 && 2 < 3);
+    System.out.println(5 == 5);
+    System.out.println(5 != 5);
+  }
+}
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+  public static void main(String[] args) {
+    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+  }
+}
+
+ +
1
+
+
+
+

+Float + + + + + +

+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+
class NumberFloat {
+  public static void main(String[] args) {
+    System.out.println(9 / 2);
+    System.out.println(9 / 2.0);
+    System.out.println(Math.floor(9 / 2.0));
+    System.out.println(Math.round(9 / 2.0));
+  }
+}
+
+ +
4
+4.5
+4.0
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+
class TypeGetType {
+  public static void main(String[] args) {
+    System.out.println("hi".getClass());
+    System.out.println(new Integer(1).getClass());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
+    System.out.println(new Integer(1).getClass());
+                       ^
+1 warning
+
+
+
+

+Int to Float + + + + + +

+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+
class TypeIntToFloat {
+  public static void main(String[] args) {
+    System.out.println((float) 10);
+  }
+}
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+
class TypeIntToString {
+  public static void main(String[] args) {
+    System.out.println(Integer.toString(10));
+  }
+}
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+
class TypeStringToInt {
+  public static void main(String[] args) {
+    System.out.println(Integer.parseInt("10"));
+  }
+}
+
+ +
10
+
+
+
+

+String? + + + + + +

+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+
class TypeIsString {
+  public static void main(String[] args) {
+    System.out.println("10" instanceof String);
+  }
+}
+
+ +
true
+
+
+
+

+Null/True/False? + + + + + +

+
+
+No easy way to do that +
+
+
import java.util.*;
+
+class TypeNullTrueFalse {
+  public static void main(String[] args) {
+    List<String> emptyArray = new ArrayList<String>();
+    System.out.println(emptyArray.isEmpty());
+
+    String emptyString = "";
+    System.out.println(emptyString.isEmpty());
+
+    String nullVar = null;
+    System.out.println(nullVar == null);
+  }
+}
+
+ +
true
+true
+true
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
import java.util.*;
+
+class ArrayCreatePopulated {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("first", "second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+

+Add + + + + + +

+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
import java.util.*;
+
+class ArrayAdd {
+  public static void main(String[] args) {
+    List<String> arr = new ArrayList<String>();
+    arr.add("first");
+    arr.add("second");
+    System.out.println(arr);
+  }
+}
+
+ +
[first, second]
+
+
+
+

+With different types + + + + + +

+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+
import java.util.*;
+
+class ArrayDifferentTypes {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList("first", 1));
+  }
+}
+
+ +
[first, 1]
+
+
+
+

+Include? + + + + + +

+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+
import java.util.*;
+
+class ArrayIsInclude {
+  public static void main(String[] args) {
+    System.out.println(Arrays.asList(1, 2).contains(1));
+  }
+}
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+
import java.util.*;
+
+class ArrayIterate {
+  public static void main(String[] args) {
+    for (int num : Arrays.asList(1, 2)) {
+      System.out.println(num);
+    }
+  }
+}
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+
import java.util.*;
+
+class ArrayIterateWithIndex {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    for (int i = 0; i < arr.size(); i++) {
+      System.out.println(arr.get(i));
+      System.out.println(i);
+    }
+  }
+}
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+
import java.util.*;
+
+class ArrayGetFirstAndLast {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("one", "two");
+    System.out.println(arr.get(0));
+    System.out.println(arr.get(arr.size() - 1));
+  }
+}
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+
import java.util.*;
+
+class ArrayFind {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    int first = 0;
+    for (int n : arr) {
+      if (n % 2 == 0) {
+        first = n;
+        break;
+      }
+    }
+    System.out.println(first);
+  }
+}
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+
import java.util.*;
+
+class ArraySelect {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> all = new ArrayList<Integer>();
+    for (int n : arr)
+      if (n % 2 == 0)
+        all.add(n);
+    System.out.println(all);
+  }
+}
+
+ +
[10, 20]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+
import java.util.*;
+
+class ArrayMap {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+    List<Integer> mapped = new ArrayList<Integer>();
+    for (int n : arr)
+      mapped.add(n * 2);
+    System.out.println(mapped);
+  }
+}
+
+ +
[2, 10, 20, 40]
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
import java.util.*;
+
+class ArrayConcat {
+  public static void main(String[] args) {
+    List<Integer> arr1 = Arrays.asList(1, 2);
+    List<Integer> arr2 = Arrays.asList(3, 4);
+    List<Integer> concated = new ArrayList<Integer>(arr1);
+    concated.addAll(arr2);
+    System.out.println(concated);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Sort + + + + + +

+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
import java.util.*;
+
+class ArraySort {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+    Collections.sort(arr);
+    System.out.println(arr);
+  }
+}
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+
import java.util.*;
+
+class ArrayMulti {
+  public static void main(String[] args) {
+    List<List<String>> arr = new ArrayList<List<String>>();
+    arr.add(Arrays.asList("first", "second"));
+    arr.add(Arrays.asList("third", "forth"));
+    System.out.println(arr.get(1).get(1));
+  }
+}
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+
import java.util.*;
+
+class ArraySize {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(arr.size());
+  }
+}
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+
import java.util.*;
+
+class ArrayCount {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 11, 111);
+    int count = 0;
+    for (int n : arr)
+      if (n > 10)
+        count++;
+    System.out.println(count);
+  }
+}
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+
import java.util.*;
+
+class ArrayReduce {
+  public static void main(String[] args) {
+    int sum = 0;
+    for (int n : Arrays.asList(1, 2, 3))
+      sum += n;
+    System.out.println(sum);
+  }
+}
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+
import java.util.*;
+
+class ArrayIndexOfElement {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "c");
+    System.out.println(arr.indexOf("c"));
+  }
+}
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+
import java.util.*;
+
+class ArrayDeleteElement {
+  public static void main(String[] args) {
+    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+    Iterator<String> iter = arr.iterator();
+    while(iter.hasNext()) {
+      if(iter.next().equalsIgnoreCase("b"))
+        iter.remove();
+    }
+    System.out.println(arr);
+  }
+}
+
+ +
[a, c]
+
+
+
+

+Unique + + + + + +

+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+
import java.util.*;
+
+class ArrayUnique {
+  public static void main(String[] args) {
+    List<String> arr = Arrays.asList("a", "b", "a");
+    Set<String> unique = new LinkedHashSet<>(arr);
+    System.out.println(unique);
+  }
+}
+
+ +
[a, b]
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
import java.util.*;
+
+class HashCreatePopulated {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+

+Add + + + + + +

+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
import java.util.*;
+
+class HashAdd {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>();
+    options.put("fontSize", "10");
+    options.put("fontFamily", "Arial");
+    System.out.println(options);
+  }
+}
+
+ +
{fontFamily=Arial, fontSize=10}
+
+
+
+

+Iterate + + + + + +

+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+
import java.util.*;
+
+class HashIterate {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    for (Map.Entry<String, String> entry : options.entrySet()) {
+      System.out.println(entry.getKey());
+      System.out.println(entry.getValue());
+    }
+  }
+}
+
+ +
fontFamily
+Arial
+fontSize
+10
+
+
+
+

+Include? + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+
import java.util.*;
+
+class HashIsInclude {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.containsKey("fontSize"));
+  }
+}
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+
import java.util.*;
+
+class HashGetValue {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.get("fonSize"));
+  }
+}
+
+ +
null
+
+
+
+

+Size + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+
import java.util.*;
+
+class HashSize {
+  public static void main(String[] args) {
+    Map<String, String> options = new HashMap<String, String>() {{
+      put("fontSize", "10");
+      put("fontFamily", "Arial");
+    }};
+    System.out.println(options.size());
+  }
+}
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+
class OtherStructureBoolean {
+  public static void main(String[] args) {
+    boolean tryIt = true;
+    if (tryIt)
+      System.out.println("Garlic gum is not funny");
+  }
+}
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+
class OtherStructureConstant {
+  public static void main(String[] args) {
+    final int COST = 100;
+    COST = 50;
+    System.out.println(COST);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
+    COST = 50;
+    ^
+1 error
+
+
+
+

+Constant list + + + + + +

+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+
enum Color {
+  RED("#FF0000"),
+  GREEN("#00FF00");
+
+  private String color;
+
+  private Color(String color) {
+    this.color = color;
+  }
+
+  public String toString() {
+    return color;
+  }
+}
+
+class OtherStructureConstantList {
+  public static void main(String[] args) {
+    System.out.println(Color.GREEN);
+  }
+}
+
+ +
#00FF00
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+
class ConditionalIf {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("Hello");
+  }
+}
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
class ConditionalUnless {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+
class ConditionalIfElse {
+  public static void main(String[] args) {
+    if (true)
+      System.out.println("work");
+    else
+      System.out.println("sleep");
+  }
+}
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+
class ConditionalAndOr {
+  public static void main(String[] args) {
+    if (true && false)
+      System.out.println("no");
+    if (true || false)
+      System.out.println("yes");
+  }
+}
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+
class ConditionalSwitch {
+  public static void main(String[] args) {
+    String s = "Hello!";
+    switch (s) {
+      case "Bye!":
+        System.out.println("wrong");
+        break;
+      case "Hello!":
+        System.out.println("right");
+        break;
+      default: break;
+    }
+  }
+}
+
+ +
right
+
+
+
+

+Ternary + + + + + +

+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+
class ConditionalTernary {
+  public static void main(String[] args) {
+    String s = false ? "no" : "yes";
+    System.out.println(s);
+  }
+}
+
+ +
yes
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
class LoopFor {
+  public static void main(String[] args) {
+    for (int i = 1; i <= 3; i++)
+      System.out.println(i + ". Hi");
+  }
+}
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+
class LoopForWithStep {
+  public static void main(String[] args) {
+    for (int i = 0; i <= 4; i += 2)
+      System.out.println(i);
+  }
+}
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
class LoopTimes {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++)
+      System.out.println("Hi");
+  }
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
class LoopWhile {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i < 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
class LoopUntil {
+  public static void main(String[] args) {
+    int i = 0;
+    while (i != 3)
+      i++;
+    System.out.println(i);
+  }
+}
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+No easy way to do that +
+
+

+Break + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
class LoopBreak {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      System.out.println((i + 1) + ". Hi");
+      if (i == 1)
+        break;
+    }
+  }
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
class LoopNext {
+  public static void main(String[] args) {
+    for (int i = 0; i < 3; i++) {
+      if (i == 1)
+        continue;
+      System.out.println((i + 1) + ". Hi");
+    }
+  }
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+
import java.util.*;
+
+class MathMaxMin {
+  public static void main(String[] args) {
+    List<Integer> arr = Arrays.asList(1, 2, 3);
+    System.out.println(Collections.min(arr));
+    System.out.println(Collections.max(arr));
+  }
+}
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+
class MathSqrt {
+  public static void main(String[] args) {
+    System.out.println(Math.sqrt(9));
+  }
+}
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+
class ErrorTryCatch {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println("Can't divide");
+    } finally {
+      System.out.println("But that's ok");
+    }
+  }
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+
class ErrorWithAMessage {
+  public static void main(String[] args) {
+    try {
+      int i = 1 / 0;
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
/ by zero
+
+
+
+

+Throw exception + + + + + +

+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+
class ErrorThrow {
+  public static void main(String[] args) {
+    try {
+      throw new Exception("An error!");
+    } catch (Exception e) {
+      System.out.println(e.getMessage());
+    }
+  }
+}
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+
import java.io.*;
+
+class FileRead {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/file.txt";
+    String content;
+    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+      StringBuilder sb = new StringBuilder();
+      String line = br.readLine();
+      while (line != null) {
+        sb.append(line);
+        sb.append(System.lineSeparator());
+        line = br.readLine();
+      }
+      content = sb.toString();
+    }
+    System.out.println(content);
+  }
+}
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+
import java.io.*;
+
+class FileWrite {
+  public static void main(String[] args) throws IOException {
+    String filePath = System.getProperty("user.dir") + "/code/output.txt";
+    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+        new FileOutputStream(filePath), "utf-8"))) {
+      writer.write("Some glorious content");
+    }
+  }
+}
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
class FileGetWorkingDir {
+  public static void main(String[] args) {
+    System.out.println(System.getProperty("user.dir"));
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+
import java.net.*;
+
+class FilePath {
+  public static void main(String[] args) {
+    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile() + "FilePath.class");
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
+
+
+
+

+Dir path + + + + + +

+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+
import java.net.*;
+
+class FileDirPath {
+  public static void main(String[] args) {
+    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    System.out.println(location.getFile());
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java/
+
+
+
+

+Parent dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+  public static void main(String[] args) {
+    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile()).getParent();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+  public static void main(String[] args) throws IOException {
+    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+    System.out.println(parentPath);
+  }
+}
+
+ +
/Users/evmorov/projects/lang-compare/code/java
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+
class MethodDeclare {
+  public static void main(String[] args) {
+    new MethodDeclare().hey();
+  }
+
+  public void hey() {
+    System.out.println("How are you?");
+  }
+}
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+
import java.util.*;
+
+class MethodMultiArg {
+  public static void main(String[] args) {
+    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+  }
+
+  public void sweets(boolean buy, String... brands) {
+    if (buy)
+      System.out.println(Arrays.toString(brands));
+  }
+}
+
+ +
[snickers, twix, bounty]
+
+
+
+

+Default value for argument + + + + + +

+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+No easy way to do that +
+
+

+Return + + + + + +

+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+
class MethodReturn {
+  public static void main(String[] args) {
+    MethodReturn obj = new MethodReturn();
+    System.out.println(obj.divide(0, 10));
+    System.out.println(obj.divide(10, 5));
+  }
+
+  public int divide(int a, int b) {
+    if (a == 0)
+      return 0;
+    return a / b;
+  }
+}
+
+ +
0
+2
+
+
+
+

+Closure + + + + + +

+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+No easy way to do that +
+
+

+Block passing + + + + + +

+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+No easy way to do that +
+
+

+Block binding + + + + + +

+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+No easy way to do that +
+
+

+Alias + + + + + +

+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+No easy way to do that +
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassDeclare {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+  }
+
+  public void walk() {
+    System.out.println("My name is " + this.name + " and I'm walking");
+  }
+}
+
+class ClassConstructor {
+  public static void main(String[] args) {
+    new Animal("Kelya").walk();
+  }
+}
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    bark();
+    guard();
+    System.out.println("I'm walking");
+  }
+
+  public void bark() {
+    System.out.println("Wuf!");
+  }
+
+  private void guard() {
+    System.out.println("WUUUF!");
+  }
+}
+
+class ClassMethodCall {
+  public static void main(String[] args) {
+    new Animal().walk();
+  }
+}
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+
class Animal {
+  public static void feed() {
+    System.out.println("Om nom nom");
+  }
+}
+
+class ClassClassMethod {
+  public static void main(String[] args) {
+    Animal.feed();
+  }
+}
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+No easy way to do that +
+
+
class Animal {
+  public void eat(String food) {
+    if (isMeat(food))
+      System.out.println("Om nom nom");
+  }
+
+  private boolean isMeat(String food) {
+    return food.equals("meat");
+  }
+}
+
+class ClassPrivateMethod {
+  public static void main(String[] args) {
+    new Animal().eat("meat");
+  }
+}
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+No easy way to do that +
+
+
class Animal {
+  private String name;
+
+  public Animal(String name) {
+    this.name = name;
+    greet();
+  }
+
+  private void greet() {
+    System.out.println("Hello! My name is " + this.name);
+  }
+}
+
+class ClassPrivateMethodAccessInstance {
+  public static void main(String[] args) {
+    new Animal("Kelya");
+  }
+}
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+
class Animal {
+  private String toy;
+
+  public void take(String toy) {
+    this.toy = toy;
+  }
+
+  public void play() {
+    System.out.println("I'm playing with " + this.toy);
+  }
+}
+
+class ClassField {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.take("a ball");
+    animal.play();
+  }
+}
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+
class Animal {
+  private String name;
+
+  public void setName(String name) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return this.name;
+  }
+}
+
+class ClassGetSet {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    animal.setName("Kelya");
+    System.out.println(animal.getName());
+  }
+}
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+
class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  public void sing() {
+    System.out.println("Bark!");
+  }
+}
+
+class ClassInheritance {
+  public static void main(String[] args) {
+    new Dog().walk();
+  }
+}
+
+ +
I'm walking
+
+
+
+

+Has method? + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+
import java.lang.reflect.*;
+
+class Animal {
+  public void walk() {
+    System.out.println("I'm walking");
+  }
+}
+
+class ClassHasMethod {
+  public static void main(String[] args) {
+    Animal animal = new Animal();
+    boolean hasMethod = false;
+    for (Method m : animal.getClass().getMethods()) {
+      if (m.getName().equals("walk")) {
+        hasMethod = true;
+        break;
+      }
+    }
+    System.out.println(hasMethod);
+  }
+}
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
// it's a comment
+
+ +

+
+
+
class OtherComment {
+  public static void main(String[] args) {
+    // it's a comment
+  }
+}
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+
// OtherFileToImport.java
+// class OtherFileToImport {
+//   public OtherFileToImport() {
+//     System.out.println("I am imported!");
+//   }
+// }
+
+class OtherImportFile {
+  public static void main(String[] args) {
+    new OtherFileToImport();
+  }
+}
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+No easy way to do that +
+
+

+Date + + + + + +

+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+  public static void main(String[] args) {
+    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+    System.out.println(date);
+  }
+}
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+  public static void main(String[] args) {
+    String time = new SimpleDateFormat().format(new Date());
+    System.out.println(time);
+  }
+}
+
+ +
28/05/2024, 20:16
+
+
+
+

+Not + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
class OtherNot {
+  public static void main(String[] args) {
+    boolean angry = false;
+    if (!angry)
+      System.out.println("smile!");
+  }
+}
+
+ +
smile!
+
+
+
+

+Run command + + + + + +

+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
import java.io.*;
+
+class OtherRunCommand {
+  public static void main(String[] args) throws IOException, InterruptedException {
+    String result = "";
+    ProcessBuilder ps = new ProcessBuilder("java", "-version");
+    ps.redirectErrorStream(true);
+    Process pr = ps.start();
+    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+    String line;
+    while ((line = in.readLine()) != null)
+      result += line + "\n";
+    pr.waitFor();
+    in.close();
+    System.out.println(result);
+  }
+}
+
+ +
openjdk version "17.0.8.1" 2023-08-24
+OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
+OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)
+
+
+
+
+
+ + + + + + + + + + diff --git a/javascript-javascript/index.html b/javascript-javascript/index.html new file mode 100644 index 0000000..67d9b2d --- /dev/null +++ b/javascript-javascript/index.html @@ -0,0 +1,3436 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

JavaScript

+
+
+

JavaScript

+
+
+

String

+

+Create + + + + + +

+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+

+Float + + + + + +

+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+

+Int to Float + + + + + +

+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+

+Add + + + + + +

+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+

+With different types + + + + + +

+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+

+Include? + + + + + +

+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+

+Sort + + + + + +

+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+

+Unique + + + + + +

+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+

+Add + + + + + +

+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+

+Iterate + + + + + +

+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+

+Include? + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+

+Constant list + + + + + +

+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+

+Ternary + + + + + +

+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+

+Break + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+

+Throw exception + + + + + +

+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+

+Get working dir path + + + + + +

+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+

+Dir path + + + + + +

+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+

+Parent dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+

+Default value for argument + + + + + +

+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+

+Closure + + + + + +

+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+

+Block binding + + + + + +

+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+

+Alias + + + + + +

+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+

+Has method? + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
// it's a comment
+
+ +

+
+
+
// it's a comment
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+

+Date + + + + + +

+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+

+Time + + + + + +

+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+

+Not + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+

+Run command + + + + + +

+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
+ + + + + + + + + + diff --git a/javascript-php/index.html b/javascript-php/index.html new file mode 100644 index 0000000..03cf25a --- /dev/null +++ b/javascript-php/index.html @@ -0,0 +1,3670 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+
+ + +
+
+
+
+

JavaScript

+
+
+

PHP

+
+
+

String

+

+Create + + + + + +

+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+ +
Hello World!
+
+
+

+Concatenation + + + + + +

+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+
<?php
+
+echo "Don't worry," . " be happy";
+
+ +
Don't worry, be happy
+
+
+

+Interpolation + + + + + +

+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+ +
Don't worry, be happy
+
+
+

+Remove part + + + + + +

+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+ +
This is funny! I am like him!
+
+
+

+Replace + + + + + +

+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+ +
You should rest
+
+
+

+Split + + + + + +

+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+ +
array (
+  0 => 'I',
+  1 => 'like',
+  2 => 'beer',
+)
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+
<?php
+
+echo trim(" eh? ");
+ +
eh?
+
+
+

+Compare + + + + + +

+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+
<?php
+
+var_dump(strcmp("string", "string") == 0);
+ +
bool(true)
+
+
+
+

+Regex + + + + + +

+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+ +
bool(false)
+bool(true)
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+ +
10
+
+
+

+Compare + + + + + +

+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+ +
bool(true)
+bool(true)
+bool(false)
+
+
+
+

+Random + + + + + +

+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+
<?php
+
+echo rand(1, 2);
+ +
1
+
+
+

+Float + + + + + +

+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+ +
float(4.5)
+float(4.5)
+float(4)
+float(5)
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+ +
string
+object
+DateTime
+
+
+
+

+Int to Float + + + + + +

+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+
<?php
+
+var_dump((float)10);
+
+ +
float(10)
+
+
+
+

+Int to String + + + + + +

+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+
<?php
+
+var_dump((string)10);
+
+ +
string(2) "10"
+
+
+
+

+String to Int + + + + + +

+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+
<?php
+
+var_dump((int)"10");
+
+ +
int(10)
+
+
+
+

+String? + + + + + +

+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+ +
bool(true)
+bool(true)
+
+
+
+

+Null/True/False? + + + + + +

+
+
+No easy way to do that +
+
+
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+ +
bool(false)
+bool(true)
+bool(true)
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+ +
Array
+(
+    [0] => first
+    [1] => second
+)
+
+
+
+

+Add + + + + + +

+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+ +
Array
+(
+    [0] => first
+    [1] => second
+)
+
+
+
+

+With different types + + + + + +

+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+
<?php
+
+print_r(["first", 1]);
+
+ +
Array
+(
+    [0] => first
+    [1] => 1
+)
+
+
+
+

+Include? + + + + + +

+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+ +
bool(true)
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+
<?php
+
+foreach ([1, 2] as $num) {
+    var_dump($num);
+}
+ +
int(1)
+int(2)
+
+
+
+

+Iterate with index + + + + + +

+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+    echo "$key\n";
+    echo "$value\n";
+}
+ +
fontSize
+10
+fontFamily
+Arial
+
+
+
+

+Get first, last element + + + + + +

+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+ +
string(3) "one"
+string(3) "two"
+
+
+
+

+Find first + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+    if ($n % 2 == 0) {
+        $first = $n;
+        break;
+    }
+}
+var_dump($first);
+ +
int(10)
+
+
+
+

+Select (find all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+    return $n % 2 == 0;
+});
+print_r($filtered);
+
+ +
Array
+(
+    [2] => 10
+    [3] => 20
+)
+
+
+
+

+Map (change all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+    return $n * 2;
+}, $arr);
+print_r($mapped);
+ +
Array
+(
+    [0] => 2
+    [1] => 10
+    [2] => 20
+    [3] => 40
+)
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+ +
Array
+(
+    [0] => 1
+    [1] => 2
+    [2] => 3
+    [3] => 4
+)
+
+
+
+

+Sort + + + + + +

+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+ +
Array
+(
+    [0] => 1
+    [1] => 2
+    [2] => 3
+    [3] => 4
+)
+
+
+
+

+Multidimensional + + + + + +

+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+ +
string(5) "forth"
+
+
+
+

+Size + + + + + +

+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+ +
int(3)
+
+
+
+

+Count + + + + + +

+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+    if ($n > 10)
+        $count++;
+var_dump($count);
+ +
int(2)
+
+
+
+

+Reduce + + + + + +

+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+    return $carry + $item;
+});
+print_r($reduced);
+ +
6
+
+
+

+Index of element + + + + + +

+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+ +
int(2)
+
+
+
+

+Delete element + + + + + +

+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+ +
Array
+(
+    [0] => a
+    [2] => c
+)
+
+
+
+

+Unique + + + + + +

+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+ +
Array
+(
+    [0] => a
+    [1] => b
+)
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+ +
array(2) {
+  ["fontSize"]=>
+  string(2) "10"
+  ["fontFamily"]=>
+  string(5) "Arial"
+}
+
+
+
+

+Add + + + + + +

+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+ +
array(2) {
+  ["fontSize"]=>
+  string(2) "10"
+  ["fontFamily"]=>
+  string(5) "Arial"
+}
+
+
+
+

+Iterate + + + + + +

+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+    echo "$key\n";
+    echo "$value\n";
+}
+ +
fontSize
+10
+fontFamily
+Arial
+
+
+
+

+Include? + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+ +
bool(true)
+
+
+
+

+Get value + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+ +
string(2) "10"
+
+
+
+

+Size + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+ +
2
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+
<?php
+
+$tryIt = true;
+if ($tryIt)
+    echo "Garlic gum is not funny";
+
+ +
Garlic gum is not funny
+
+
+

+Constant + + + + + +

+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+ +
PHP Warning:  Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4
+
+Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4
+100
+
+
+

+Constant list + + + + + +

+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+No easy way to do that +
+
+

Conditional

+

+If + + + + + +

+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+
<?php
+
+if (true)
+    echo "Hello";
+
+ +
Hello
+
+
+

+Unless + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
<?php
+
+$angry = false;
+if (!$angry)
+    echo "smile!";
+
+ +
smile!
+
+
+

+If/else + + + + + +

+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+
<?php
+
+if (true)
+    echo "work";
+else
+    echo "sleep";
+
+ +
work
+
+
+

+And/Or + + + + + +

+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+
<?php
+
+if (true && false)
+    echo "no";
+if (true || false)
+    echo "yes";
+
+ +
yes
+
+
+

+Switch + + + + + +

+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+
<?php
+
+$s = "Hello!";
+switch ($s) {
+    case "Bye!":
+        echo "wrong";
+        break;
+    case "Hello!":
+        echo "right";
+        break;
+    default:
+        break;
+}
+
+ +
right
+
+
+

+Ternary + + + + + +

+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+ +
yes
+
+
+

Loop

+

+For + + + + + +

+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
<?php
+
+for ($i = 1; $i <= 3; $i++)
+    echo $i . ". Hi\n";
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+    echo $i . "\n";
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++)
+    echo "Hi\n";
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
<?php
+
+$i = 0;
+while ($i < 3)
+    $i++;
+echo $i;
+
+ +
3
+
+
+

+Until + + + + + +

+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
<?php
+
+$i = 0;
+while ($i != 3)
+    $i++;
+echo $i;
+
+ +
3
+
+
+

+Return array + + + + + +

+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+No easy way to do that +
+
+

+Break + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++) {
+    echo ($i + 1) . ". Hi\n";
+    if ($i == 1)
+        break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
<?php
+
+for ($i = 0; $i < 3; $i++) {
+    if ($i == 1)
+        continue;
+    echo ($i + 1) . ". Hi\n";
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+
<?php
+
+echo sqrt(9);
+
+ +
3
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+
<?php
+
+try {
+    throw new Exception();
+} catch (Exception $e) {
+    echo "Can't divide\n";
+} finally {
+    echo "But that's ok\n";
+}
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+
<?php
+
+try {
+    throw new Exception("An error!");
+} catch (Exception $e) {
+    echo $e->getMessage();
+}
+
+ +
An error!
+
+
+

+Throw exception + + + + + +

+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+
<?php
+
+try {
+    throw new Exception("An error!");
+} catch (Exception $e) {
+    echo $e->getMessage();
+}
+
+ +
An error!
+
+
+

File

+

+Read + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+ +
Hello
+World
+
+
+
+

+Write + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
<?php
+
+echo getcwd();
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+

+File path + + + + + +

+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+
<?php
+
+echo __FILE__;
+
+ +
/Users/evmorov/projects/lang-compare/code/php/FilePath.php
+
+
+

+Dir path + + + + + +

+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+
<?php
+
+echo __DIR__;
+
+ +
/Users/evmorov/projects/lang-compare/code/php
+
+
+

+Parent dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
<?php
+
+echo realpath(__DIR__ . "/..");
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+

+Sister dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+

Method

+

+Declare + + + + + +

+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+
<?php
+
+function hey()
+{
+    echo "How are you?";
+}
+
+hey();
+
+ +
How are you?
+
+
+

+Multiple arguments + + + + + +

+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+    if ($buy)
+        var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+ +
array(3) {
+  [0]=>
+  string(8) "snickers"
+  [1]=>
+  string(4) "twix"
+  [2]=>
+  string(6) "bounty"
+}
+
+
+
+

+Default value for argument + + + + + +

+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+No easy way to do that +
+
+

+Return + + + + + +

+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+
<?php
+
+function divide(int $a, int $b) : float
+{
+    if ($a == 0)
+        return 0;
+    return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+ +
0
+2
+0.5
+
+
+
+

+Closure + + + + + +

+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+No easy way to do that +
+
+

+Block passing + + + + + +

+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+No easy way to do that +
+
+

+Block binding + + + + + +

+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+No easy way to do that +
+
+

+Alias + + + + + +

+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+No easy way to do that +
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+
<?php
+
+class AnimalC
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+ +
I'm walking
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+
<?php
+
+class AnimalB
+{
+    private $name;
+
+    public function __construct(string $name)
+    {
+        $this->name = $name;
+    }
+
+    public function walk()
+    {
+        echo "My name is {$this->name} and I'm walking";
+    }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+ +
My name is Kelya and I'm walking
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+
<?php
+
+class AnimalH
+{
+    public function walk()
+    {
+        $this->bark();
+        $this->guard();
+        echo "I'm walking\n";
+    }
+
+    public function bark()
+    {
+        echo "Wuf!\n";
+    }
+
+    private function guard()
+    {
+        echo "WUUUF!\n";
+    }
+}
+
+(new AnimalH())->walk();
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+
<?php
+
+class AnimalA
+{
+    public static function feed()
+    {
+        echo "Om nom nom";
+    }
+}
+
+AnimalA::feed();
+
+ +
Om nom nom
+
+
+

+Private method + + + + + +

+
+
+No easy way to do that +
+
+
<?php
+
+class AnimalI
+{
+    public function eat(string $food)
+    {
+        if ($this->isMeat($food))
+            echo "Om nom nom";
+    }
+
+    private function isMeat(string $food) : bool
+    {
+        return strcmp($food, "meat") == 0;
+    }
+}
+
+(new AnimalI())->eat("meat");
+
+ +
Om nom nom
+
+
+

+Private method, access instance variable + + + + + +

+
+
+No easy way to do that +
+
+
<?php
+
+class AnimalJ
+{
+    private $name;
+
+    public function __construct(string $name)
+    {
+        $this->name = $name;
+        $this->greet();
+    }
+
+    private function greet()
+    {
+        echo "Hello! My name is " . $this->name;
+    }
+}
+
+new AnimalJ("Kelya");
+
+ +
Hello! My name is Kelya
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+
<?php
+
+class AnimalD
+{
+
+    private $toy;
+
+    public function take(string $toy)
+    {
+        $this->toy = $toy;
+    }
+
+    public function play()
+    {
+        echo "I'm playing with " . $this->toy;
+    }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+ +
I'm playing with a ball
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+
<?php
+
+class AnimalE
+{
+    private $name;
+
+    public function setName(string $name)
+    {
+        $this->name = $name;
+    }
+
+    public function getName() : string
+    {
+        return $this->name;
+    }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+ +
Kelya
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+
<?php
+
+class AnimalG
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+class Dog extends AnimalG
+{
+    public function sing()
+    {
+        echo "Bark!";
+    }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+ +
I'm walking
+
+
+

+Has method? + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+
<?php
+
+class AnimalF
+{
+    public function walk()
+    {
+        echo "I'm walking";
+    }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+ +
bool(true)
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
// it's a comment
+
+ +

+
+
+
<?php
+
+// it's a comment
+
+ +

+
+
+

+Import another file + + + + + +

+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+ +
I am imported!
+
+
+

+Destructuring assignment + + + + + +

+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+No easy way to do that +
+
+

+Date + + + + + +

+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+ +
2024-05-28
+
+
+

+Time + + + + + +

+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+ +
05/28/24 06:22 PM
+
+
+

+Not + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
<?php
+
+$angry = false;
+if (!$angry)
+    echo "smile!";
+
+ +
smile!
+
+
+

+Run command + + + + + +

+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+ +
PHP 8.2.8 (cli) (built: Jul  6 2023 11:16:57) (NTS)
+
+
+
+ + + + + + + + + + diff --git a/javascript-python/index.html b/javascript-python/index.html new file mode 100644 index 0000000..0cab707 --- /dev/null +++ b/javascript-python/index.html @@ -0,0 +1,3751 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+ +
+
+
+

JavaScript

+
+
+

Python

+
+
+

String

+

+Create + + + + + +

+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+
greeting = 'Hello World!'
+print(greeting)
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+
print("Don't worry," + ' be happy')
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+ +
Don't worry, be happy
+
+[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+
print('You should work'.replace('work', 'rest'))
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+
print('I like beer'.split())
+
+ +
['I', 'like', 'beer']
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+
print(' eh? '.strip())
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+
print('string' == 'string')
+print('string' != 'string')
+
+ +
True
+False
+
+
+
+

+Regex + + + + + +

+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+ +
None
+<re.Match object; span=(0, 1), match='a'>
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+
i = 9
+i += 1
+print(i)
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+ +
True
+True
+False
+
+
+
+

+Random + + + + + +

+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+
import random
+
+print(random.randint(1, 2))
+
+ +
2
+
+
+
+

+Float + + + + + +

+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2))  # rounds half to even
+
+ +
4
+4.5
+4
+4
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+
print(type('hi'))
+print(type(1))
+
+ +
<class 'str'>
+<class 'int'>
+
+
+
+

+Int to Float + + + + + +

+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+
print(float(10))
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+
print(str(10))
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+
print(int('5'))
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+
print(isinstance('10', str))
+
+ +
True
+
+
+
+

+Null/True/False? + + + + + +

+
+
+No easy way to do that +
+
+
def check(label, fn, values):
+    print(label)
+    for value in values:
+        try:
+            result = 'true' if fn(value) else 'false'
+        except TypeError as e:
+            result = 'error: %s' % e
+        print("  %-9r - %s" % (value, result))
+    print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+ +
if value:
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - true
+  0         - false
+  True      - true
+  False     - false
+  None      - false
+
+if value is None:
+  'string'  - false
+  ''        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  True      - false
+  False     - false
+  None      - true
+
+if len(value):
+  'string'  - true
+  ''        - false
+  [1, 2, 3] - true
+  []        - false
+  5         - error: object of type 'int' has no len()
+  0         - error: object of type 'int' has no len()
+  True      - error: object of type 'bool' has no len()
+  False     - error: object of type 'bool' has no len()
+  None      - error: object of type 'NoneType' has no len()
+
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
arr = ['first', 'second']
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+Add + + + + + +

+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+ +
['first', 'second']
+
+
+
+

+With different types + + + + + +

+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+
print(['first', 1])
+
+ +
['first', 1]
+
+
+
+

+Include? + + + + + +

+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+
print(1 in [1, 2])
+
+ +
True
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+
for num in [1, 2]:
+  print(num)
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+
for i, num in enumerate(['one', 'two']):
+  print(num)
+  print(i)
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+ +
[10, 20]
+
+
+
+

+Map (change all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+ +
[2, 10, 20, 40]
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
print([1, 2] + [3, 4])
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Sort + + + + + +

+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
print(sorted([4, 2, 3, 1]))
+
+ +
[1, 2, 3, 4]
+
+
+
+

+Multidimensional + + + + + +

+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+
print(len([1, 2, 3]))
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3]))  # a more Pythonic example
+
+ +
6
+6
+
+
+
+

+Index of element + + + + + +

+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+
print(['a', 'b', 'c'].index('c'))
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+ +
['a', 'c']
+
+
+
+

+Unique + + + + + +

+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+
print(set(['a', 'b', 'a']))
+
+ +
{'a', 'b'}
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Add + + + + + +

+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+ +
{'font_size': 10, 'font_family': 'Arial'}
+
+
+
+

+Iterate + + + + + +

+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+  print(key, value)
+
+ +
font_size 10
+font_family Arial
+
+
+
+

+Include? + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+ +
True
+
+
+
+

+Get value + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+
try_it = True
+if try_it:
+    print('Garlic gum is not funny')
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+
COST = 100
+COST = 50
+print(COST)
+
+ +
50
+
+
+
+

+Constant list + + + + + +

+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+
class Colors:
+    RED = '#FF0000'
+    GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+ +
#00FF00
+
+
+
+

+Struct + + + + + +

+
+
+No easy way to do that +
+
+
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+    def greeting(self):
+        return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+ +
Hello Dave!
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+
if True:
+    print('Hello')
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+    print('smile!')
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+
if True:
+  print('work')
+else:
+  print('sleep')
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+
if True and False:
+    print('no')
+if True or False:
+    print('yes')
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+
foo = 'Hello!'
+if foo in range(1, 6):
+    print("It's between 1 and 5")
+elif foo in (10, 20):
+    print('10 or 20')
+elif foo == 'And':
+    print('case in one line')
+elif isinstance(foo, str):
+    print("You passed a string %r" % foo)
+else:
+    print("You gave me %r" % foo)
+
+ +
You passed a string 'Hello!'
+
+
+
+

+Switch as else if + + + + + +

+
+
+No easy way to do that +
+
+
score = 76
+grades = [
+    (60, 'F'),
+    (70, 'D'),
+    (80, 'C'),
+    (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+ +
C
+
+
+
+

+Ternary + + + + + +

+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+
print('no' if False else 'yes')
+
+ +
yes
+
+
+
+

+If assign + + + + + +

+
+
+No easy way to do that +
+
+
result = 'a' if True else 'b'
+print(result)
+
+ +
a
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
for i in range(1, 4):
+    print('%d. Hi' % i)
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+
for i in range(0, 5, 2):
+    print(i)
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
for i in range(3):
+  print('Hi')
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
i = 0
+while i < 3:
+  i += 1
+print(i)
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
i = 0
+while i != 3:
+    i += 1
+print(i)
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+ +
['1. Hello!', '2. Hello!', '3. Hello!']
+
+
+
+

+Break + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
for time in range(1, 4):
+  print("%d. Hi" % time)
+  if time == 2:
+    break
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
for time in range(1, 4):
+  if time == 2:
+      continue
+  print("%d. Hi" % time)
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+
import math
+
+print(math.sqrt(9))
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+
try:
+  1 / 0
+except:
+  print("Can't divide")
+finally:
+  print("But that's ok")
+
+ +
Can't divide
+But that's ok
+
+
+
+

+With a message + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+
try:
+  1 / 0
+except Exception as e:
+  print(e)
+
+ +
division by zero
+
+
+
+

+Method + + + + + +

+
+
+No easy way to do that +
+
+
def divide(num1, num2):
+  try:
+    num1 / num2
+  except Exception as e:
+    print(e)
+divide(1, 0)
+
+ +
division by zero
+
+
+
+

+Throw exception + + + + + +

+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+
try:
+  raise Exception('An error!')
+except Exception as e:
+  print(e)
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+    print(f.read())
+
+ +
Hello
+World
+
+
+
+
+

+Write + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+    f.write('Some glorious content')
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
import os
+
+print(os.getcwd())
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+
print(__file__)
+
+ +
/Users/evmorov/projects/lang-compare/code/python/file_path.py
+
+
+
+

+Dir path + + + + + +

+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+

+Parent dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+
def hey():
+  print('How are you?')
+hey()
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+
def sweets(buy, *brands):
+  if buy:
+      print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+ +
('snickers', 'twix', 'bounty')
+
+
+
+

+Default value for argument + + + + + +

+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+
def send(abroad=False):
+  print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+
def multiply(a, b):
+    return a * b
+
+def divide(a, b):
+    return 0 if a == 0 else a / b
+
+def default_value():
+    pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+ +
6
+0
+None
+
+
+
+

+Closure + + + + + +

+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+ +
[4, 9]
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+
def select(arr):
+    yield from arr
+
+def select_filter(arr, filter):
+    for a in arr:
+        if filter(a):
+            yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+ +
[1, 5]
+[1, 5]
+
+
+
+

+Block binding + + + + + +

+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+
class Action:
+  name = 'Ann'
+
+  @staticmethod
+  def say(sentence):
+    print(sentence())
+
+
+class Person:
+  def __init__(self, name):
+    self.name = name
+
+  def greet(self):
+    Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+ +
My name is Alex!
+
+
+
+

+Initialize in runtime + + + + + +

+
+
+No easy way to do that +
+
+
class ProccessElements:
+  def __init__(self):
+    def element(el_name):
+      def render(content):
+        return '<{0}>{1}</{0}>'.format(el_name, content)
+      return render
+
+    for el_name in self.elements:
+      setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+  elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+ +
<div>hello</div>
+
+
+
+

+Alias + + + + + +

+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+
class Greetings:
+  def hey(self):
+    print('How are you?')
+  hi = hey
+
+Greetings().hi()
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+Animal().walk()
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+
+  def walk(self):
+    print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    self.bark()
+    self._guard()
+    print("I'm walking")
+
+  def bark(self):
+    print('Wuf!')
+
+  # Private by convention
+  def _guard(self):
+    print('WUUUF!')
+
+Animal().walk()
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+
class Animal:
+  @classmethod
+  def feed(cls):
+    print('Om nom nom')
+
+Animal.feed()
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+No easy way to do that +
+
+
class Animal:
+  def eat(self, food):
+    if self._is_meat(food):
+      print('Om nom nom')
+
+  def _is_meat(self, food):
+    return food == 'meat'
+
+Animal().eat('meat')
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+No easy way to do that +
+
+
class Animal:
+  def __init__(self, name):
+    self.name = name
+    self._greet()
+
+  def _greet(self):
+    print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+
class Animal:
+  def take(self, toy):
+    self.toy = toy
+
+  def play(self):
+    print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+
class Animal:
+  name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+class Dog(Animal):
+  def sing(self):
+    print('Bark!')
+
+Dog().walk()
+
+ +
I'm walking
+
+
+
+

+Mixin + + + + + +

+
+
+No easy way to do that +
+
+
class Moving:
+  def walk(self):
+    print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+  def talk(self):
+    print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+    pass
+
+human = Human()
+human.walk()
+human.talk()
+
+ +
Human is walking
+Human is talking
+
+
+
+

+Has method? + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+
class Animal:
+  def walk(self):
+    print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+ +
True
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
// it's a comment
+
+ +

+
+
+
# it's a comment
+
+ +

+
+
+

+Assign value if not exist + + + + + +

+
+
+No easy way to do that +
+
+
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+ +
0
+
+
+
+

+Import another file + + + + + +

+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+
# other_file_to_import.py
+# class Import:
+#   def __init__(self):
+#     print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+
one, two = 1, 2
+print(one, two)
+
+ +
1 2
+
+
+
+

+Date + + + + + +

+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+
import datetime
+print(datetime.date.today())
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+
import datetime
+print(datetime.datetime.now())
+
+ +
2024-05-28 20:18:14.644332
+
+
+
+

+Not + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
angry = False
+if not angry:
+  print('smile!')
+
+ +
smile!
+
+
+
+

+Assign this or that + + + + + +

+
+
+No easy way to do that +
+
+
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+ +
bear
+
+
+
+

+Run command + + + + + +

+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
import subprocess
+subprocess.call(['python3', '--version'])
+
+ +
Python 3.11.2
+
+
+
+
+ + + + + + + + + + diff --git a/javascript-ruby/index.html b/javascript-ruby/index.html new file mode 100644 index 0000000..99be4ba --- /dev/null +++ b/javascript-ruby/index.html @@ -0,0 +1,3859 @@ + + + + + +Language compare + + + +
+ + +Fork me on GitHub + +
+

+Language compare +

+
+
+ +
+
+ +
+
+
+
+ + +
+ +
+
+
+

JavaScript

+
+
+

Ruby

+
+
+

String

+

+Create + + + + + +

+
+
+
const greeting = 'Hello World!';
+console.log(greeting);
+
+ +
Hello World!
+
+
+
+
greeting = 'Hello World!'
+puts greeting
+
+ +
Hello World!
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log("Don't worry" + ' be happy');
+
+ +
Don't worry be happy
+
+
+
+
puts "Don't worry," + ' be happy'
+
+ +
Don't worry, be happy
+
+
+
+

+Interpolation + + + + + +

+
+
+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+ +
Don't worry, be happy
+
+
+
+
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+ +
Don't worry, be happy
+
+
+
+

+Remove part + + + + + +

+
+
+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+ +
This is funny! I am like him!
+
+
+
+
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+ +
This is funny! I am like him!
+
+
+
+

+Replace + + + + + +

+
+
+
console.log('You should work'.replace(/work/g, 'rest'));
+
+ +
You should rest
+
+
+
+
puts 'You should work'.gsub('work', 'rest')
+
+ +
You should rest
+
+
+
+

+Split + + + + + +

+
+
+
console.log('I like beer'.split(' '));
+
+ +
[ 'I', 'like', 'beer' ]
+
+
+
+
puts 'I like beer'.split
+
+ +
I
+like
+beer
+
+
+
+

+Remove leading and trailing whitespace + + + + + +

+
+
+
console.log(' eh? '.trim());
+
+ +
eh?
+
+
+
+
puts ' eh? '.strip
+
+ +
eh?
+
+
+
+

+Compare + + + + + +

+
+
+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+ +
true
+false
+
+
+
+
puts 'string' == 'string'
+puts 'string' != 'string'
+
+ +
true
+false
+
+
+
+

+Regex + + + + + +

+
+
+
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+ +
null
+[ 'a', index: 0, input: 'apple', groups: undefined ]
+
+
+
+
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+ +
nil
+0
+
+
+
+

Number

+

+Increment + + + + + +

+
+
+
let i = 9;
+i++;
+console.log(i);
+
+ +
10
+
+
+
+
i = 9
+i += 1
+puts i
+
+ +
10
+
+
+
+

+Compare + + + + + +

+
+
+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+ +
true
+true
+false
+
+
+
+
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+ +
true
+true
+false
+
+
+
+

+Random + + + + + +

+
+
+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+ +
2
+
+
+
+
puts rand(1..2)
+
+ +
1
+
+
+
+

+Float + + + + + +

+
+
+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+ +
4.5
+4.5
+4
+5
+
+
+
+
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+ +
4
+4.5
+4
+5
+
+
+
+

Type

+

+Get type of object + + + + + +

+
+
+
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+ +
string
+number
+String
+Number
+
+
+
+
puts 'hi'.class
+puts 1.class
+
+ +
String
+Fixnum
+
+
+
+

+Int to Float + + + + + +

+
+
+
console.log((10).toFixed(1));
+
+ +
10.0
+
+
+
+
puts 10.to_f
+
+ +
10.0
+
+
+
+

+Int to String + + + + + +

+
+
+
console.log((10).toString());
+
+ +
10
+
+
+
+
puts 10.to_s
+
+ +
10
+
+
+
+

+String to Int + + + + + +

+
+
+
console.log(parseInt('5', 10));
+
+ +
5
+
+
+
+
puts '5'.to_i
+
+ +
5
+
+
+
+

+String? + + + + + +

+
+
+
console.log(typeof '10' === 'string');
+
+ +
true
+
+
+
+
puts '10'.is_a? String
+
+ +
true
+
+
+
+

+Null/True/False? + + + + + +

+
+
+No easy way to do that +
+
+
def check(label, fn, values)
+  puts label
+  values.each do |value|
+    begin
+      result = fn.call(value) ? 'true' : 'false'
+    rescue NoMethodError => e
+      result = "error: #{e}"
+    end
+    puts format("  %-9p - %s", value, result)
+  end
+  puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+ +
if value:
+  "string"  - true
+  ""        - true
+  [1, 2, 3] - true
+  []        - true
+  5         - true
+  0         - true
+  true      - true
+  false     - false
+  nil       - false
+
+if value.nil?:
+  "string"  - false
+  ""        - false
+  [1, 2, 3] - false
+  []        - false
+  5         - false
+  0         - false
+  true      - false
+  false     - false
+  nil       - true
+
+if value.empty?:
+  "string"  - false
+  ""        - true
+  [1, 2, 3] - false
+  []        - true
+  5         - error: undefined method `empty?' for 5:Fixnum
+  0         - error: undefined method `empty?' for 0:Fixnum
+  true      - error: undefined method `empty?' for true:TrueClass
+  false     - error: undefined method `empty?' for false:FalseClass
+  nil       - error: undefined method `empty?' for nil:NilClass
+
+
+
+
+

Array

+

+Create populated + + + + + +

+
+
+
const arr = ['first', 'second'];
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
arr = %w(first second)
+puts arr
+
+ +
first
+second
+
+
+
+

+Add + + + + + +

+
+
+
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+ +
[ 'first', 'second' ]
+
+
+
+
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+ +
first
+second
+
+
+
+

+With different types + + + + + +

+
+
+
console.log(['first', 1]);
+
+ +
[ 'first', 1 ]
+
+
+
+
puts ['first', 1]
+
+ +
first
+1
+
+
+
+

+Include? + + + + + +

+
+
+
console.log([1, 2].includes(1));
+
+ +
true
+
+
+
+
puts [1, 2].include? 1
+
+ +
true
+
+
+
+

+Iterate + + + + + +

+
+
+
[1, 2].forEach(num => console.log(num));
+
+ +
1
+2
+
+
+
+
[1, 2].each do |num|
+  puts num
+end
+
+ +
1
+2
+
+
+
+

+Iterate with index + + + + + +

+
+
+
['one', 'two'].forEach((num, i) => {
+  console.log(num);
+  console.log(i);
+});
+
+ +
one
+0
+two
+1
+
+
+
+
%w(one two).each_with_index do |num, i|
+  puts num
+  puts i
+end
+
+ +
one
+0
+two
+1
+
+
+
+

+Get first, last element + + + + + +

+
+
+
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+ +
one
+two
+
+
+
+
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+ +
one
+two
+
+
+
+

+Find first + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+ +
10
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+ +
10
+
+
+
+

+Select (find all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+ +
[ 10, 20 ]
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+ +
10
+20
+
+
+
+

+Map (change all) + + + + + +

+
+
+
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+ +
[ 2, 10, 20, 40 ]
+
+
+
+
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+ +
2
+10
+20
+40
+
+
+
+

+Concatenation + + + + + +

+
+
+
console.log([1, 2].concat([3, 4]));
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
puts [1, 2] + [3, 4]
+
+ +
1
+2
+3
+4
+
+
+
+

+Sort + + + + + +

+
+
+
console.log([4, 2, 3, 1].sort());
+
+ +
[ 1, 2, 3, 4 ]
+
+
+
+
puts [4, 2, 3, 1].sort
+
+ +
1
+2
+3
+4
+
+
+
+

+Multidimensional + + + + + +

+
+
+
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+ +
forth
+
+
+
+
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+ +
forth
+
+
+
+

+Size + + + + + +

+
+
+
console.log([1, 2, 3].length);
+
+ +
3
+
+
+
+
puts [1, 2, 3].size 
+
+ +
3
+
+
+
+

+Count + + + + + +

+
+
+
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+ +
2
+
+
+
+
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+ +
2
+
+
+
+

+Reduce + + + + + +

+
+
+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+ +
6
+
+
+
+
puts [1, 2, 3].reduce(:+)
+
+ +
6
+
+
+
+

+Index of element + + + + + +

+
+
+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+ +
2
+
+
+
+
puts ['a', 'b', 'c'].index('c')
+
+ +
2
+
+
+
+

+Delete element + + + + + +

+
+
+
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+ +
[ 'a', 'c' ]
+
+
+
+
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+ +
a
+c
+
+
+
+

+Unique + + + + + +

+
+
+
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+ +
[ 'a', 'b' ]
+
+
+
+
puts %w(a b a).uniq
+
+ +
a
+b
+
+
+
+

Hash (map)

+

+Create populated + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+

+Add + + + + + +

+
+
+
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+ +
{ font_size: 10, font_family: 'Arial' }
+
+
+
+
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+ +
{:font_size=>10, :font_family=>"Arial"}
+
+
+
+

+Iterate + + + + + +

+
+
+
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+  const value = hsh[key];
+  console.log(key, value);
+}
+
+ +
font_size 10
+font_family Arial
+
+
+
+
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+  puts key, value
+end
+
+ +
font_size
+10
+font_family
+Arial
+
+
+
+

+Include? + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+ +
true
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+ +
true
+
+
+
+

+Get value + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+ +
10
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+ +
10
+
+
+
+

+Size + + + + + +

+
+
+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+ +
2
+
+
+
+
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+ +
2
+
+
+
+

Other structure

+

+Boolean + + + + + +

+
+
+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+ +
Garlic gum is not funny
+
+
+
+
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+ +
Garlic gum is not funny
+
+
+
+

+Constant + + + + + +

+
+
+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2
+COST = 50;
+     ^
+
+TypeError: Assignment to constant variable.
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47
+
+Node.js v18.17.0
+
+
+
+
COST = 100
+COST = 50
+puts COST
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here
+50
+
+
+
+

+Constant list + + + + + +

+
+
+
const Colors = Object.freeze({
+  RED: '#FF0000',
+  GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+ +
#00FF00
+
+
+
+
module Colors
+  RED = '#FF0000'
+  GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+ +
#00FF00
+
+
+
+

+Struct + + + + + +

+
+
+No easy way to do that +
+
+
Customer = Struct.new(:name, :address) do
+  def greeting
+    "Hello #{name}!"
+  end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+ +
Hello Dave!
+
+
+
+

Conditional

+

+If + + + + + +

+
+
+
if (true) console.log('Hello');
+
+ +
Hello
+
+
+
+
puts 'Hello' if true
+
+ +
Hello
+
+
+
+

+Unless + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
angry = false
+puts 'smile!' unless angry
+
+ +
smile!
+
+
+
+

+If/else + + + + + +

+
+
+
if (true) {
+  console.log('work');
+} else {
+  console.log('sleep');
+}
+
+ +
work
+
+
+
+
if true
+  puts 'work'
+else
+  puts 'sleep'
+end
+
+ +
work
+
+
+
+

+And/Or + + + + + +

+
+
+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+ +
yes
+
+
+
+
puts 'no' if true && false
+puts 'yes' if true || false
+
+ +
yes
+
+
+
+

+Switch + + + + + +

+
+
+
const foo = 'Hello!';
+switch (foo) {
+  case 10: case 20:
+    console.log('10 or 20');
+    break;
+  case 'And': console.log('case in one line'); break;
+  default:
+    console.log(`You gave me '${foo}'`);
+}
+
+ +
You gave me 'Hello!'
+
+
+
+
foo = 'Hello!'
+case foo
+when 1..5
+  puts "It's between 1 and 5"
+when 10, 20
+  puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+  puts "You passed a string '#{foo}'"
+else
+  puts "You gave me '#{foo}'"
+end
+
+ +
You passed a string 'Hello!'
+
+
+
+

+Switch as else if + + + + + +

+
+
+No easy way to do that +
+
+
score = 76
+grade = case
+        when score < 60 then 'F'
+        when score < 70 then 'D'
+        when score < 80 then 'C'
+        when score < 90 then 'B'
+        else 'A'
+        end
+puts grade
+
+ +
C
+
+
+
+

+Ternary + + + + + +

+
+
+
console.log(false ? 'no' : 'yes');
+
+ +
yes
+
+
+
+
puts false ? 'no' : 'yes'
+
+ +
yes
+
+
+
+

+If assign + + + + + +

+
+
+No easy way to do that +
+
+
result =
+if true
+  'a'
+else
+  'b'
+end
+puts result
+
+
+ +
a
+
+
+
+

Loop

+

+For + + + + + +

+
+
+
for (let i = 1; i < 4; i++)
+  console.log(`${i}. Hi`);
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+
(1..3).each do |i|
+  puts "#{i}. Hi"
+end
+
+ +
1. Hi
+2. Hi
+3. Hi
+
+
+
+

+For with a step + + + + + +

+
+
+
for (let i = 0; i < 6; i += 2) {
+  console.log(i);
+}
+
+ +
0
+2
+4
+
+
+
+
(0..4).step(2) do |i|
+  puts i
+end
+
+ +
0
+2
+4
+
+
+
+

+Times + + + + + +

+
+
+
for (let i of Array(3).keys()) {
+  console.log('Hi');
+}
+
+ +
Hi
+Hi
+Hi
+
+
+
+
3.times do
+  puts 'Hi'
+end
+
+ +
Hi
+Hi
+Hi
+
+
+
+

+While + + + + + +

+
+
+
let i = 0;
+while (i < 3)
+  i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
i = 0
+while i < 3
+  i += 1
+end
+puts i
+
+ +
3
+
+
+
+

+Until + + + + + +

+
+
+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+ +
3
+
+
+
+
i = 0
+i += 1 until i == 3
+puts i
+
+ +
3
+
+
+
+

+Return array + + + + + +

+
+
+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+ +
[ '1. Hello!', '2. Hello!', '3. Hello!' ]
+
+
+
+
greetings = Array.new(3) do |i|
+  "#{i + 1}. Hello!"
+end
+puts greetings
+
+ +
1. Hello!
+2. Hello!
+3. Hello!
+
+
+
+

+Break + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  console.log(`${i + 1}. Hi`);
+  if (i === 1) break;
+}
+
+ +
1. Hi
+2. Hi
+
+
+
+
3.times do |time|
+  puts "#{time + 1}. Hi"
+  break if time == 1
+end
+
+ +
1. Hi
+2. Hi
+
+
+
+

+Next/Continue + + + + + +

+
+
+
for (let i = 0; i < 3; i++) {
+  if (i === 1) continue;
+  console.log(`${i + 1}. Hi`);
+}
+
+ +
1. Hi
+3. Hi
+
+
+
+
3.times do |time|
+  next if time == 1
+  puts "#{time + 1}. Hi"
+end
+
+ +
1. Hi
+3. Hi
+
+
+
+

Math

+

+Max/Min + + + + + +

+
+
+
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+ +
1
+3
+
+
+
+
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+ +
1
+3
+
+
+
+

+Sqrt + + + + + +

+
+
+
console.log(Math.sqrt(9));
+
+ +
3
+
+
+
+
puts Math.sqrt(9)
+
+ +
3.0
+
+
+
+

Error handling

+

+Try/catch/finally + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log("Can't change undefined variable");
+} finally {
+  console.log("But that's ok");
+}
+
+ +
Can't change undefined variable
+But that's ok
+
+
+
+
begin
+  1 / 0
+rescue
+  puts "Can't divide"
+ensure
+  puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+ +
Can't divide
+But that's ok
+Can't divide
+
+
+
+

+With a message + + + + + +

+
+
+
try {
+  age++;
+} catch (error) {
+  console.log(error.message);
+}
+
+ +
age is not defined
+
+
+
+
begin
+  1 / 0
+rescue => e
+  puts e.message
+end
+
+ +
divided by 0
+
+
+
+

+Method + + + + + +

+
+
+No easy way to do that +
+
+
def divide(num1, num2)
+  num1 / num2
+rescue => e
+  puts e.message
+end
+divide(1, 0)
+
+ +
divided by 0
+
+
+
+

+Throw exception + + + + + +

+
+
+
try {
+  throw new Error('An error!');
+} catch (e) {
+  console.log(e.message);
+}
+
+ +
An error!
+
+
+
+
begin
+  fail 'An error!'
+rescue => e
+  puts e.message
+end
+
+ +
An error!
+
+
+
+

File

+

+Read + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+ +
Hello
+World
+
+
+
+
+
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+ +
Hello
+World
+
+
+
+

+Write + + + + + +

+
+
+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+ +
node:internal/validators:440
+    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
+    ^
+
+TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
+    at maybeCallback (node:fs:189:3)
+    at Object.writeFile (node:fs:2266:14)
+    at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4)
+    at Module._compile (node:internal/modules/cjs/loader:1256:14)
+    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
+    at Module.load (node:internal/modules/cjs/loader:1119:32)
+    at Module._load (node:internal/modules/cjs/loader:960:12)
+    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
+    at node:internal/main/run_main_module:23:47 {
+  code: 'ERR_INVALID_ARG_TYPE'
+}
+
+Node.js v18.17.0
+
+
+
+
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+ +

+
+
+

+Get working dir path + + + + + +

+
+
+
console.log(process.cwd());
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+
puts Dir.getwd
+
+ +
/Users/evmorov/projects/lang-compare
+
+
+
+

+File path + + + + + +

+
+
+
console.log(__filename);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript/file-path.js
+
+
+
+
puts __FILE__
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb
+
+
+
+

+Dir path + + + + + +

+
+
+
console.log(__dirname);
+
+ +
/Users/evmorov/projects/lang-compare/code/javascript
+
+
+
+
puts File.dirname(__FILE__)
+
+ +
/Users/evmorov/projects/lang-compare/code/ruby
+
+
+
+

+Parent dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+
puts File.expand_path File.join(__FILE__, '..', '..')
+
+ +
/Users/evmorov/projects/lang-compare/code
+
+
+
+

+Sister dir path + + + + + +

+
+
+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+ +
/Users/evmorov/projects/lang-compare/code/python
+
+
+
+
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+ +
/Users/evmorov/projects/lang-compare/code/php
+
+
+
+

Method

+

+Declare + + + + + +

+
+
+
function hey() {
+  console.log('How are you?');
+}
+hey();
+
+ +
How are you?
+
+
+
+
def hey
+  puts 'How are you?'
+end
+hey
+
+ +
How are you?
+
+
+
+

+Multiple arguments + + + + + +

+
+
+
function sweets(buy, ...brands) {
+  if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+ +
[ 'snickers', 'twix', 'bounty' ]
+
+
+
+
def sweets(buy, *brands)
+  puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+ +
snickers
+twix
+bounty
+
+
+
+

+Default value for argument + + + + + +

+
+
+
function send(abroad = false) {
+  console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+ +
Send locally
+Send abroad
+
+
+
+
def send(abroad = false)
+  puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+ +
Send locally
+Send abroad
+
+
+
+

+Return + + + + + +

+
+
+
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+  if (a === 0) return 0;
+  return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+ +
6
+0
+undefined
+
+
+
+
def multiple(a, b)
+  a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+  return 0 if a == 0
+  a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+ +
6
+0
+nil
+
+
+
+

+Closure + + + + + +

+
+
+
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+ +
[ 4, 9 ]
+Hello World!
+
+
+
+
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+ +
4
+9
+Hello World!
+
+
+
+

+Block passing + + + + + +

+
+
+
function mySelect(arr, filter) {
+  const selected = [];
+  arr.forEach(e => {
+    if (filter(e)) selected.push(e);
+  });
+  return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+ +
[ 1, 5 ]
+
+
+
+
def my_select(arr)
+  selected = []
+  arr.each do |a|
+    selected.push a if yield(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+  selected = []
+  arr.each do |a|
+    selected.push a if filter.call(a)
+  end
+  selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+ +
1
+5
+1
+5
+
+
+
+

+Block binding + + + + + +

+
+
+
class Action {
+  static say(sentence) {
+    console.log(sentence());
+  }
+}
+
+class Person {
+  constructor(name) {
+    this.name = name;
+  }
+
+  greet() {
+    try {
+      Action.say(function() { `My name is ${this.name}!`; });
+    } catch (err) {
+      console.log(err.message);
+    }
+    Action.say(() => `My name is ${this.name}!`);
+  }
+}
+
+new Person('Alex').greet();
+
+ +
Cannot read properties of undefined (reading 'name')
+My name is Alex!
+
+
+
+
class Action
+  def self.say(&sentence)
+    @name = 'Ann'
+    puts sentence.call
+  end
+end
+
+class Person
+  def initialize(name)
+    @name = name
+  end
+
+  def greet
+    Action.say { "My name is #{@name}!" }
+  end
+end
+
+Person.new('Alex').greet
+
+ +
My name is Alex!
+
+
+
+

+Initialize in runtime + + + + + +

+
+
+No easy way to do that +
+
+
class ProccessElements
+  def self.element(el_name)
+    define_method "#{el_name}_element" do |content|
+      "<#{el_name}>#{content}</#{el_name}>"
+    end
+  end
+end
+
+class HtmlELements < ProccessElements
+  element :div
+  element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+ +
<div>hello</div>
+
+
+
+

+Alias + + + + + +

+
+
+
class Greetings {
+  constructor() {
+    this.hi = this.hey.bind(this, true);
+  }
+
+  hey() {
+    console.log('How are you?');
+  }
+}
+
+new Greetings().hi();
+
+ +
How are you?
+
+
+
+
class Greetings
+  def hey
+    puts 'How are you?'
+  end
+  alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+ +
How are you?
+
+
+
+

Class

+

+Declare + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+new Animal().walk();
+
+ +
I'm walking
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+Animal.new.walk
+
+ +
I'm walking
+
+
+
+

+Constructor + + + + + +

+
+
+
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  walk() {
+    console.log(`My name is ${this.name} and I'm walking`);
+  }
+}
+
+new Animal('Kelya').walk();
+
+ +
My name is Kelya and I'm walking
+
+
+
+
class Animal
+  def initialize(name)
+    @name = name
+  end
+
+  def walk
+    puts "My name is #{@name} and I'm walking"
+  end
+end
+
+Animal.new('Kelya').walk
+
+ +
My name is Kelya and I'm walking
+
+
+
+

+Method call + + + + + +

+
+
+
class Animal {
+  walk() {
+    this.bark();
+    console.log("I'm walking");
+  }
+
+  bark() {
+    console.log('Wuf!');
+  }
+}
+
+new Animal().walk();
+
+ +
Wuf!
+I'm walking
+
+
+
+
class Animal
+  def walk
+    bark
+    guard
+    puts "I'm walking"
+  end
+
+  def bark
+    puts 'Wuf!'
+  end
+
+  private
+
+  def guard
+    puts 'WUUUF!'
+  end
+end
+
+Animal.new.walk
+
+ +
Wuf!
+WUUUF!
+I'm walking
+
+
+
+

+Class method + + + + + +

+
+
+
class Animal {
+  static feed() {
+    console.log('Om nom nom');
+  }
+}
+
+Animal.feed();
+
+ +
Om nom nom
+
+
+
+
class Animal
+  def self.feed
+    puts 'Om nom nom'
+  end
+end
+
+Animal.feed
+
+ +
Om nom nom
+
+
+
+

+Private method + + + + + +

+
+
+No easy way to do that +
+
+
class Animal
+  def eat(food)
+    puts 'Om nom nom' if meat? food
+  end
+
+  private
+
+  def meat?(food)
+    food == 'meat'
+  end
+end
+
+Animal.new.eat('meat')
+
+ +
Om nom nom
+
+
+
+

+Private method, access instance variable + + + + + +

+
+
+No easy way to do that +
+
+
class Animal
+  def initialize(name)
+    @name = name
+    greet
+  end
+
+  private
+
+  def greet
+    puts "Hello! My name is #{@name}"
+  end
+end
+
+Animal.new('Kelya')
+
+ +
Hello! My name is Kelya
+
+
+
+

+Field + + + + + +

+
+
+
class Animal {
+  take(toy) {
+    this.toy = toy;
+  }
+
+  play() {
+    console.log(`I'm playing with ${this.toy}`);
+  }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+ +
I'm playing with a ball
+
+
+
+
class Animal
+  def take(toy)
+    @toy = toy
+  end
+
+  def play
+    puts "I'm playing with #{@toy}"
+  end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+ +
I'm playing with a ball
+
+
+
+

+Get/set + + + + + +

+
+
+
class Animal {
+  setName(name) {
+    this.name = name;
+  }
+
+  getName() {
+    return this.name;
+  }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+ +
Kelya
+
+
+
+
class Animal
+  attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+ +
Kelya
+
+
+
+

+Inheritance + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+class Dog extends Animal {
+  sing() {
+    console.log('Bark!');
+  }
+}
+
+new Dog().walk();
+
+ +
I'm walking
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+class Dog < Animal
+  def sing
+    puts 'Bark!'
+  end
+end
+
+Dog.new.walk
+
+ +
I'm walking
+
+
+
+

+Mixin + + + + + +

+
+
+No easy way to do that +
+
+
module Moving
+  def walk
+    puts "#{self.class.name} is walking"
+  end
+end
+
+module Interacting
+  def talk
+    puts "#{self.class.name} is talking"
+  end
+end
+
+class Human
+  include Moving
+  include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+ +
Human is walking
+Human is talking
+
+
+
+

+Has method? + + + + + +

+
+
+
class Animal {
+  walk() {
+    console.log("I'm walking");
+  }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+ +
true
+
+
+
+
class Animal
+  def walk
+    puts "I'm walking"
+  end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+ +
true
+
+
+
+

Other

+

+Comment + + + + + +

+
+
+
// it's a comment
+
+ +

+
+
+
# it's a comment
+
+ +

+
+
+

+Assign value if not exist + + + + + +

+
+
+No easy way to do that +
+
+
speed = 0
+speed ||= 15
+puts speed
+
+ +
0
+
+
+
+

+Safe navigation + + + + + +

+
+
+No easy way to do that +
+
+[ 2.3 ]
class Winner
+  attr_reader :address
+
+  def initialize
+    # @address = Address.new
+  end
+end
+
+class Address
+  attr_reader :zipcode
+
+  def initialize
+    @zipcode = 192187
+  end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+ +
No prize without zipcode
+
+
+
+

+Import another file + + + + + +

+
+
+
// other-file-to-import.js
+// module.exports =
+// class Import {
+//   constructor() {
+//     console.log('I am imported!');
+//   }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+ +
I am imported!
+
+
+
+
# other_file_to_import.rb
+# class Import
+#   def initialize
+#     puts 'I am imported!'
+#   end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+ +
I am imported!
+
+
+
+

+Destructuring assignment + + + + + +

+
+
+
const [one, two] = [1, 2];
+console.log(one, two);
+
+ +
1 2
+
+
+
+
one, two = [1, 2]
+puts one, two
+
+ +
1
+2
+
+
+
+

+Date + + + + + +

+
+
+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date =  `${year}-${month}-${day}`;
+console.log(date);
+
+ +
2024-5-28
+
+
+
+
require 'date'
+puts Date.today
+
+ +
2024-05-28
+
+
+
+

+Time + + + + + +

+
+
+
console.log(new Date());
+
+ +
2024-05-28T18:17:39.286Z
+
+
+
+
puts Time.now
+
+ +
2024-05-28 20:17:54 +0200
+
+
+
+

+Not + + + + + +

+
+
+
const angry = false;
+if (!angry) console.log('smile!');
+
+ +
smile!
+
+
+
+
angry = false
+puts 'smile!' if !angry
+
+ +
smile!
+
+
+
+

+Assign this or that + + + + + +

+
+
+No easy way to do that +
+
+
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+ +
bear
+
+
+
+

+Run command + + + + + +

+
+
+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+ +
v18.17.0
+
+
+
+
+
puts `ruby -v`
+
+ +
ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21]
+
+
+
+
+ + + + + + + + + + diff --git a/javascripts/all-091923e6.js b/javascripts/all-091923e6.js new file mode 100644 index 0000000..048b86c --- /dev/null +++ b/javascripts/all-091923e6.js @@ -0,0 +1,111 @@ +/*! + * jQuery JavaScript Library v1.11.2 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-17T15:27Z + */ +!function(t,e){"object"==typeof module&&"object"==typeof module.exports?module.exports=t.document?e(t,!0):function(t){if(!t.document)throw new Error("jQuery requires a window with a document");return e(t)}:e(t)}("undefined"!=typeof window?window:this,function(t,e){function n(t){var e=t.length,n=ot.type(t);return"function"===n||ot.isWindow(t)?!1:1===t.nodeType&&e?!0:"array"===n||0===e||"number"==typeof e&&e>0&&e-1 in t}function i(t,e,n){if(ot.isFunction(e))return ot.grep(t,function(t,i){return!!e.call(t,i,t)!==n});if(e.nodeType)return ot.grep(t,function(t){return t===e!==n});if("string"==typeof e){if(pt.test(e))return ot.filter(e,t,n);e=ot.filter(e,t)}return ot.grep(t,function(t){return ot.inArray(t,e)>=0!==n})}function o(t,e){do t=t[e];while(t&&1!==t.nodeType);return t}function r(t){var e=xt[t]={};return ot.each(t.match(bt)||[],function(t,n){e[n]=!0}),e}function s(){ht.addEventListener?(ht.removeEventListener("DOMContentLoaded",a,!1),t.removeEventListener("load",a,!1)):(ht.detachEvent("onreadystatechange",a),t.detachEvent("onload",a))}function a(){(ht.addEventListener||"load"===event.type||"complete"===ht.readyState)&&(s(),ot.ready())}function l(t,e,n){if(void 0===n&&1===t.nodeType){var i="data-"+e.replace(Nt,"-$1").toLowerCase();if(n=t.getAttribute(i),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Et.test(n)?ot.parseJSON(n):n}catch(o){}ot.data(t,e,n)}else n=void 0}return n}function c(t){var e;for(e in t)if(("data"!==e||!ot.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}function u(t,e,n,i){if(ot.acceptData(t)){var o,r,s=ot.expando,a=t.nodeType,l=a?ot.cache:t,c=a?t[s]:t[s]&&s;if(c&&l[c]&&(i||l[c].data)||void 0!==n||"string"!=typeof e)return c||(c=a?t[s]=Q.pop()||ot.guid++:s),l[c]||(l[c]=a?{}:{toJSON:ot.noop}),"object"!=typeof e&&"function"!=typeof e||(i?l[c]=ot.extend(l[c],e):l[c].data=ot.extend(l[c].data,e)),r=l[c],i||(r.data||(r.data={}),r=r.data),void 0!==n&&(r[ot.camelCase(e)]=n),"string"==typeof e?(o=r[e],null==o&&(o=r[ot.camelCase(e)])):o=r,o}}function d(t,e,n){if(ot.acceptData(t)){var i,o,r=t.nodeType,s=r?ot.cache:t,a=r?t[ot.expando]:ot.expando;if(s[a]){if(e&&(i=n?s[a]:s[a].data)){ot.isArray(e)?e=e.concat(ot.map(e,ot.camelCase)):e in i?e=[e]:(e=ot.camelCase(e),e=e in i?[e]:e.split(" ")),o=e.length;for(;o--;)delete i[e[o]];if(n?!c(i):!ot.isEmptyObject(i))return}(n||(delete s[a].data,c(s[a])))&&(r?ot.cleanData([t],!0):nt.deleteExpando||s!=s.window?delete s[a]:s[a]=null)}}}function p(){return!0}function f(){return!1}function h(){try{return ht.activeElement}catch(t){}}function g(t){var e=Rt.split("|"),n=t.createDocumentFragment();if(n.createElement)for(;e.length;)n.createElement(e.pop());return n}function m(t,e){var n,i,o=0,r=typeof t.getElementsByTagName!==Ct?t.getElementsByTagName(e||"*"):typeof t.querySelectorAll!==Ct?t.querySelectorAll(e||"*"):void 0;if(!r)for(r=[],n=t.childNodes||t;null!=(i=n[o]);o++)!e||ot.nodeName(i,e)?r.push(i):ot.merge(r,m(i,e));return void 0===e||e&&ot.nodeName(t,e)?ot.merge([t],r):r}function v(t){At.test(t.type)&&(t.defaultChecked=t.checked)}function y(t,e){return ot.nodeName(t,"table")&&ot.nodeName(11!==e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function b(t){return t.type=(null!==ot.find.attr(t,"type"))+"/"+t.type,t}function x(t){var e=Vt.exec(t.type);return e?t.type=e[1]:t.removeAttribute("type"),t}function w(t,e){for(var n,i=0;null!=(n=t[i]);i++)ot._data(n,"globalEval",!e||ot._data(e[i],"globalEval"))}function T(t,e){if(1===e.nodeType&&ot.hasData(t)){var n,i,o,r=ot._data(t),s=ot._data(e,r),a=r.events;if(a){delete s.handle,s.events={};for(n in a)for(i=0,o=a[n].length;o>i;i++)ot.event.add(e,n,a[n][i])}s.data&&(s.data=ot.extend({},s.data))}}function C(t,e){var n,i,o;if(1===e.nodeType){if(n=e.nodeName.toLowerCase(),!nt.noCloneEvent&&e[ot.expando]){o=ot._data(e);for(i in o.events)ot.removeEvent(e,i,o.handle);e.removeAttribute(ot.expando)}"script"===n&&e.text!==t.text?(b(e).text=t.text,x(e)):"object"===n?(e.parentNode&&(e.outerHTML=t.outerHTML),nt.html5Clone&&t.innerHTML&&!ot.trim(e.innerHTML)&&(e.innerHTML=t.innerHTML)):"input"===n&&At.test(t.type)?(e.defaultChecked=e.checked=t.checked,e.value!==t.value&&(e.value=t.value)):"option"===n?e.defaultSelected=e.selected=t.defaultSelected:"input"!==n&&"textarea"!==n||(e.defaultValue=t.defaultValue)}}function E(e,n){var i,o=ot(n.createElement(e)).appendTo(n.body),r=t.getDefaultComputedStyle&&(i=t.getDefaultComputedStyle(o[0]))?i.display:ot.css(o[0],"display");return o.detach(),r}function N(t){var e=ht,n=Zt[t];return n||(n=E(t,e),"none"!==n&&n||(Kt=(Kt||ot("