This example is based on the code in the CpuConfiguration.java and MemoryConfiguration.java sample files.

Note: For a complete and up-to-date version of the Java sample code, see the vsphere-automation-sdk-java VMware repository at GitHub.
... 

    private String vmName;
    private String vmId;
    private Memory memoryService;
    private Cpu cpuService;
... 

        this.memoryService = vapiAuthHelper.getStubFactory().createStub(Memory.class,
                    this.sessionStubConfig);

        this.vmId = VmHelper.getVM(vapiAuthHelper.getStubFactory(), sessionStubConfig, vmName);

        // Update the memory size of the virtual machine
        MemoryTypes.UpdateSpec memoryUpdateSpec = new MemoryTypes.UpdateSpec.Builder().setSizeMiB(8 * 1024l).build();
        memoryService.update(this.vmId, memoryUpdateSpec);
        memoryInfo = memoryService.get(this.vmId);   
    
        // Enable adding memory while the virtual machine is running
        memoryUpdateSpec = new MemoryTypes.UpdateSpec.Builder().setHotAddEnabled(true).build();
        memoryService.update(this.vmId, memoryUpdateSpec);
             ... 

        this.cpuService = vapiAuthHelper.getStubFactory().createStub(Cpu.class,
            this.sessionStubConfig);

          // Get the current CPU information
        CpuTypes.Info cpuInfo = cpuService.get(this.vmId);

         // Update the number of CPU cores 
        CpuTypes.UpdateSpec cpuUpdateSpec = new CpuTypes.UpdateSpec.Builder()
            .setCount(2l).build();
        cpuService.update(this.vmId, cpuUpdateSpec);
        cpuInfo = cpuService.get(this.vmId);

         // Update the number of cores per socket in the virtual machine and 
         // allow CPU cores to be added to the virtual machine while it is running 
        cpuUpdateSpec = new CpuTypes.UpdateSpec.Builder().setCoresPerSocket(2l).setHotAddEnabled(true).build();
        cpuService.update(this.vmId, cpuUpdateSpec);
...