Newsletter – Week 14, 2021

News:

Articles:

Videos:

Rust & Keywords

This is my first article about the Rust programming language, so I wanted to make it a little bit funny and interesting at the same time.

There are lots of great technical articles about Rust, but today we will
talk about the keywords defined in Rust and languages that influenced the Rust creation.

Rust keywords

as, async, await, break, const, continue, crate, dyn, else, enum, extern, false, fn, for, if, impl, in, let, loop, match, mod, move, mut, pub, ref, return, Self, self, static, struct, super, trait, true, type, union, unsafe, use, where, while, abstract, become, box, do, final, macro, override, priv, try, typeof, unsized, virtual, yield

Following Wikipedia there are languages that influenced Rust the most.

Rust was influenced by

Alef,C#, C++, Cyclone, Erlang, Haskell, Limbo, Newsqueak, OCaml, Ruby, Scheme, Standard ML, Swift

So, idea is to compare keywords defined in Rust with the keywords defined in “parent” languages and see the match rate and figure out the most “valuable” language. If you are interested you can find all keywords by languages mentioned in the article below.

All comparison result represents in the table, but we can make them more visual.

Keywords comparison table

“Parents” pie chart

“Parents” radar chart

As Java developer I had to include Java in comparison as well, so here we go.

“Parents” pie chart + Java

“Parents” radar chart + Java

Based on chart above and some observations gathered during comparison there are some fun facts:

  • C# and Swift most influences on Rust development and most critical “parents” of this language.
  • Erlang is still an important but less valuable “parent” for the Rust.
  • Rust’s keywords “self” and “Self” must be coming from Swift as this pair presents only there when “self” itself could be found in Swift, Ruby, and Limbo.
  • Even if Java and Rust share some common pieces there is not influence Java on Rust creation and development
  • There is no “goto” in Rust which everybody should avoid in Alef, C#, C++, Java.
  • Rust doesn’t have “new” present in C#, C++, OCaml, Java.
  • There is no “this” and “void” in Rust which you know by C#, C++, and Java
  • Rust’s “fn” highly possible goes from Limbo because only Limbo has the same keyword.
  • Rust’s “macro” must be going from Schema when “match” and “mod’ from OCaml.
  • Cyclone, Newsqueak, Standard ML are missed in analysis because it is quite difficult to find keywords for them.

Title image by Free-Photos from Pixabay


Alef keywords

adt, aggr, alloc, alt, become, break, byte, case, chan, check, continue, default, do, else, enum, extern, float, for, goto, if, int, intern, lint, nil, par, proc, raise, rescue, return, sint, sizeof, switch, task, tuple, typedef, typeof, uint, ulint, unalloc, union, usint, void, while, zerox

C# keywords

abstract, as, base, bool, break, byte, case, catch, char, checked, class, const, continue, decimal, default, delegate, do, double, else, enum, event, explicit, extern, false, finally, fixed, float, for, foreach, goto, if, implicit, in, int, interface, internal, is, lock, long, namespace, new, null, object, operator, out, override, params, private, protected, public, readonly, ref, return, sbyte, sealed, short, sizeof, stackalloc, static, string, struct, switch, this, throw, true, try, typeof, uint, ulong, unchecked, unsafe, ushort, using, virtual, void, volatile, while, add, and, alias, ascending, async, await, by, descending, dynamic, equals, from, get, global, group, init, into, join, let, nameof, nint, not, notnull, nuint, on, or, orderby, partial, record, remove, select, set, unmanaged, value, var, when, where, with, yield

C++ keywords

alignas, alignof, and, and_eq, asm, atomic_cancel, atomic_commit, atomic_noexcept, auto, bitand, bitor, bool, break, case, catch, char, char8_t, char16_t, char32_t, class, compl, concept, const, consteval, constexpr, constinit, const_cast, continue, co_await, co_return, co_yield, decltype, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, reflexpr, register, reinterpret_cast, requires, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch, synchronized, template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq

Erlang keywords

