Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
CharBuffer clear() methods in Java with Examples
Next article icon

CharsetEncoder encode(CharBuffer in) method in Java with Examples

Last Updated : 10 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
The encode(CharBuffer input) method is a built-in method of the java.nio.charset.CharsetEncoder which encodes the content which is remaining of a single input character buffer to a newly-allocated byte-buffer. The encode() method in itself implements an entire operation of encoding. This function should not be invoked if the operation is in progress. Syntax:
public final ByteBuffer encode(CharBuffer input)
Parameters: The function accepts a mandatory parameter input which specifies the input character buffer. Return Value: The function returns a newly-allocated byte buffer containing the result of the encoding operation. Error and Exceptions: The function throws four exceptions which can be described as below:
  • IllegalStateException: It is thrown if an encoding operation is already in progress.
  • MalformedInputException: It is thrown if the character sequence starting at the input buffer's current position is not a legal sixteen-bit Unicode sequence and the current malformed-input action is CodingErrorAction.REPORT.
  • UnmappableCharacterException: It is thrown if the character sequence starting at the input buffer's current position cannot be mapped to an equivalent byte sequence and the current unmappable-character action is CodingErrorAction.REPORT
  • CharacterCodingException
Below is the implementation of the above function: Program 1: Java
// Java program to implement // the above function import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder;  public class Main {     public static void main(String[] args) throws Exception     {          // Gets the new encoder         CharsetEncoder encoder = Charset.forName("UTF8").newEncoder();          // Encodes         String res = "gfggfg";         System.out.println(encoder.encode(CharBuffer.wrap(res)));     } } 
Output:
  java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]  
Program 2: Java
// Java program to implement // the above function import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder;  public class Main {     public static void main(String[] args) throws Exception     {          // Gets the new encoder         CharsetEncoder encoder = Charset.forName("UTF16").newEncoder();          // Encodes         String res = "gopal";         System.out.println(encoder.encode(CharBuffer.wrap(res)));     } } 
Output:
  java.nio.HeapByteBuffer[pos=0 lim=12 cap=21]  
The exception programs cannot be demonstrated in programs. Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/CharsetEncoder.html#encode(java.nio.CharBuffer)

Next Article
CharBuffer clear() methods in Java with Examples
author
gopaldave
Improve
Article Tags :
  • Java
  • Java-Functions
  • Java-NIO package
  • Java-CharsetEncoder
Practice Tags :
  • Java

Similar Reads

  • CharsetEncoder charset() method in Java with Examples
    The charset() method is a built-in method of the java.nio.charset.CharsetEncoder returns the charset that created this encoder. Syntax: public final Charset charset() Parameters: The function does not accepts any parameter. Return Value: The function returns this encoder's charset. Below is the impl
    1 min read
  • CharBuffer chars() methods in Java with Examples
    The chars() method of java.nio.CharBuffer Class is used to return a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. The stream binds to this sequence when the terminal stream operation commences (specific
    2 min read
  • CharBuffer clear() methods in Java with Examples
    The clear() method of java.nio.CharBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer. For example: // Prepare buffer for
    2 min read
  • CharsetEncoder averageBytesPerChar() method in Java with Examples
    The averageBytesPerChar() method is a built-in method of the java.nio.charset.CharsetEncoder which returns the average number of bytes that will be produced for each character of input which is provided. The heuristic value thus is used to estimate the size of the output buffer required for a given
    1 min read
  • CharsetDecoder averageCharsPerByte() method in Java with Examples
    The averageCharsPerByte() method is a built-in method of the java.nio.charset.CharsetDecoder class which returns the average number of characters that will be produced for each byte of input. This heuristic value may be used to estimate the size of the output buffer required for a given input sequen
    2 min read
  • CharArrayReader close() method in Java with Examples
    The close() method of CharArrayReader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources If the stream is already closed, it will have no effe
    3 min read
  • CharsetDecoder charset() in Java with examples
    CharsetDecoder.charset() is an in-built method in Java of CharsetDecoder class that returns the charset that created this decoder. Syntax: public final Charset charset() Parameter: The function does not accepts any parameter. Return value: The function returns the decoder's charset. Program below de
    1 min read
  • CharsetDecoder detectedCharset() method in Java with Examples
    The detectedCharset() method is a built-in method of the java.nio.charset.CharsetDecoder class which retrieves the charset that has been detected by this decoder. The default implementation of this method always throws an UnsupportedOperationException. It should be overridden by auto-detecting decod
    2 min read
  • CharsetEncoder reset() method in Java with Examples
    The reset() method is a built-in method of the java.nio.charset.CharsetEncoder resets this encoder, and clears all the internal states if there are any. It also resets charset-independent state and also invokes the implReset method in order to perform any charset-specific reset actions. Syntax: publ
    2 min read
  • CharBuffer flip() methods in Java with Examples
    The flip() method of java.nio.CharBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences