get current user id in apex

getUserInfo in salesforce can be used to get the personal information about the currently logged-in user.

One can use userinfo.getuserid() in apex to get current users personal information like nmae, profile, language,locale, role id, time zone etc.. To get the id just use this method of userinfo - getuserid() : 
  ID CurrentuserId = userinfo.getuserID();

In the following example, the output text in the pageblock will dispaly the current logged in user's ID

  visualforce page
<apex:page extensions="DemoController" standardcontroller="Account">
           <apex:outputtext value="{!LoggedInUSerId}">

Public with sharing class DemoController {
   Public Id LoggedInUSerId{get;set;}
     Public DemoController(ApexPages.StandardController controller) {
          LoggedInUSerId = UserInfo.getUserId();

Similarly we can also get user name, profile and most of the other field values using userinfo.

For example, to get current logged in users name just use this method:
 String CurrentUserName = Userinfo.getuserName();

to get current user profile name in salesforce yuo need fire a soql query on profile object using userinfo.getProfileId() as below.

List<Profile> proList = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId()];

String profileName  = proList[0].Name;

Lets see how to get current username in salesforce. In visualforce page the current user name can be displayed simply by using User.FirstName and User.LastName as shown below,

 <apex:outputText label="Current User Name" value="{!$User.FirstName&' '&$user.lastname}"></apex:outputText>

userinfo class provides lots of method to get almost everything related to user. But still, if you want to retrieves some field that is not available by given methods or say you have a custom field on user object then you can userinfo.getuserid() in soql and retrieve that information like below,

 User us = [select id, mycustomfld__c from user where id =:userinfo.getuserid() limit 1];


  1. From where i can access the user id now ??

  2. Hi Ankit ,here you get the user id in vf page. just preview vf page.

    [select id,name from user where id='vfpageid(ouputid)'] .