after, and, andalso, band, begin, bnot, bor, bsl, bsr, bxor, case, catch, cond, div, end, fun, if, let, not, of, or, orelse, query, receive, rem, try, when, xor

Haskell keywords

!, ', '', -, --, -<, -<<, ->, ::, ;, <-, ,, =, =>, >, ?, #, *, @, [|, |], \, _, `, {, }, {-, -}, |, ~, as, case, of, class, data, data family, data instance, default, deriving, deriving instance, do, forall, foreign, hiding, if, then, else, import, infix, infixl, infixr, instance, let, in, mdo, module, newtype, proc, qualified, rec, type, type family, type instance, where

Limbo keywords

adt, alt, array, big, break, byte, case, chan, con, continue, cyclic, do, else, exit, fn, for, hd, if, implement, import, include, int, len, list, load, module, nil, of, or, pick, real, ref, return, self, spawn, string, tagof, tl, to, type, while

OCaml keywords

and, as, assert, asr, begin, class, constraint, do, done, downto, else, end, exception, external, false, for, fun, function, functor, if, in, include, inherit, initializer, land, lazy, let, lor, lsl, lsr, lxor, match, method, mod, module, mutable, new, nonrec, object, of, open, or, private, rec, sig, struct, then, to, true, try, type, val, virtual, when, while, with

Ruby keywords

alias, and, begin, break, case, class, def, defined?, do, else, elsif, end, ensure, false, for, if, in, module, next, nil, not, or, redo, rescue, retry, return, self, super, then, true, undef, unless, until, when, while, yield

Schema keywords

access, define-syntax, macro, and, delay, make-environment, begin, do, named-lambda, bkpt, fluid-let, or, case, if, quasiquote, cond, in-package, quote, cons-stream, lambda, scode-quote, declare, let, sequence, default-object?, let*, set!, define, let-syntax, the-environment, define-integrable, letrec, unassigned?, define-macro, local-declare, using-syntax, define-structure

Swift keywords

associatedtype, class, deinit, enum, extension, func, import, init, inout, internal, let, operator, private, protocol, public, static, struct, subscript, typealias, var, break, case, continue, default, defer, do, else, fallthrough, for, guard, if, in, repeat, return, switch, where, while, as, catch, dynamicType, false, is, nil, rethrows, super, self, Self, throw, throws, true, try, #column, #file, #function, #line, #available, #column, #else#elseif, #endif, #file, #function, #if, #line, #selector, associativity, convenience, dynamic, didSet, final, get, infix, indirect, lazy, left, mutating, none, nonmutating, optional, override, postfix, precedence, prefix, Protocol, required, right, set, Type, unowned, weak, willSet

Java keywords

abstract, continue, for, new, switch, assert, default, goto, package, synchronized, boolean, do, if, private, this, break, double, implements, protected, throw, byte, else, import, public, throws, case, enum, instanceof, return, transient, catch, extends, int, short, try, char, final, interface, static, void, class, finally, long, strictfp, volatile, const, float, native, super, while

Newsletter – Week 13, 2021

News:

Articles:

Videos:

Newsletter – Week 12, 2021

News:

Articles:

Videos:

Newsletter – Week 11, 2021

News:

Articles:

Videos:

Newsletter – Week 10, 2021

News:

Articles:

Videos:

Autoboxing & Unboxing

Today I’m going to discuss quite an interesting topic of autoboxing and unboxing in Java. Let’s remind what it is exactly.

Autoboxing – automatic conversion of primitive type to corresponding object wrapped class in Java.

Unboxing – automated conversion of wrapped class to corresponding primitive type.

Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble
nullnull

In the example below, we can see examples of autoboxing and unboxing at the same time.

public class Test{
  public static void main(String[] args){
    Integer a = 12; //autoboxing
    int b = a; //unboxing
  }
}

Let’s compile it

javac Test.java

and disassemble to see what is under the hood there

javap -c Test.class
public class Test {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: bipush        12
       2: invokestatic  #7                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #13                 // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: return
}

