Semiconductor p-n junctions are the elementary building blocks of most electronic and optoelectronic devices. The need for their miniaturization has fuelled the rapid growth of interest in two-dimensional (2D) materials. However, the performance of a p-n junction considerably degrades as its thickness approaches a few nanometres and traditional technologies, such as doping and implantation, become invalid at the nanoscale. Here we report stable non-volatile programmable p-n junctions fabricated from the vertically stacked all-2D semiconductor/insulator/metal layers (WSe2/hexagonal boron nitride/graphene) in a semifloating gate field-effect transistor configuration. The junction exhibits a good rectifying behaviour with a rectification ratio of 104 and photovoltaic properties with a power conversion efficiency up to 4.1% under a 6.8 nW light. Based on the non-volatile programmable properties controlled by gate voltages, the 2D p-n junctions have been exploited for various electronic and optoelectronic applications, such as memories, photovoltaics, logic rectifiers and logic optoelectronic circuits.