Author: saqibkhan

  • ClassLoader 

    Introduction

    The Java ClassLoader class is an object that is responsible for loading classes. This class is an abstract class. It may be used by security managers to indicate security domains.

    Class Declaration

    Following is the declaration for java.lang.ClassLoader class −

    publicabstractclassClassLoaderextendsObject

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class constructors

    Sr.No.Constructor & Description
    1protected ClassLoader()This creates a new class loader using the ClassLoader returned by the method getSystemClassLoader() as the parent class loader.
    2protected ClassLoader(ClassLoader parent)This creates a new class loader using the specified parent class loader for delegation.

    Class methods

    Sr.No.Method & Description
    1void clearAssertionStatus()This method sets the default assertion status for this class loader to false and discards any package defaults or class assertion status settings associated with the class loader.
    2protected Class<?> defineClass(String name, byte[] b, int off, int len)This method converts an array of bytes into an instance of class Class.
    3protected Class<?> defineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain)This method converts an array of bytes into an instance of class Class, with an optional ProtectionDomain
    4protected Class<?> defineClass(String name, ByteBuffer b, ProtectionDomain protectionDomain)This method converts a ByteBuffer into an instance of class Class, with an optional ProtectionDomain.
    5protected Package definePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase)This method defines a package by name in this ClassLoader.
    6protected Class<?> findClass(String name)This method finds the class with the specified binary name.
    7protected String findLibrary(String libname)This method returns the absolute path name of a native library.
    8protected Class<?> findLoadedClass(String name)This method returns the class with the given binary name if this loader has been recorded by the Java virtual machine as an initiating loader of a class with that binary name.
    9protected URL findResource(String name)This method Finds the resource with the given name.
    10protected Enumeration<URL> findResources(String name)This method returns an enumeration of URL objects representing all the resources with the given name.
    11protected Class<?> findSystemClass(String name)This method finds a class with the specified binary name, loading it if necessary.
    12protected Package getPackage(String name)This method returns a Package that has been defined by this class loader or any of its ancestors.
    13protected Package[] getPackages()This method returns all of the Packages defined by this class loader and its ancestors.
    14ClassLoader getParent()This method returns the parent class loader for delegation.
    15URL getResource(String name)This method finds the resource with the given name.
    16InputStream getResourceAsStream(String name)This method returns an input stream for reading the specified resource.
    17Enumeration<URL> getResources(String name)This method finds all the resources with the given name.
    18static ClassLoader getSystemClassLoader()This method returns the system class loader for delegation.
    19static URL getSystemResource(String name)This method find a resource of the specified name from the search path used to load classes.
    20static InputStream getSystemResourceAsStream(String name)This method is open for reading, a resource of the specified name from the search path used to load classes.
    21static Enumeration<URL> getSystemResources(String name)This method finds all resources of the specified name from the search path used to load classes.
    22Class<?> loadClass(String name)This method loads the class with the specified binary name.
    23protected Class<?> loadClass(String name, boolean resolve)This method loads the class with the specified binary name.
    24protected void resolveClass(Class<?> c)This method links the specified class.
    25void setClassAssertionStatus(String className, boolean enabled)This method sets the desired assertion status for the named top-level class in this class loader and any nested classes contained therein.
    26void setDefaultAssertionStatus(boolean enabled)This method sets the default assertion status for this class loader.
    27void setPackageAssertionStatus(String packageName, boolean enabled)This method sets the package default assertion status for the named package.
    28protected void setSigners(Class<?> c, Object[] signers)This method sets the signers of a class.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object

    Getting ClassLoader and its Parent ClassLoader Example

    The following example shows the usage of java.lang.ClassLoader.getParent() method. In this program, we’ve retrieved class of a ClassLoaderDemo. Then using getClassLoader(), we get the required ClassLoader and printed class loader class using getClass() and printed the parent class loader using getParent() method.

    Open Compiler

    packagecom.tutorialspoint;publicclassClassLoaderDemo{publicstaticvoidmain(String[] args)throwsException{Class cls =Class.forName("com.tutorialspoint.ClassLoaderDemo");// returns the ClassLoader object associated with this ClassClassLoader cLoader = cls.getClassLoader();System.out.println(cLoader.getClass());// returns the parent ClassLoaderSystem.out.println(cLoader.getParent());}}

    Output

    Let us compile and run the above program, this will produce the following result −

    class jdk.internal.loader.ClassLoaders$AppClassLoader
    jdk.internal.loader.ClassLoaders$PlatformClassLoader@4517d9a3
    
  • Class

    Introduction

    The Java Class class instance represent classes and interfaces in a running Java application. It has no public constructor.

    Class Declaration

    Following is the declaration for java.lang.Class class −

    publicfinalclassClass<T>extendsObjectimplementsSerializable,GenericDeclaration,Type,AnnotatedElement

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1<U> Class<? extends U> asSubclass(Class<U> clazz)This method casts this Class object to represent a subclass of the class represented by the specified class object.
    2T cast(Object obj)This method casts an object to the class or interface represented by this Class object.
    3boolean desiredAssertionStatus()This method returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.
    4static Class<?> forName(String className)This method returns the Class object associated with the class or interface with the given string name.
    5static Class<?> forName(String name, boolean initialize, ClassLoader loader)This method returns the Class object associated with the class or interface with the given string name, using the given class loader.
    6<A extends Annotation> A getAnnotation(Class<A> annotationClass)This method returns this element’s annotation for the specified type if such an annotation is present, else null.
    7Annotation[] getAnnotations()This method returns all annotations present on this element.
    8String getCanonicalName()This method returns the canonical name of the underlying class as defined by the Java Language Specification.
    9Class<?>[] getClasses()This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.
    10ClassLoader getClassLoader()This method returns the class loader for the class.
    11Class<?> getComponentType()This method returns the Class representing the component type of an array.
    12Constructor<T> getConstructor(Class<?>… parameterTypes)This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
    13Constructor<?>[] getConstructors()This method returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
    14Annotation[] getDeclaredAnnotations()This method returns all annotations that are directly present on this element.
    15Class<?>[] getDeclaredClasses()This method returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.
    16Constructor<T> getDeclaredConstructor(Class<?>… parameterTypes)This method returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
    17Constructor<?>[] getDeclaredConstructors()This method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
    18Field getDeclaredField(String name)This method returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
    19Field[] getDeclaredFields()This method returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.
    20Method getDeclaredMethod(String name, Class<?>… parameterTypes)This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
    21Method[] getDeclaredMethods()This method returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.
    22Class<?> getDeclaringClass()If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.
    23Class<?> getEnclosingClass()This method returns the immediately enclosing class of the underlying class.
    24Constructor<?> getEnclosingConstructor()If this Class object represents a local or anonymous class within a constructor, returns a Constructor object representing the immediately enclosing constructor of the underlying class.
    25Method getEnclosingMethod()If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class.
    26T[] getEnumConstants()This method returns the elements of this enum class or null if this Class object does not represent an enum type.
    27Field getField(String name)This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
    28Field[] getFields()This method returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
    29Type[] getGenericInterfaces()This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object.
    30Type getGenericSuperclass()This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.
    31Class<?>[] getInterfaces()This method determines the interfaces implemented by the class or interface represented by this object.
    32Method getMethod(String name, Class<?>… parameterTypes)This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
    33Method[] getMethods()This method returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
    34int getModifiers()This method returns the Java language modifiers for this class or interface, encoded in an integer.
    35String getName()This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
    36Package getPackage()This method gets the package for this class.
    37ProtectionDomain getProtectionDomain()This method returns the ProtectionDomain of this class.
    38URL getResource(String name)This method finds a resource with a given name.
    39InputStream getResourceAsStream(String name)This method finds a resource with a given name.
    40Object[] getSigners()This method gets the signers of this class.
    41String getSimpleName()This method returns the simple name of the underlying class as given in the source code.
    42Class<? super T> getSuperclass()This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
    43TypeVariable<Class<T>>[]getTypeParameters()This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.
    44boolean isAnnotation()This method returns true if this Class object represents an annotation type.
    45boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)This method returns true if an annotation for the specified type is present on this element, else false.
    46boolean isAnonymousClass()This method returns true if and only if the underlying class is an anonymous class.
    47boolean isArray()This method determines if this Class object represents an array class.
    48boolean isAssignableFrom(Class<?> cls)This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
    49boolean isEnum()This method returns true if and only if this class was declared as an enum in the source code.
    50boolean isInstance(Object obj)This method determines if the specified Object is assignment-compatible with the object represented by this Class.
    51boolean isInterface()This method Determines if the specified Class object represents an interface type.
    52boolean isLocalClass()This method returns true if and only if the underlying class is a local class.
    53boolean isMemberClass()This method returns true if and only if the underlying class is a member class.
    54boolean isPrimitive()This method determines if the specified Class object represents a primitive type.
    55boolean isSynthetic()This method returns true if this class is a synthetic class; returns false otherwise.
    56T newInstance()This method creates a new instance of the class represented by this Class object.
    57String toString()This method converts the object to a string.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object

    Getting Class Names and Casting a Parent Class as SubClass Example

    The following example shows the usage of Class asSubclass() method. We’ve created two classes, ClassDemo and its subclass SubClass1. Using getClass() method, we printed the class names and then using asSubClass we’re casting parent class as child class and are getting its instance.

    Open Compiler

    packagecom.tutorialspoint;publicclassClassDemo{publicstaticvoidmain(String[] args){try{ClassDemo cls =newClassDemo();ClassDemo subcls =newSubClass1();// class ClassDemoClass c = cls.getClass();System.out.println(c);// sub class SubClass1Class c1 = subcls.getClass();System.out.println(c1);// represent a subclass of the specified class objectClass retval = c1.asSubclass(c);System.out.println(retval);}catch(ClassCastException e){System.out.println(e.toString());}}}classSubClass1extendsClassDemo{// sub class}

    Let us compile and run the above program, this will produce the following result −

    class com.tutorialspoint.ClassDemo
    class com.tutorialspoint.SubClass1
    class com.tutorialspoint.SubClass1
    
  • UnicodeBlock Class

    The Java Character.UnicodeBlock class is a family of character subsets representing the character blocks in the Unicode specification. Character blocks generally define characters used for a specific script or purpose.

    Class Declaration

    Following is the declaration for java.lang.Character.UnicodeBlock class −

    publicstaticfinalclassCharacter.UnicodeBlockextendsCharacter.Subset

    Class Methods

    Sr.No.Method & Description
    1forName()This method returns the UnicodeBlock with the given name.
    2of()This method returns the object representing the Unicode block containing the given character, or null if the character is not a member of a defined block.
    2of(int codePoint)This method returns the object representing the Unicode block containing the given character, or null if the character is not a member of a defined block.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Getting UnicodeBlock using Block Names Example

    The following example shows the usage of Java Character.UnicodeBlock forName() method.

    Open Compiler

    packagecom.tutorialspoint;publicclassCharacterUnicodeBlockDemo{publicstaticvoidmain(String[] args){// returns the UnicodeBlock instance with blockName "BASIC_LATIN"System.out.println(Character.UnicodeBlock.forName("BASIC_LATIN"));// returns the UnicodeBlock instance with blockName "BasicLatin"System.out.println(Character.UnicodeBlock.forName("BasicLatin"));// returns the UnicodeBlock instance with specified blockName System.out.println(Character.UnicodeBlock.forName("ARABIC"));System.out.println(Character.UnicodeBlock.forName("MUSICALSYMBOLS"));System.out.println(Character.UnicodeBlock.forName("TAMIL"));}}

    Let us compile and run the above program, this will produce the following result −

    BASIC_LATIN
    BASIC_LATIN
    ARABIC
    MUSICAL_SYMBOLS
    TAMIL
    
  • Subset Class

    The java.lang.Character.Subset class instances represent particular subsets of the Unicode character set. The only family of subsets defined in the Character class is UnicodeBlock.

    Class Declaration

    Following is the declaration for java.lang.Character.Subset class −

    publicstaticclassCharacter.SubsetextendsObject

    Class Constructors

    Sr.No.Constructor & Description
    1protected Character.Subset(String name)This constructs a new Subset instance.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class Methods

    Sr.No.Method & Description
    1equals()This method compares two Subset objects for equality.
    2hashCode()This method returns the standard hash code as defined by the Object.hashCode() method.
    3toString()This method returns the name of this subset.

    Comparing Subset objects for Equality Example

    In the following example, we instantiate CharacterSubsetDemo class objects. The method Java Character.Subset equals() is then called on these objects to check whether they are equal or not.

    Open Compiler

    packagecom.tutorialspoint;publicclassCharacterSubsetDemoextendsCharacter.Subset{// constructor of super classCharacterSubsetDemo(String s){super(s);// invokes the immediate parent class: Object}publicstaticvoidmain(String[] args){CharacterSubsetDemo obj1 =newCharacterSubsetDemo("admin");CharacterSubsetDemo obj2 =newCharacterSubsetDemo("webmaster");CharacterSubsetDemo obj3 =newCharacterSubsetDemo("administrator");// compares Subset objects for equalityboolean retval = obj1.equals(obj1);System.out.println("Object obj1 is equal to obj1 ? "+ retval);
    
      retval = obj2.equals(obj1);System.out.println("Object obj1 is equal to obj2 ? "+ retval);
      retval = obj3.equals(obj1);System.out.println("Object obj1 is equal to obj3 ? "+ retval);}}</code></pre>

    Output

    Let us compile and run the above program, this will produce the following result −

    Object obj1 is equal to obj1 ? true
    Object obj1 is equal to obj2 ? false
    Object obj1 is equal to obj3 ? false
    
  • Byte class with Examples

    Introduction

    The Java Byte class class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.

    Class Declaration

    Following is the declaration for java.lang.Byte class −

    publicfinalclassByteextendsNumberimplementsComparable<Byte>

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.lang.Byte class −

    • static byte MAX_VALUE − This is constant holding the maximum value a byte can have, 27-1.
    • static byte MIN_VALUE − This is constant holding the minimum value a byte can have, -27.
    • static int SIZE − This is the number of bits used to represent a byte value in two’s complement binary form.
    • static Class<Byte> TYPE − This is the Class instance representing the primitive type byte.

    Class constructors

    Sr.No.Constructor & Description
    1Byte(byte value)This constructs a newly allocated Byte object that represents the specified byte value.
    2Byte(String s)This constructs a newly allocated Byte object that represents the byte value indicated by the String parameter.

    Class methods

    Sr.No.Method & Description
    1byte byteValue()This method returns the value of this Byte as a byte.
    2int compareTo(Byte anotherByte)This method compares two Byte objects numerically.
    3static Byte decode(String nm)This method decodes a String into a Byte.
    4double doubleValue()This method returns the value of this Byte as a double.
    5boolean equals(Object obj)This method compares this object to the specified object.
    6float floatValue()This method returns the value of this Byte as a float.
    7int hashCode()This method returns a hash code for this Byte.
    8int intValue()This method returns the value of this Byte as an int.
    9long longValue()This method returns the value of this Byte as a long.
    10static byte parseByte(String s)This method parses the string argument as a signed decimal byte.
    11static byte parseByte(String s, int radix)This method parses the string argument as a signed byte in the radix specified by the second argument.
    12short shortValue()This method returns the value of this Byte as a short.
    13String toString()This method returns a String object representing this Byte’s value.
    14static String toString(byte b)This method returns a new String object representing the specified byte.
    15static Byte valueOf(byte b)This method returns a Byte instance representing the specified byte value.
    16static Byte valueOf(String s)This method returns a Byte object holding the value given by the specified String.
    17static Byte valueOf(String s, int radix)This method returns a Byte object holding the value extracted from the specified String when parsed with the radix given by the second argument.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object

    Example

    The following example shows the usage of Byte class to get byte from a string.

    Open Compiler

    packagecom.tutorialspoint;publicclassByteDemo{publicstaticvoidmain(String[] args){// create a String s and assign value to itString s ="+120";// create a Byte object bByte b;// get the value of byte from string
    
      b =Byte.valueOf(s);// print the valueSystem.out.println("Byte value of string "+ s +" is "+ b );}}</code></pre>

    Let us compile and run the above program, this will produce the following result −

    Byte value of string +120 is 120
    
  • Unicode Conversion from/to Reader/Writer

    Reader and Writer classes are character oriented stream classes. These can be used to read and convert Unicode characters.

    Conversion

    Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer classes.

    Example

    Open Compiler

    importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.Reader;importjava.io.Writer;importjava.nio.charset.Charset;importjava.text.ParseException;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException,IOException{String input ="This is a sample text";InputStream inputStream =newByteArrayInputStream(input.getBytes());//get the UTF-8 dataReader reader =newInputStreamReader(inputStream,Charset.forName("UTF-8"));//convert UTF-8 to Unicodeint data = reader.read();while(data !=-1){char theChar =(char) data;System.out.print(theChar);
    
         data = reader.read();}
      reader.close();System.out.println();//Convert Unicode to UTF-8 BytesByteArrayOutputStream outputStream =newByteArrayOutputStream();Writer writer =newOutputStreamWriter(outputStream,Charset.forName("UTF-8"));
      writer.write(input);
      writer.close();String out =newString(outputStream.toByteArray());System.out.println(out);}}</code></pre>

    Output

    It will print the following result.

    This is a sample text
    This is a sample text
    
  • Unicode Conversion from/to String

    In java, text is internally stored in Unicode format. If input/output is in differnt format then conversion is required.

    Conversion

    Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[].

    Example

    Open Compiler

    importjava.io.UnsupportedEncodingException;importjava.nio.charset.Charset;importjava.text.ParseException;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException,UnsupportedEncodingException{String unicodeString ="\u00C6\u00D8\u00C5";//convert Unicode to UTF8 formatbyte[] utf8Bytes = unicodeString.getBytes(Charset.forName("UTF-8"));printBytes(utf8Bytes,"UTF 8 Bytes");//convert UTF8 format to UnicodeString converted =newString(utf8Bytes,"UTF8");byte[] unicodeBytes = converted.getBytes();printBytes(unicodeBytes,"Unicode Bytes");}publicstaticvoidprintBytes(byte[] array,String name){for(int k =0; k < array.length; k++){System.out.println(name +"["+ k +"] = "+ array[k]);}}}

    Output

    It will print the following result.

    UTF 8 Bytes[0] = -61
    UTF 8 Bytes[1] = -122
    UTF 8 Bytes[2] = -61
    UTF 8 Bytes[3] = -104
    UTF 8 Bytes[4] = -61
    UTF 8 Bytes[5] = -123
    Unicode Bytes[0] = -58
    Unicode Bytes[1] = -40
    Unicode Bytes[2] = -59
    
  • UTC

    UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. All timezones are computed comparatively with UTC as offset. For example, time in Copenhagen, Denmark is UTC + 1 means UTC time plus one hour. It is independent of Day light savings and should be used to store date and time in databases.

    Conversion of Time Zones

    Following example will showcase conversion of various timezones. We’ll print hour of the day and time in milliseconds. First will vary and second will remain same.

    Example

    Open Compiler

    importjava.text.ParseException;importjava.util.Calendar;importjava.util.GregorianCalendar;importjava.util.TimeZone;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException{Calendar date =newGregorianCalendar();
    
    
      date.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
      date.set(Calendar.HOUR_OF_DAY,12);System.out.println("UTC: "+ date.get(Calendar.HOUR_OF_DAY));System.out.println("UTC: "+ date.getTimeInMillis());
      date.setTimeZone(TimeZone.getTimeZone("Europe/Copenhagen"));System.out.println("CPH: "+ date.get(Calendar.HOUR_OF_DAY));System.out.println("CPH: "+ date.getTimeInMillis());
      date.setTimeZone(TimeZone.getTimeZone("America/New_York"));System.out.println("NYC: "+ date.get(Calendar.HOUR_OF_DAY));System.out.println("NYC: "+ date.getTimeInMillis());}}</code></pre>

    Output

    It will print the following result.

    UTC: 12
    UTC: 1511956997540
    CPH: 13
    CPH: 1511956997540
    NYC: 7
    NYC: 1511956997540
    

    Available Time Zones

    Following example will showcase the timezones available with the system.

    Example

    Open Compiler

    importjava.text.ParseException;importjava.util.TimeZone;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException{String[] availableIDs =TimeZone.getAvailableIDs();for(String id : availableIDs){System.out.println("Timezone = "+ id);}}}

    Output

    It will print the following result.

    Timezone = Africa/Abidjan
    Timezone = Africa/Accra
    ...
    Timezone = VST
    
  • Date Format Patterns

    Followings is the use of characters in date formatting patterns.

    Sr.No.Class & Description
    1GTo display Era.
    2yTo display Year. Valid values yy, yyyy.
    3MTo display Month. Valid values MM, MMM or MMMMM.
    4dTo display day of month. Valid values d, dd.
    5hTo display hour of day (1-12 AM/PM). Valid value hh.
    6HTo display hour of day (0-23). Valid value HH.
    7mTo display minute of hour (0-59). Valid value mm.
    8sTo display second of minute (0-59). Valid value ss.
    9STo display milliseconds of minute (0-999). Valid value SSS.
    10ETo display Day in week (e.g Monday, Tuesday etc.)
    11DTo display Day in year (1-366).
    12FTo display Day of week in month (e.g. 1st Thursday of December).
    13wTo display Week in year (1-53).
    14WTo display Week in month (0-5)
    15aTo display AM / PM
    16kTo display Hour in day (1-24).
    17KTo display Hour in day, AM / PM (0-11).
    18zTo display Time Zone.

    Example

    In this example, we’re formatting dates based on different patterns.

    Open Compiler

    importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassI18NTester{publicstaticvoidmain(String[] args)throwsParseException{String pattern ="dd-MM-yy";SimpleDateFormat simpleDateFormat =newSimpleDateFormat(pattern);Date date =newDate();System.out.println(simpleDateFormat.format(date));
    
    
      pattern ="MM-dd-yyyy";
      simpleDateFormat =newSimpleDateFormat(pattern);System.out.println(simpleDateFormat.format(date));
      pattern ="yyyy-MM-dd HH:mm:ss";
      simpleDateFormat =newSimpleDateFormat(pattern);System.out.println(simpleDateFormat.format(date));
      pattern ="EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
      simpleDateFormat =newSimpleDateFormat(pattern);System.out.println(simpleDateFormat.format(date));}}</code></pre>

    Output

    It will print the following result.

    07-06-24
    06-07-2024
    2024-06-07 16:04:40
    Friday June 2024 16:04:40.866+0530
    
  • DateFormatSymbols Class

    Using DecimalFormatSymbols class, the default separator symbols, grouping separator symbols etc. can be changed. Following example is illustrating the same.

    Example

    Open Compiler

    importjava.text.DecimalFormat;importjava.text.DecimalFormatSymbols;publicclassI18NTester{publicstaticvoidmain(String[] args){String pattern ="#,###.###";double number =126473.4567;DecimalFormat decimalFormat =newDecimalFormat(pattern);System.out.println(decimalFormat.format(number));DecimalFormatSymbols decimalFormatSymbols =newDecimalFormatSymbols();
    
      decimalFormatSymbols.setDecimalSeparator(';');
      decimalFormatSymbols.setGroupingSeparator(':');
      decimalFormat =newDecimalFormat(pattern, decimalFormatSymbols);System.out.println(decimalFormat.format(number));}}</code></pre>

    Output

    It will print the following result.

    126,473.457
    126:473;457