{"id":1856,"date":"2017-05-03T00:00:00","date_gmt":"2017-05-02T22:00:00","guid":{"rendered":"https:\/\/wwwneu.strehle.de\/tim\/weblog\/archives\/2017\/05\/03\/1616-2\/"},"modified":"2025-07-31T21:51:38","modified_gmt":"2025-07-31T19:51:38","slug":"1616-2","status":"publish","type":"post","link":"https:\/\/www.strehle.de\/tim\/weblog\/archives\/2017\/05\/03\/1616-2\/","title":{"rendered":"Learning Java coming from PHP (1)"},"content":{"rendered":"\n<p>Despite my almost 20 years of professional software development, I haven\u2019t learnt a lot of programming languages (see <a href=\"\/tim\/weblog\/archives\/2013\/03\/07\/1568\">my honest r\u00e9sum\u00e9<\/a>). So far, it\u2019s just been PHP and JavaScript (plus SQL, XSLT, and \u2013 back in the day \u2013 Object Pascal and Visual Basic).<\/p>\n\n\n\n<p>Now I\u2019m trying to teach myself some Java. This blog post lists differences between PHP and Java, from the perspective of a PHP developer just getting started with Java. (Please let me know if I got something wrong!)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Running \u201cHello World\u201d<\/h3>\n\n\n\n<p>In PHP, you create a <code>hello.php<\/code> file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\necho \"Hello World\\n\";\n<\/code><\/pre>\n\n\n\n<p>\u2026 and simply run it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ php hello.php\n<\/code><\/pre>\n\n\n\n<p>In Java, almost everything is an object \u2013 even \u201cHello World\u201d requires defining a class with a <code>main()<\/code> method. Here\u2019s a <code>hello.java<\/code> file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class HelloWorld {\n  public static void main(String args&#91;]) { \n    System.out.println(\"Hello World\"); \n  } \n}\n<\/code><\/pre>\n\n\n\n<p>And you need to run it in two steps:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ javac hello.java &amp;&amp; java HelloWorld\n<\/code><\/pre>\n\n\n\n<p>Java code must be compiled to bytecode first. That\u2019s what the <code>javac<\/code> invocation does, creating a <code>.class<\/code> file for each class definition. The <code>java<\/code> command runs the main classes\u2019 file. (You should name the <code>.java<\/code> file after the class \u2013 I didn\u2019t do this to make that point.)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Variables<\/h3>\n\n\n\n<p>In PHP, variable names always start with <code>$<\/code>, and you don\u2019t declare a type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$num = 5;\n<\/code><\/pre>\n\n\n\n<p>No dollar signs required in Java, but the type is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int num = 5;\n<\/code><\/pre>\n\n\n\n<p>As a side effect, Java variable names can collide with reserved keywords. <code>$default = 1<\/code> is fine in PHP, <code>int default = 1<\/code> isn\u2019t in Java.<\/p>\n\n\n\n<p><strong>Variable scope<\/strong>: PHP variables are available in the whole function regardless of how deeply nested they were declared:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for ($i = 0; $i &lt; 10; $i++) { }\necho \"i is $i\\n\"; \/\/ \"i is 10\"\n<\/code><\/pre>\n\n\n\n<p>Java uses block scope instead, i.e. variables only exist within the block they\u2019re defined in:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (int i = 0; i &lt; 10; i++) { }\nSystem.out.println(\"i is \" + i); \/\/ compile error, i undefined\n<\/code><\/pre>\n\n\n\n<p>In PHP, all non-object variables (including arrays) are <strong>passed by value<\/strong> into methods, unless you prepend <code>&amp;<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function changeMe($str, &amp;$i, $ints) {\n&nbsp; $str = \"bye\";\n&nbsp; $i = 99;\n&nbsp; $ints&#91;0]=99;\n}\n\n$str = \"hello\";\n$i = 42;\n$ints = &#91;42];\n\nchangeMe($str, $i, $ints);\n\necho $str . \"\\n\"; \/\/ hello\necho $i . \"\\n\"; \/\/ 99\necho $ints&#91;0] . \"\\n\"; \/\/ 42\n<\/code><\/pre>\n\n\n\n<p>Java passes all primitive types (int, double, char) and immutable objects (String, Integer, Double) by value. There\u2019s no way to change that. Arrays are passed by reference since they\u2019re objects. Example code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static void changeMe(String str, Integer i, int&#91;] ints) {\n&nbsp; str = \"bye\";\n&nbsp; i = 99;\n&nbsp; ints&#91;0]=99;\n}\n\nString str = \"hello\";\nInteger i = 42;\nint&#91;] ints = {42};\n\nchangeMe(str, i, ints);\n\nSystem.out.println(str); \/\/ hello\nSystem.out.println(i); \/\/ 42\nSystem.out.println(ints&#91;0]); \/\/ 99\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Numbers<\/h3>\n\n\n\n<p>Java\u2019s numeric type behaviour seems a bit weird initially. This division works as expected in PHP:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$num = 5 \/ 2; \/\/ $num is now 2.5\n<\/code><\/pre>\n\n\n\n<p>The result gets truncated in Java because 5 is an <code>int<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int num = 5 \/ 2; \/\/ num is now 2\n<\/code><\/pre>\n\n\n\n<p>That\u2019s why it doesn\u2019t help to try storing the result in a <code>double<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>double num = 5 \/ 2; \/\/ num is now 2.0\n<\/code><\/pre>\n\n\n\n<p>Now it works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>double num = 5.0 \/ 2; \/\/ num is now 2.5\n<\/code><\/pre>\n\n\n\n<p>At least this code produces a compilation error \u201cpossible loss of precision\u201d:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>double a = 5, b = 2;\nint num = a \/ b;\n<\/code><\/pre>\n\n\n\n<p>There\u2019s object oriented wrappers for primitive types in Java, for example an <code>Integer<\/code> class for <code>int<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Strings<\/h3>\n\n\n\n<p>In PHP, you can use either single or double quotes for strings. Only within double quotes, escape sequences (like <code>\\n<\/code> or <code>\\t<\/code>) or variables are interpreted. String concatenation in PHP uses the <code>.<\/code> (dot) operator:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$str = 'Hello ' . \"World \ud83d\ude0e\\n\";\n<\/code><\/pre>\n\n\n\n<p>Java has a special primitive (not an object) type <code>char<\/code> for a single character, enclosed in single quotes. <code>String<\/code> values require double quotes. Concatenation is done with <code>+<\/code> (plus):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>char space = ' ';\nString str = \"Hello\" + space + \"World \ud83d\ude0e\\n\";\n<\/code><\/pre>\n\n\n\n<p>While both PHP and the Java <code>String<\/code> (but not <code>char<\/code>) accept the Unicode emoji, PHP (with its mbstring extension) handles it better:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$len = mb_strlen(\"\ud83d\ude0e\"); \/\/ 1\n<\/code><\/pre>\n\n\n\n<p>Java gets the length wrong:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int len = \"\ud83d\ude0e\".length(); \/\/ 2\n<\/code><\/pre>\n\n\n\n<p>PHP has tons of string functions, like <code>strpos()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$pos = strpos('hello', 'll');\necho $pos . \"\\n\"; \/\/ 2\n<\/code><\/pre>\n\n\n\n<p>The Java equivalent is <code>String.indexOf()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int pos = \"hello\".indexOf(\"ll\");\nSystem.out.println(pos); \/\/ 2\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Operators<\/h3>\n\n\n\n<p>In PHP you\u2019ll often use <code>===<\/code> and <code>!==<\/code> for exact comparison (to avoid trouble with <code>0 == ''<\/code> and the like):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$isEqual = ($a === $b);\n<\/code><\/pre>\n\n\n\n<p>There\u2019s no need for this in (strongly-typed) Java, which simply uses <code>==<\/code> and <code>!=<\/code>.<\/p>\n\n\n\n<p>The <strong>logical operators<\/strong> for AND and OR in PHP are <code>&amp;&amp;<\/code> and <code>||<\/code>. <code>&amp;<\/code> and <code>|<\/code> exist, but are rarely-used bitwise operators. In Java, both forms are considered logical operators. In both languages, <code>&amp;&amp;<\/code> and <code>||<\/code> are \u201cshort-circuit\u201d operators evaluating from left to right and stopping when the result is clear:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int i = 0, j = 0;\nif ((i &gt; 0) &amp;&amp; (++i &gt; 0)) { }\nif ((j &gt; 0) &amp; (++j &gt; 0)) { }\n\/\/ i is now 0, j is now 1\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Program control<\/h3>\n\n\n\n<p>Java doesn\u2019t have PHP\u2019s <code>elseif<\/code>, just use <code>else if<\/code>.<\/p>\n\n\n\n<p>Simple <code>break<\/code> and <code>continue<\/code> statements work the same, but breaking out of nested loops is done by specifying the number of levels in PHP:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while (true) {\n&nbsp; while (true) {\n&nbsp;&nbsp;&nbsp; break 2; \/\/ Break out of both loops\n&nbsp; }\n}\n<\/code><\/pre>\n\n\n\n<p>In Java, you\u2019re using <code>break<\/code> (or <code>continue<\/code>) with a label instead:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>top: { \/\/ label\n&nbsp; while (true) { \n&nbsp;&nbsp;&nbsp; while (true) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break top; \/\/ Break to label\n&nbsp;&nbsp;&nbsp; }\n&nbsp; }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Arrays<\/h3>\n\n\n\n<p>PHP arrays are pretty versatile \u2013 growing as needed, arbitrary keys, mixed types, easily nested. It\u2019s not really fair to compare Java arrays to them (maybe Java collections would be a better match).<\/p>\n\n\n\n<p>Anyway, here\u2019s a simple array in PHP:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ages = &#91;];\n$ages&#91;0] = 16;\n<\/code><\/pre>\n\n\n\n<p>In Java, you must use <code>new<\/code> and specify the size of the array:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int&#91;] ages = new int&#91;4];\nages&#91;0] = 16;\n<\/code><\/pre>\n\n\n\n<p>You can assign values during declaration in PHP:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ages = &#91;16, 12, 5, 4];\n<\/code><\/pre>\n\n\n\n<p>And in Java:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int&#91;] ages = {16, 12, 5, 4};\n<\/code><\/pre>\n\n\n\n<p>Both <code>int[] ages<\/code> and <code>int ages[]<\/code> are valid syntax.<\/p>\n\n\n\n<p>In PHP, you usually iterate over an array using <code>foreach<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ages = &#91;16, 12, 5, 4];\n\nforeach ($ages as $key =&gt; $age) {\n&nbsp; echo $age . \"\\n\";\n}\n<\/code><\/pre>\n\n\n\n<p>Java has a special form of <code>for<\/code> for this, but it doesn\u2019t support getting the key:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int&#91;] ages = {16, 12, 5, 4};\n\nfor (int age: ages) {\n&nbsp; System.out.println(age);\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Classes<\/h3>\n\n\n\n<p>PHP class properties require a visibility keyword, methods are defined via <code>function<\/code>. Members are accessed using <code>-&gt;<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Dog {\n&nbsp; private $greeting = \"Woof\";\n\n&nbsp; function getGreeting() { \n&nbsp;&nbsp;&nbsp; return $this-&gt;greeting . ' ' . $this-&gt;greeting;\n&nbsp; } \n}\n\n$dog = new Dog();\necho $dog-&gt;getGreeting() . \"\\n\"; \/\/ Woof Woof\n<\/code><\/pre>\n\n\n\n<p>In Java, property visibility is optional. There is no keyword for methods. Members are accessed using the dot. <code>this.<\/code> is optional within the class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Dog {\n&nbsp; String greeting = \"Woof\";\n\n&nbsp; String getGreeting() { \n&nbsp;&nbsp;&nbsp; return greeting + ' ' + this.greeting;\n&nbsp; } \n}\n\nDog dog = new Dog();\nSystem.out.println(dog.getGreeting()); \/\/ Woof Woof\n<\/code><\/pre>\n\n\n\n<p><strong>Constructors<\/strong> are named <code>__construct()<\/code> in PHP. Parent constructors are called through <code>parent::__construct()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class PoliteGreeter extends Greeter {\n  protected $title;\n\n&nbsp; public function __construct($title, $who) {\n&nbsp;&nbsp;&nbsp; parent::__construct($who);\n&nbsp;&nbsp;&nbsp; $this-&gt;title = $title;\n&nbsp; }\n}\n<\/code><\/pre>\n\n\n\n<p>In Java, the constructor is named after the class. To call a parent constructor, invoke <code>super()<\/code> (which must be the first call in the constructor if present):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class PoliteGreeter extends Greeter {\n&nbsp; String title;\n&nbsp; \n&nbsp; PoliteGreeter(String title, String who) {\n&nbsp;&nbsp;&nbsp; super(who);\n&nbsp;&nbsp;&nbsp; this.title = title;\n&nbsp; }\n}\n<\/code><\/pre>\n\n\n\n<p>PHP methods can have <strong>default (optional) parameters<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Greeter {\n&nbsp; function greet($who = 'World') {\n&nbsp;&nbsp;&nbsp; echo 'Hello ' . $who . \"\\n\";\n&nbsp; } \n}\n<\/code><\/pre>\n\n\n\n<p>Java doesn\u2019t have default parameters, but <strong>method overloading<\/strong> is pretty cool:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Greeter {\n&nbsp; void greet(String who) {\n&nbsp;&nbsp;&nbsp; System.out.println(\"Hello \" + who);\n&nbsp; } \n\n&nbsp; void greet() {\n&nbsp;&nbsp;&nbsp; this.greet(\"World\");\n&nbsp; } \n}\n<\/code><\/pre>\n\n\n\n<p><strong>Nested classes<\/strong> are another Java feature not available in PHP (used here as a workaround for passing primitive variables by reference):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ByRefExample {\n&nbsp; class ByRefParams {\n&nbsp;&nbsp;&nbsp; String str;\n&nbsp;&nbsp;&nbsp; Integer i;\n&nbsp; }\n\n&nbsp; void changeMe(ByRefParams params) {\n&nbsp;&nbsp;&nbsp; params.str = \"bye\";\n&nbsp;&nbsp;&nbsp; params.i = 99;\n&nbsp; }\n\n&nbsp; public void run() {\n&nbsp;&nbsp;&nbsp; ByRefParams params = new ByRefParams();\n&nbsp;&nbsp;&nbsp; params.str = \"hello\";\n&nbsp;&nbsp;&nbsp; params.i = 42;\n\n&nbsp;&nbsp;&nbsp; changeMe(params);\n&nbsp;&nbsp;&nbsp; \n&nbsp;&nbsp;&nbsp; System.out.println(params.str); \/\/ bye\n&nbsp;&nbsp;&nbsp; System.out.println(params.i); \/\/ 99\n&nbsp; } \n}\n<\/code><\/pre>\n\n\n\n<p><strong>Class constants<\/strong> are defined via <code>const<\/code> in PHP:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Greeter {\n&nbsp; const GREETING = 'Hello';\n}\n\necho Greeter::GREETING . \"\\n\";\n<\/code><\/pre>\n\n\n\n<p>In Java, you\u2019re using <code>final<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Greeter {\n&nbsp; final static String GREETING = \"Hello\";\n}\n\nSystem.out.println(Greeter.GREETING);\n<\/code><\/pre>\n\n\n\n<p><strong>Interfaces<\/strong> and <strong>abstract classes<\/strong> work similarly in PHP and Java. PHP has traits, Java has default and static interface methods as of JDK 8.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Namespaces<\/h3>\n\n\n\n<p>You use <code>namespace<\/code> to declare a PHP file\u2019s namespace:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n\nnamespace example;\n\nclass Greeter {\n&nbsp; const GREETING = 'Hello';\n}\n<\/code><\/pre>\n\n\n\n<p>PHP\u2019s namespace delimiter is the backslash <code>\\<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>echo \\example\\Greeter::GREETING . \"\\n\";\n<\/code><\/pre>\n\n\n\n<p>Java calls a namespace a <code>package<\/code> \u2013 and requires you to mark classes as <code>public<\/code> to be able to use them from other namespaces:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package example;\n\npublic class Greeter {\n&nbsp; public final static String GREETING = \"Hello\";\n}\n<\/code><\/pre>\n\n\n\n<p>Java assumes your sources are organized in subdirectories by package names. The separator is the dot:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(example.Greeter.GREETING);\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Despite my almost 20 years of professional software development, I haven\u2019t learnt a lot of programming languages (see my honest r\u00e9sum\u00e9). So far, it\u2019s just been PHP and JavaScript (plus SQL, XSLT, and \u2013 back in the day \u2013 Object Pascal and Visual Basic). Now I\u2019m trying to teach myself some Java. This blog post [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_share_on_mastodon":"0"},"categories":[1],"tags":[],"class_list":["post-1856","post","type-post","status-publish","format-standard","hentry","category-weblog"],"share_on_mastodon":{"url":"","error":""},"_links":{"self":[{"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/posts\/1856","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/comments?post=1856"}],"version-history":[{"count":1,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/posts\/1856\/revisions"}],"predecessor-version":[{"id":1904,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/posts\/1856\/revisions\/1904"}],"wp:attachment":[{"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/media?parent=1856"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/categories?post=1856"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strehle.de\/tim\/wp-json\/wp\/v2\/tags?post=1856"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}