Why does the following code print True: 1: a = 1 2: b = 1 3: print(a is b) Whereas this code prints false: 4: a = 100000 5: b = 100000 6: print(a is b)
This is perhaps one of the sneakiest beginner mistakes in Python: using the "is" operator when you should use the "==" operator. The "is" operator checks for *object equivalence*, which means that it only returns True when both operands reference the same object. Since numbers are stored as objects in Python, lines 4 and 5 are creating two distinct objects, thus line 6 prints False. But then you may ask, why does line 3 print True? This is because objects for smaller numbers (numbers between -5 and 256) are cached by the Python application for reasons of efficiency. So, when you create 2 references to the same small number (such as in lines 1 and 2), they will happen to point to the same object until they are reassigned. What's the lesson? Don't compare numbers with the "is" operator! When comparing numbers, use the arithmetic equality operator, "==", which tests the actual value of the variable.
What is a "static" method in Java?
First, let's recall what methods are. A method is a function that interacts with an object. For example, in real life, you can interact with a car by performing the function "start engine". Performing this function requires an existing car to interact with, so we call it a method. A static method is a function that only interacts with the class itself, rather than a specific object of the class. So, in the same car example, a static method might be the function "convert MPG to KM/H". Such a function is related to the concept of a car, but doesn't interact with an existing car (an "instance" of a car). The word "static" means just that: relating to a class rather than an instance of a class.
What are pointers and what are they used for?
In C, the memory of the computer is directly accessible; we can retrieve or set the value at any given memory location (provided it's in an area we've allocated). So, say you want to store the value 10 in the memory location 1483. You can do this in a single line (using literals for 10 and 1483). However, what if we wanted to store those numbers (10 and 1483) in variables? 10 can be stored in an int. However, since 1483 is referring to a memory location, we store it in a special kind of int: a pointer. Why? Because pointers are actually the only way to access memory. Even if you don't use variables (and instead use literals), you still must cast the value 1483 into a pointer, otherwise the assignment isn't a memory operation. As you can see, pointers are just plain-old variables, except their value corresponds to a memory location. They are used anytime you wish to refer to locations in memory.