top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Format Specifiers in java

0 votes
923 views

Format Specifiers

Whenever an output is to be displayed on the screen, it needs to be formatted. The formatting can be done with the help of format specifiers in java. The printf() method introduced in J2SE 5.0 can be used to format the numerical output to the console.

 

The table lists some of the format specifiers in java.

Format Specifier

Description

%d

Result formatted as a decimal integer

%f

Result formatted as a real number

%o

Result formatted as an octal number

%e

Result formatted as a decimal number in scientific notation

%n

Result is displayed in a new line

 

 

 

The code snippet demonstrates the use of various format specifiers.

int i = 55/22;

//decimal integer

System.out.printf (“55/22 = %d %n”,i);

// pad with zeros

double q = 1.0/2.0;

System.out.printf (“1.0/2.0 = %09.3f %n”, q);

//Scientific notation

q = 5000.0 / 3.0;

System.out.printf (“-10.0/0.0= %7.2e %n”, q);

Scanner Class

 The scanner class allows the user to read values of various types. To use the scanner class, pass the InputStream object to the constructor as shown below.

Scanner input = new scanner (System.in);

Here, input is an object of scanner class and, System.in is an input stream object. The table shows the different methods of the scanner class that can be used to accept numerical values from the user.

Method

Description

nextByte()

Returns the token as a byte value

nextInt()

Returns the next token as an int value

nextLong()

Returns the next token as a long value

nextFloat()

Returns the next token as a float value

nextDouble()

Returns the next token as a double value

 

 

 

Escape Sequences           

An escape sequence is a special sequence of characters that is used to represent characters, which cannot be entered directly into a string. For example, to include tab spaces or a new line character in a line or to include characters which otherwise have a different connotation in a java program (such as \ or “), escape sequences are used. An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way. The output displayed by java can be formatted with the help of escape sequence characters.

The table displays the various escape sequences in java.

Escape Sequence

Description

\b

Backspace character

\t

Horizontal Tab Character

\n

New line character

\’

Single quote arks

\\

Backslash

\r

Carriage Return character

\”

Double quote marks

 

The code snippet demonstrates the use of escape sequence characters.

// use of tab and new line escape sequences System.out.println (“Java \t programming \n Language”) ;

// Printing Tom “Dick” Harry string           

System.out.println (“Tom \ “Dick\” Harry “);

Go through this video:-

posted Jun 22, 2017 by Rameshwar Singh

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Java Access specifiers

Java comes with four access specifiers namely, public, private, protected, and default. The details are as follows:

  • Public

The public access specifier is the least restrictive of all access specifiers. A field, method, or class declared public is visible to any class in a java application in the same package or in another package.

  • Private

The private access specifier is the most restrictive of all access specifiers. The private access specifier cannot be used for classes and interfaces as well as fields and methods of an interface. Fields and methods declared private cannot be accessed from outside the enclosing class. A standard convention is to declare all fields private and provide public accessor methods to access them. Thus when data is important, sensitive, and con not be shared with others, it is declared as private.

  • Protected

The protected access specifier is used with classes that share a parent-child relationship which is referred to as inheritance. The protected keyword cannot be used for classes and interfaces as well as fields and methods of an interface. Fields and methods declared protected in a parent or super class can be accessed only by its child or subclass in another packages. However, classes in the same package can also access protected fields and methods, even if they are not a subclass of the protected member’s class.

  • Default

The default access specifier is used when no access specifier is present. The default specifier gets applied to any class, field, or method for which no access specifier has been mentioned. With default specifier, the class, field, or method is accessible only to the classes of the same package. The default specifier is not used for fields and methods within an interface.

                                        Figure: Using Access Specifiers

Class A with four data members having public protected, default, and private access specifiers. Class B is a child class of A and class C is another class belonging to the same package, Package1. From the figure it is clear that they belong to the same package.

The package, package2 consists of classes D and E. Class D can only access the public members of class A. However, class E can access public as well as protected members of class A even though it belongs to another package. This is because class E is a child class of A. However, none of the classes B,C,D, or E can access the private members of class A.

Access Specifier

Class

Package

Subclass

World

public

Y

Y

Y

Y

Protected

Y

Y

Y

N

No modifier (default)

Y

Y

N

N

Private

Y

N

N

N

                                                   Table: Access Levels of Access Specifiers

The first column states whether the class itself has access to its own data members. As can be seen, class can always access its own members. The second column states whether classes within the same package as the owner class (irrespective of their parentage) can access the member. As can be seen, members can be accessed except private members.

The third column states whether the subclasses of a class declared outside this package can access a member. In such cases, public and protected members can be accessed. The fourth column states whether all classes can access a data member.

READ MORE

Standard Date and Time Format Specifiers

 A Date and time format specifier is a special character that enables you to display the date and time values in different formats. For example, you can display a date in mm-dd-yyyy format and time in hh:mm format. If you are displaying  GMT time as the output, you can display the GMT time along with the abbreviation GMT using date and time format specifiers.

The date and time format specifiers allow you to display the date and time and time in 12-hour and 24-hour formats.

The following is the syntax for date and time format specifiers.

Console.WriteLine(“{format specifier}”, <datetime object>);

Where,

Format specifier: Is the date and time format specifier.

Datetime object: Is the object of the DateTime class.

Some Standard date and time specifiers are used in the Console.WriteLine() method with the datetime object. To create the datetime object, you must create an object of the DateTime class and initialize it. The formatted date and time are always displayed as string in the console window.
                                                                                                      

 

The table shown below displays some of the standard date and time format specifiers in C#.

Format Specifier

Name

Description

  D

Long date

