Blockchain development has become increasingly accessible thanks to powerful libraries like Web3j, a lightweight Java library for integrating Ethereum blockchain functionality into Java-based applications. Whether you're building decentralized finance (DeFi) tools, NFT platforms, or enterprise blockchain solutions, understanding how to perform basic ETH transfers and ERC-20 token transactions using Web3j is essential.
This comprehensive guide walks you through setting up Web3j in a Maven project, executing secure Ethereum transfers, and sending custom tokens—complete with practical code examples and best practices. We’ll also answer common questions developers face when working with Web3j.
Setting Up Web3j in a Maven Project
Before performing any blockchain operations, you need to integrate Web3j into your Java environment. If you're using Apache Maven, simply add the Web3j core dependency to your pom.xml
file.
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
This dependency provides all necessary tools for connecting to Ethereum nodes, managing cryptographic keys, signing transactions, and interacting with smart contracts.
👉 Discover how blockchain developers streamline transaction workflows using advanced tools.
Performing a Basic ETH Transfer
Transferring Ether (ETH) from one address to another is one of the most fundamental operations in Ethereum development. Web3j simplifies this process with its Transfer
utility class.
Here’s a step-by-step implementation:
public static void transfer() throws Exception {
// Connect to an Ethereum node via Infura or your own RPC endpoint
Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
// Import private key (ensure it's securely stored!)
BigInteger privateKey = new BigInteger("钱包私钥", 16);
ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);
Credentials credentials = Credentials.create(ecKeyPair);
// Send 0.001 ETH to the recipient address
TransactionReceipt transactionReceipt = Transfer.sendFunds(
web3j,
credentials,
"目标地址",
BigDecimal.valueOf(0.001),
Convert.Unit.ETHER
).send();
// Output transaction result
System.out.println(transactionReceipt);
}
Key Points:
- Replace
"infura节点链接"
with your actual Infura or Alchemy endpoint. - The private key must be in hexadecimal format and handled securely—never expose it in source code.
Convert.Unit.ETHER
ensures the amount is interpreted correctly in Ether units.
Executing ERC-20 Token Transfers
Unlike ETH, tokens such as USDT, DAI, or custom ERC-20 tokens require interaction with their respective smart contracts. This involves manually constructing a transaction that calls the transfer
function on the token contract.
Below is a complete method for sending ERC-20 tokens:
public static void transferToken() throws Exception {
Web3j web3j = Web3j.build(new HttpService("infura节点链接"));
BigInteger privateKey = new BigInteger("私钥", 16);
ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);
Credentials credentials = Credentials.create(ecKeyPair);
String fromAddress = credentials.getAddress();
// Get current nonce to prevent transaction replay
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
fromAddress,
DefaultBlockParameterName.LATEST
).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
// Define recipient and transfer value (in wei)
Address toAddress = new Address("目标地址");
Uint256 value = new Uint256(new BigInteger("数量 单位wei"));
List<Type> parametersList = new ArrayList<>();
parametersList.add(toAddress);
parametersList.add(value);
List<TypeReference<?>> outList = new ArrayList<>();
// Create function call: transfer(address,uint256)
Function function = new Function("transfer", parametersList, outList);
String encodedFunction = FunctionEncoder.encode(function);
// Set gas parameters
System.out.println("Gas Price: " + DefaultGasProvider.GAS_PRICE);
System.out.println("Gas Limit: " + DefaultGasProvider.GAS_LIMIT);
// Build raw transaction
RawTransaction rawTransaction = RawTransaction.createTransaction(
nonce,
DefaultGasProvider.GAS_PRICE,
new BigInteger("210000"), // Adjust gas limit based on contract complexity
"合约地址", // ERC-20 contract address
encodedFunction
);
// Sign transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
// Broadcast transaction
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
Object transactionHash = ethSendTransaction.getTransactionHash();
System.out.println("Transaction Hash: " + transactionHash.toString());
}
Important Notes:
"合约地址"
must be replaced with the actual ERC-20 token contract address (e.g., USDT on Ethereum).- The transfer amount should be in wei or converted appropriately using
BigInteger
. - Gas limits may vary; consider estimating gas usage via
ethEstimateGas
for dynamic adjustment.
👉 Learn how top developers optimize gas costs and improve transaction success rates.
Core Keywords for SEO and Developer Search Intent
To ensure visibility among developers searching for blockchain integration solutions, the following core keywords have been naturally integrated throughout this article:
- Web3j Java
- Ethereum transfer Java
- ERC-20 token transfer
- Web3j Maven setup
- Java blockchain development
- Smart contract interaction Java
- Send tokens programmatically
- Web3j transaction signing
These terms align with high-intent searches from developers building decentralized applications with Java backends.
Frequently Asked Questions (FAQ)
Q: Is Web3j suitable for production environments?
Yes, Web3j is widely used in enterprise-grade blockchain applications. It supports asynchronous calls, robust error handling, and integration with Spring Boot, making it ideal for scalable systems.
Q: Can I use local Ethereum nodes instead of Infura?
Absolutely. While Infura offers convenient cloud-based access, you can connect Web3j to any Ethereum node (e.g., Geth, Parity) by pointing the HttpService
to your local RPC URL (http://localhost:8545
).
Q: How do I handle transaction failures or reverts?
Always check the TransactionReceipt
. If getStatus().equals("0x1")
, the transaction succeeded. A status of "0x0"
indicates failure. Additionally, monitor gas limits and simulate transactions off-chain when possible.
Q: What security best practices should I follow when handling private keys?
Never hardcode private keys. Use secure vaults like Hashicorp Vault, environment variables, or hardware security modules (HSMs). Also, enable two-factor authentication and restrict access permissions in production.
Q: How can I verify if a token transfer was successful?
After obtaining the transaction hash, use web3j.ethGetTransactionReceipt()
to fetch the receipt. Check the logs for Transfer events emitted by the ERC-20 contract.
Q: Does Web3j support other blockchains besides Ethereum?
Yes. Web3j works with any Ethereum-compatible blockchain such as Binance Smart Chain, Polygon, Avalanche, and Arbitrum—just adjust the node URL accordingly.
Final Thoughts
Mastering Web3j for Java-based Ethereum interactions opens doors to innovative blockchain integrations. From simple ETH transfers to complex smart contract invocations, Web3j provides a clean, object-oriented API that fits seamlessly into modern Java ecosystems.
As blockchain adoption grows across industries—from finance to supply chain—developers equipped with skills in programmatic token transfers, secure key management, and transaction broadcasting will remain in high demand.
👉 See how leading platforms empower developers with real-time blockchain data and tools.