I'm new to infosec. I'm studying about various encryption algorithms. Based on what I've found so far, I think HMAC and Digital signature are almost the same except whether the key is symmetric or asymmetric. For me, it seems that a complexity of HMAC is lower than the digital signature according to its function. Then can I say using HMAC is preferable to digital signature? I found that the weakness of HMAC is the key getting compromised. But does it really happen? if so, how does it occur in the real world? + when digital signature is more efficient than HMAC?
They're suitable for different use cases. Assuming you're using a well-tested implementation written by somebody who knows what they're doing (so, probably not something you wrote yourself or pulled off some random person's GitHub), they're both quite secure, although the threat models are a little different. Also, HMACs are generally computationally cheaper.
HMACs are only usable when you have complete trust in both the party certifying the message (usually the author), and the party verifying the message's authenticity. Complete trust is required because the ability to verify an HMAC also means having the ability to forge one. It also only works when you have a secure way to exchange the shared key.
Signatures are used when the party verifying the authenticity is not fully trusted by the certifying party, or when there's no way to securely exchange keys. It's usually more computationally expensive and requires storing/transmitting more data, so it's usually not used unless needed.
HMAC key leakage is mostly a problem when "fully trusted" is a little fuzzy. For example, you might trust a third party to not forge messages, but do you also trust them to have adequate storage of the key and adequate protection against application compromise? Or perhaps you trust their key exchange system to be secure against an attacker intercepting or tampering with the exchanged key, but don't trust them not to capture it in a log file somewhere that might later get leaked?
There aren't many situations where you really have to choose between the two constructions. The main one that comes to mind is the JSON Web Token (JWT). My usual advice for JWTs is that if the party verifying the JWT is meaningfully less trusted/trustworthy than the party generating the JWT, use a signature; otherwise use HMAC. However, it really should be decided on a case by case basis.