Displays date in long date pattern. The default format is “dddd*, MMMM*, dd, yyyy”.

  d

Short date

Displays date in short date pattern. The default format is “mm/dd/yyyy”

  f

Full date/time (short time)

Displays date in long date and short time patterns,, separated by a space. The default format is “dddd*”, MMMM* dd, yyyy HH*:mm*”.

  F

Full date/time (long time)

Displays date in long date and long time patterns, separated by a space. The default format is “dddd*, MMMM* dd,,yyyy HH*: mm*: ss*”.

  G

General date/time (short time)

Displays date in short date and short time patterns, separated by a space. The default format is “MM/dd/yyyy  HH*:mm*”.

 

The following snippet demonstrates the conversion of a specified date and time using the d,D,f,F and g date and time format specifiers:-

DateTime dt =  DateTime.Now;

//Returns short date (MM/DD/YYYY)

Console.WriteLine("Short date format (d): {0:d}",dt);

//Returns long date (Day, Month Date, Year)

Console.WriteLine("Long date format (D) : {0:D}", dt);

//Returns full date with time and without seconds

Console.WriteLine("Full date with time without seconds (f) : {0:f}", dt);

//Returns full date with time and with seconds

Console.WriteLine ("Full date with time with seconds (F) : {0:F}", dt);

//Returns short date and short time without seconds

Console.WriteLine ("Short date and short time without seconds (g) : {0:g}", dt);

 

Output:

Short date format (d) : 23/06/2017

Long date format  (D) : Friday, June 23, 2017

Full date with time without seconds (f) : Friday, June 23, 2017 11:12 AM

Full date with time with seconds (F): Friday, June 23, 2017 11:12:34 AM

Short date and short time without seconds (g): 23/06/2017 11:12 AM

 

More Standard Date and Time Format Specifiers

Format Specifier Name   Description
  G General date/time (long time)  Displays date in short date and long time patterns, separated by a space. The default format is "MM/dd/yyyy HH*:mm*:ss*".
 m or M Month day Displays only month and day of the date.The default format is "MMMM* dd".
  tShort time Displays time in short time pattern.The default format is "HH*:mm*".
  TLong time Displays time in long time pattern. The default format is "HH*:mm*:ss*".
 y or YYear month pattern Displays only month and year from the date.he default format is "YYYY MMMM*".
   

 

The following snippet demonstrates the conversion of a specified date and time using the G,m,t,T :-

DateTime dt = DateTime.Now;

//Returns short date and short time with seconds

Console.WriteLine ("Short date and short time with seconds (G) : {0:G}",dt);

//Returns month and day -M can also be used 

Console.WriteLine ("Month and day (m) : {0:m}", dt);

//Returns short time 

Console.WriteLine("Short time (t) : {0:t}", dt);

 

//Returns short time with seconds

Console.WriteLine("Short time with seconds (T) : {0:T}", dt);

//Returns year and month -Y also can be used 

Console.WriteLine ("Year and Month (y): {0:y}" dt);

Output:

Short date and short time with seconds (G): 23/06/2017 11:40:55 AM

Month and day (m) : June 23

Short time (t) : 11:40 AM

Short time with seconds (T): 11:40:55 AM

Year and Month (y): June , 2017 

READ MORE

Define Numeric Format specifiers

Format specifiers are special characters that are used to display values of variables in a particular format. For example, you can display an octal value as decimal using format specifiers.

In C#, you can convert  numeric values in different  formats. For example, you can display a big number in an exponential form. To convert numeric values using numeric format specifiers, you should enclose the specifier in curly braces. These curly braces must enclosed in double quotes. This is done in the output methods of the console class.

The following is the syntax for the numeric format specifier

Console.WriteLine(“(format specifier)”, variable name>);

Where,

Format specifier: Is the numeric format specifier.

Variable name: Is the name of the integer variable.

Some Numeric Format Specifiers

Numeric format specifiers work only with numeric data . A numeric format specifier can be suffixed with digits. The digits specify the number of zeros to be inserted after the decimal location. For example, if you use a specifier such as c3, three zeros will be suffixed after the decimal location of the given number.

Format Specifier

Name

Description

C or c

Currency

The number is converted to a string that represents a currency amount.

D or d

Decimal

The number is converted to a string of decimal digits (0-9), prefixed by a minus sign is case the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. This format is supported for fundamental types only.

E or e

Scientific (Exponential)

The number is converted to a string of the form “-d.ddd…e+ddd”, where each ‘d’ indicates a digit (0-9).

 

The following snippet demonstrates the conversion of a numeric value using C,D and E format specifiers.

int  num =456;

console.WriteLine (“{0:C}”, num);

Console.WriteLine (“{0:D}”, num);

Console.WriteLine (“{0:E}”), num);

Output:

$456.00

456

4.560000E+002

Format Specifier

Name

Description

F or f

Fixed-point

The number is converted to a string of the fomr “-ddd.ddd…” where each ‘d’ indicates a digit (0-9). If the number is negative, the string starts with minus sign.

N or n

Number

The number is converted to a string of the form “-d,ddd,ddd.ddd…”. If the number is negative the string starts with a minus sign.

X or x

Hexadecimal

The number is conveted to a string of hexadecimal digits. Uses “X” to produce “ABCDEF”, AND “x” to produce “abcdef”.

 

The following snippet demonstrates the conversion of the numeric value using F, N and X format specifiers.

int num =456;

Console.WriteLine(“{0:F}”, num);

Console.WriteLine(“{0:N}”, num);

Console.WriteLine(“{0:X}”, num);

Output

456.00

456.00

1CB

READ MORE
...