-5

In Java, if we run:

public class HelloWorld{

     public static void main(String []args){
         if (true) {
             int test = 1;
         } else {
             int test = 2;
         }
        System.out.println(test);
     }
}

It will throw:

HelloWorld.java:9: error: cannot find symbol
        System.out.println(test);
                           ^
  symbol:   variable test
  location: class HelloWorld
1 error

However, in php, if we run:

<?php
        //Enter your code here, enjoy!

if (true) {
    $test = 1;
} else {
    $test = 2;
}

echo $test;

It will print 1.

I suspect if that is because Java is strong typed language and php is weak typed language. Can someone give a more deep and lower level explanation?

weijia_yu
  • 965
  • 4
  • 14
  • 31
  • @JoshuaBurt I am more concerned about why php and Java behave differently. Luckily, one of the answer addresses my puzzle. php is functional scope while Java is blocked scope – weijia_yu Jun 11 '20 at 20:55

3 Answers3

3

In Java, the visibility scope of a variable is limited by {}

if (true) {
    int test = 1;
} else {
    int test = 2;
}
System.out.println(test);// Will fail to compile

It is also important to note the dead code as shown below:

int test;
if (true) {
    test = 1;
} else {
    test = 2;// Dead code
}
System.out.println(test);

Because of if (true) the else block will never be executed causing test = 2 to become the dead code.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

This has nothing to do with difference between static and dynamic typing. The difference here between Java and PHP is variable scope.

  1. In PHP $test = 1; will be part of the global scope as per docs.

  2. In Java int test = 1; will be part of local scope, in your case limited to if block.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
2

Java is "block scoped"; things introduced inside of one { } block go away at the end of that block.

PHP is "function scoped"; things introduced inside of a function last until the end of the function. If you're not in a function, the variable is a global, and lasts until the program completes.

In both languages, once something falls out of scope, it's garbage collected.

Dean J
  • 39,360
  • 16
  • 67
  • 93