It's unspecified whether or not a reference takes up memory. If the compiler can determine which object it refers to, then it can simply use the reference as an alternative "name" for that object, with no need for any run-time information. If it can't, then the reference will need to hold its target's address, just like a pointer.
Pointers are objects, and so take up memory like any other object. However, optimisations under the "as if" rule mean that objects only have to take up memory if the program's behaviour depends on them doing so; for example, if you print its address. So if the compiler can determine which object the pointer points to, then it can replace indirect accesses through the pointer with direct accesses to that object, and perhaps remove the pointer altogether.
The same optimisation rule means that, in both your examples, all the variables can be removed since they have no effect.