Ok, this is when a careful definition becomes so critical in answering a question. We need a careful set theoretic definition of a function and we need some prerequisite definitions.
Def: An ordered pair is the following set:
(a,b)= { {a},{a,b}}
where a,b are elements. 2 ordered pairs are said to be equal iff they are subsets of each other.
Def: Let A and B be sets. Then the Cartesian product of 2 sets is the following set:
$A\times B$ = { (a,b)| $a\in A$ and $b\in B$}
Now the definition of a function:
Def:Let A and B be sets. Then we define a function from A into B, denoted $f:A \rightarrow B$ as $f\subseteq A\times B$ such that (a,b),(a,d)$\in f$ iff b = d. (In other words,no 2 different ordered pairs in a function have the same first member.) A is called the domain the function and it consists of all the first members of all the ordered pairs of f. B is called the codomain of the function. The range of the function is the set of all second members of the ordered pairs of the function and it is a subset of B.
Notice our definition of function is completely independent of whether or not it's defined by a formula or not.
Now let's look at the examples. Consider example 1. Given the definition of f and g,despite having different codomains,the ranges of both functions is the set of positive reals because $x^2\geq 0$ for all $x\in \mathbb R$. Since the domains are $\mathbb R$ for both f and g ,clearly every ordered pair in f is in g and vice versa. Therefore f= g.
Now consider example 2. The domain of f is $\mathbb R$ while the domain of g is $\mathbb R \geq 0$. Therefore, {(x,$x^2$)| $x\leq 0$ } $\subset f$ but {(x,$x^2$)| $x\leq 0$ } is not a subset of g. Therefore f is not equal to g.