Former German foreign minister Frank-Walter Steinmeier has been elected president by a parliamentary assembly.
The Social Democrat, 61, is one of Germany's most popular politicians.
The post is largely ceremonial, but the president represents Germany abroad and is seen as carrying moral weight.
During the US election campaign, the usually circumspect ex-lawyer described Donald Trump as a "hate preacher" and predicted more challenging relations with Washington.
He has also criticised those who "make politics with fear", and spoken out against right-wing populism.
Mr Steinmeier was chosen by the Federal Assembly meeting in parliament in Berlin.
He won 931 out of 1,239 valid votes.
Lawmakers and representatives from various social fields delegated by Germany's 16 states are represented in the assembly.
Electors include Joachim Loew, the national football coach, and Olivia Jones, a colourful drag queen sent to vote by the Green Party in Lower Saxony.
Read more:The drag queen who wants to be president
Mr Steinmeier, who takes up the job on 19 March, held the post of foreign minister twice for a total of eight years.
Both terms were served under Chancellor Angela Merkel in grand coalitions of Christian Democrats and Social Democrats.
In 2009, he stood unsuccessfully against Mrs Merkel in the federal election.
Mr Steinmeier is seen as straight-talking, and as foreign minister was widely respected for taking a strong stance on issues important to German voters, the BBC's Damien McGuinness reports from Berlin.
Many expect he will work to support Germany's reputation as global defender of tolerant liberal values, our correspondent adds.
Mr Steinmeier's election to the presidency is seen as a boost by the Social Democrats as they seek to unseat Mrs Merkel in September's federal elections.
The current post-holder, President Joachim Gauck, decided against bidding for a second five-year term due to his age - 77.
Mr Gauck is a former Lutheran pastor and civil rights activist in the former East Germany.
Mrs Merkel's Christian Democrats failed to find their own candidate for the presidency, and agreed to back Mr Steinmeier for president.
Other candidates included Christoph Butterwegge - nominated by the opposition Left Party - and Albrecht Glaser from the anti-immigrant Alternative for Germany.