So, the compiler just transformed previous example into this form

public class Test{
  public static void main(String[] args){
    Integer a = Integer.valueOf(12);
    int b = a.intValue();
  }
}

The same rule applies for all other types

AutoboxingUnboxing
Boolean Boolean.valueOf(boolean val)boolean Boolean.booleanValue()
Byte Byte.valueOf(byte val)byte Byte.byteValue()
Character Character.valueOf(char val)char Character.charValue()
Float Float.valueOf(float val)float Float.floatValue()
Integer Integer.valueOf(int val)int Integer.intValue()
Long Long.valueOf(long val)long Long.longValue()
Short Short.valueOf(short val)short Short.shortValue()
Double Double.valueOf(double val)double Double.doubleValue()

Pretty easy – you can say and would be right, but let me ask you some questions.

Q: In the code below for the section a == b will it Autoboxing or Unboxing?

public class Test{
  public static void main(String[] args){
    Boolean a = true;
    boolean b = false;
   
    boolean c = a == b;
  }
}

A: Unboxing is the right answer.

Disassembled code as proof below

public class Test {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_1
       1: invokestatic  #7                  // Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
       4: astore_1
       5: iconst_0
       6: istore_2
       7: iload_2
       8: aload_1
       9: invokevirtual #13                 // Method java/lang/Boolean.booleanValue:()Z
      12: if_icmpne     19
      15: iconst_1
      16: goto          20
      19: iconst_0
      20: istore_3
      21: return
}

Now, when we covered previous example this question should be easy for you.

Q: What value will be assigned to variable b in the code below?

public class Test{
  public static void main(String[] args){
    Boolean a = null;
    boolean b = a;
  }
}

A: no value will be assigned to b due to exception during execution.

Exception in thread "main" java.lang.NullPointerException
	at Test.main(Test.java:4)

Code in the question is equal to this one

public class Test{
  public static void main(String[] args){
    Boolean a = null;
    boolean b = a.booleanValue(); //null.booleanValue()
  }
}

Q: What value will be assigned to variable c in the example below?

public class Test{
  public static void main(String[] args){
    Long a = 20L;
    long b = 20;
    boolean c = a.equals(b);
  }
}

A: the correct answer – true.

public class Test {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #7                  // long 20l
       3: invokestatic  #9                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       6: astore_1
       7: ldc2_w        #7                  // long 20l
      10: lstore_2
      11: aload_1
      12: lload_2
      13: invokestatic  #9                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
      16: invokevirtual #15                 // Method java/lang/Long.equals:(Ljava/lang/Object;)Z
      19: istore        4
      21: return
}

which is the same as

public class Test{
  public static void main(String[] args){
    Long a = 20L;
    long b = 20;
    boolean c = a.equals(Long.valueOf(b));
  }
}

Q: What value will be assigned to variable c in the example below?

public class Test{
  public static void main(String[] args){
    Long a = 20L;
    boolean c = a.equals(20);
  }
}

A: the correct answer – false.

public class Test {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #7                  // long 20l
       3: invokestatic  #9                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       6: astore_1
       7: aload_1
       8: bipush        20
      10: invokestatic  #15                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      13: invokevirtual #20                 // Method java/lang/Long.equals:(Ljava/lang/Object;)Z
      16: istore_2
      17: return
}

In this example there is no type reference so 20 is represented as most appropriate integer type.

public class Test{
  public static void main(String[] args){
    Long a = 20L;
    boolean c = a.equals(Integer.valueOf(20));
  }
}

So, even if autoboxing/unboxing logic seems pretty straightforward and easy you still need to keep attention to details. As best practice to avoid memory and/or performance-related issues you shouldn’t rely on the autoboxing/unboxing mechanism in your code. The most appropriate case when this mechanism is really needed is when you store primitive types in the collection.

Photo by Ante Hamersmit on Unsplash

Newsletter – Week 09, 2021

News:

Articles:

Videos:

Newsletter – Week 08, 2021

News:

Articles:

Videos: