A 17-year-old who was caught by his friend's parents while he was having unprotected sex with a 12-year-old girl has been spared a jail sentence.

The teenager from Queensland had pleaded guilty to five charges relating to his sexual relationship with the girl and was sentenced to two years probation, The Queensland Times reported on Friday.

He pleaded guilty to three counts of indecent treatment of a child under 16 and two counts of unlawful carnal knowledge with a child under 16.

The 17-year-old teenager from Queensland was spared a jail term for having sex with a 12-year-old girl (stock image)

The Ipswich District Court heard the 17-year-old and the 12-year-old girl had consensual sex on two occasions between December 15, 2014 and January 1, 2015.

The pair had exchanged flirtatious messages on Facebook before the sexual encounters and the 17-year-old knew how old the girl was.

The matter came to the attention of the authorities when the pair had sex in the 17-year-old's friend's house and were caught by the friend's parents.

CONSENT IN QUEENSLAND The age of consent in Queensland is 16 for vaginal sex and 18 for anal sex. If you are under the age of consent, you cannot legally agree to have sex. Even if you agree to sex, the person who has sex with you may be charged. If you are aged between 12 and 15, a person can legally have sex with you if you agree and they believed you were 16 or older. Courtesy: Law Stuff Advertisement

Crown prosecutor Noel Needham told the court the girl could consent at the age of 12.

'She still is able to consent, even though the carnal knowledge is unlawful, it's still considered consensual,' Mr Needham said.

'It's under the age of 12 years that is deemed not capable of giving consent.'

Judge Greg Koppenol told the 17-year-old he could have been sentenced to jail.

'There may not have been a big age difference but the fact of the matter is that this girl was only 12,' he said.

However, judge Koppenol also noted the 17-year-old had no prior criminal record and had shown remorse.