This paper investigates how gender composition of classes impacts achievement of students who self-selected into different specialization tracks (STEM vs. Languages) according to their educational preferences. Based on administrative records from one of the largest high schools in the canton of Zurich (Switzerland), we are able to identify the causal effect of the gender composition of classes on student achievement by exploiting random assignment of students to classes. Compared to the previous literature, which mainly focused on average effects across all students, we find highly heterogeneous effects across students who self-selected into different specialization tracks. While the effect of a higher proportion of girls in the classroom is positive for girls and boys with an educational preference for languages, the effect is negative for girls in the STEM track. Our findings have important implications for the optimal organization of classes in schools and for the explanation of career trajectories after school. For instance, concentrating girls in few classes has a positive effect only on girls who favor languages over STEM.