Meta tags:
description= The 8 primitive data types in Java with sizes, ranges, defaults and literals, plus overflow, float precision, casts and wrapper classes, on Java 25.;
author= Lokesh Gupta;
Headings (most frequently used words):
primitive, types, java, and, type, ez, toc, in, font, data, is, integer, the, ezw_tco, color, char, boolean, of, size, weight, widget, container, ul, list, li, 16, access, sizes, ranges, defaults, what, byte, short, int, long, floating, point, float, double, default, values, converting, between, wrapper, classes, faqs, 10, conclusion, 11, references, leave, comment, basics, title, 15px, 500, 3d3d3d, 13px, 400, 7a7a7a, active, background, ffffff, table, contents, literals, overflow, precision, errors, infinity, nan, division, by, zero, characters, outside, bit, range, widening, conversions, narrowing, casts, numeric, promotion, expressions, string, how, much, memory, does, take, why, bits, can, variable, be, null, which, should, we, use, for, big, numbers, jpa, field, vs, property, mixed, mode, introduction, to, programming, language, about, us, tutorial, series, meta, links, our, blogs, follow, on,
Text of the page (most frequently used words):
the (185), and (108), int (87), java (52), double (45), types (42), integer (42), value (41), byte (40), type (39), primitive (38), #boolean (36), for (33), char (33), float (30), #values (27), long (27), not (26), with (21), bits (21), that (19), when (19), such (19), use (17), short (16), has (16), variable (15), wrapper (14), number (14), false (14), stock (14), default (13), from (13), cast (13), numbers (12), does (12), string (12), data (12), range (12), math (12), every (12), one (12), two (12), product (12), can (11), null (11), error (11), character (11), overflow (10), class (10), object (10), conversion (10), true (10), decimal (10), only (10), max_value (10), about (9), which (9), classes (9), widening (9), point (9), are (9), negative (9), into (9), size (9), each (9), literal (9), bit (8), zero (8), reference (8), system (8), never (8), code (8), array (8), store (8), result (8), new (8), min_value (8), digits (8), numeric (7), characters (7), literals (7), line (7), before (7), binary (7), keeps (7), exact (7), bigdecimal (7), compiler (7), unicode (7), 127 (7), arithmeticexception (7), positive (7), also (6), field (6), nan (6), precision (6), floating (6), variables (6), jls (6), wrong (6), without (6), whole (6), stores (6), fit (6), than (6), holds (6), form (6), shows (6), large (6), stocks (6), sum (6), cannot (6), escape (6), 255 (6), narrowing (5), between (5), outside (5), infinity (5), errors (5), jvm (5), exception (5), but (5), must (5), goes (5), most (5), small (5), methods (5), throw (5), eight (5), 128 (5), get (5), example (5), counter (5), 300 (5), last (5), needs (5), out (5), println (5), price (5), rating (5), u0000 (5), need (5), sizes (5), how (4), lokesh (4), gupta (4), memory (4), take (4), casts (4), conversions (4), division (4), pass (4), equals (4), other (4), february (4), 2016 (4), works (4), its (4), local (4), compare (4), limits (4), them (4), per (4), gives (4), hold (4), objects (4), map (4), stockbyitem (4), throws (4), add (4), format (4), lossy (4), views (4), grade (4), defaults (4), instock (4), smiley (4), length (4), notanumber (4), suffix (4), all (4), 2026 (3), language (3), next (3), references (3), big (3), why (3), method (3), unsigned (3), fields (3), instead (3), money (3), multiplyexact (3), utf (3), always (3), rejects (3), stored (3), section (3), uffff (3), single (3), element (3), flags (3), quotes (3), operator (3), makes (3), large1 (3), large2 (3), same (3), larger (3), ones (3), banana (3), unboxing (3), converts (3), called (3), back (3), arithmetic (3), return (3), reports (3), nearest (3), round (3), 2147483647 (3), smaller (3), lowest (3), digit (3), 120 (3), because (3), score (3), have (3), active (3), name (3), emoji (3), more (3), accepts (3), tab (3), notice (3), write (3), four (3), plain (3), integral (3), isnan (3), 30000000000000004 (3), calculation (3), bytes (3), significant (3), 1000 (3), too (3), 2147483648 (3), fits (3), 32767 (3), copy (3), examples (3), ranges (3), twitter (2), github (2), follow (2), tutorial (2), interview (2), related (2), technologies (2), introduction (2), access (2), conclusion (2), should (2), much (2), faqs (2), promotion (2), expressions (2), converting (2), what (2), table (2), endian (2), exe (2), static (2), statements (2), comments (2), jdk (2), basics (2), may (2), results (2), run (2), html (2), sangeetha (2), explicit (2), any (2), comment (2), source (2), javadoc (2), elements (2), assigned (2), collection (2), whereas (2), sums (2), comparisons (2), returning (2), fixed (2), fractions (2), unit (2), limit (2), both (2), where (2), missing (2), count (2), 536 (2), since (2), above (2), set (2), flag (2), like (2), small1 (2), small2 (2), returns (2), safe (2), getordefault (2), nullpointerexception (2), shop (2), reads (2), item (2), list (2), autoboxing (2), first (2), while (2), wraps (2), around (2), total (2), operation (2), operands (2), tobyteexact (2), check (2), 200 (2), fractional (2), part (2), becomes (2), lost (2), lose (2), read (2), counts (2), following (2), specification (2), 65535 (2), app (2), 100 (2), twice (2), octal (2), letter (2), quote (2), feed (2), cover (2), plus (2), hex (2), smallest (2), 324 (2), try (2), peritem (2), catch (2), getmessage (2), equal (2), itself (2), difference (2), fraction (2), arrays (2), possible (2), uses (2), checked (2), they (2), 30l (2), milliseconds (2), program (2), 9223372036854775807 (2), level (2), 32768 (2), file (2), content (2), covers (2), many (2), groups (2), samearray (2), copying (2), through (2), three (2), max (2), spring (2), menu (2), search, copyright, sitemap, facebook, linkedin, rest, api, our, blogs, privacy, policy, contact, advertise, meta, links, python, typescript, logging, maven, regex, oop, series, shares, best, practices, algorithms, solutions, frequently, asked, questions, provides, tutorials, guides, howtodoinjava, programming, jpa, property, mixed, mode, previous, portfolio, fun, loving, family, man, passionate, computers, problem, solving, over, years, experience, avid, sci, movie, enthusiast, fan, christopher, nolan, quentin, tarantino, contents, little, generate, bytecode, javaw, immutable, hashcode, import, properties, block, statement, command, args, main, operators, control, flow, classpath, jre, naming, conventions, hello, world, installation, closed, despite, fact, underflow, loss, information, occur, time, https, docs, oracle, com, javase, specs, se7, then, negtive, typecasting, assisgn, datatype, using, showing, leave, happy, learning, dev, jvms, contexts, start, boxes, watch, wrappers, bugs, come, their, give, carry, platform, upper, slower, requires, biginteger, optional, age, optionalint, was, designed, early, 1990s, had, fewer, were, enough, grew, later, specifications, fix, hotspot, util, bitset, package, special, support, look, lang, parsing, convert, parseint, samesmall, cached, samelarge, equallarge, fails, cache, apple, crash, arraylist, collections, generics, work, compile, compound, contains, hidden, left, side, compiles, 310, tointexact, did, comes, quantity, want, call, places, fromint, fromlarge, 70_000, 4464, truncated, clamped, 1e10, fromnan, rounded, drops, rounds, toward, 16_777_217, 6777216e7, 16777216, magnitude, 777, 216, widens, bigstock, asdouble, fromchar, happens, assignment, parameter, arrow, dashed, arrows, this, step, opposite, direction, might, been, initialized, checks, stops, otherwise, creates, setting, created, starts, define, says, canship, converted, conditional, done, conditions, loops, unlike, treats, truth, ud83d, ude00, codepoints, codepointcount, maxchar, smiling, face, surrogate, pair, chat, messages, points, added, space, ending, escapes, easier, 101, text, blocks, backslash, carriage, backspace, sequences, inside, turns, addition, fromunicode, fromcode, plusone, takes, well, uxxxx, floatmin, floatmax, 4028235e38, doublemin, doublemax, 7976931348623157e308, meaning, behaves, differently, nanequals, anything, even, test, case, these, hurt, adds, invoice, print, amounts, create, strings, after, tolerance, close, abs, way, show, extra, costs, sense, vertex, model, distance, 5e3, 1500, third, 33333334, thirdd, 3333333333333333, spends, sign, exponent, position, separately, ieee, 754, except, rare, cases, checksum, another, divideunsigned, tounsignedstring, unnoticed, addexact, 1702967296, right, 2592000000, say, subscription, computes, day, trial, period, expression, multiplies, overflows, writing, intmin, intmax, longmax, intbits, longbytes, constants, ourselves, 150, incompatible, there, 0xff, 0377, 0b1111_1111, population, 8_100_000_000l, 8100000000, medium, 30_000, systems, make, readable, underscores, uppercase, lowercase, looks, timestamps, save, uploaded, billion, complement, standard, signed, differ, far, applies, specified, 8e308, 4e38, 9223372036854775808, lists, will, see, fall, stands, alone, seven, copies, independent, change, visible, splits, built, named, interface, enum, address, reserved, keyword, sections, lines, past, maximum, minimum, year, 2_147_483_647, 9_000_000_000l, wrapped, narrowed, declares, surprise, developers, counters, prices, loop, indexes, yes, less, defines, operating, namely, october, casting, rules, tested, junit, hibernate, boot, skip,
Text of the page (random words):
types fall into two groups the boolean type stands alone and the other seven are numeric types the numeric types are the integral types byte short int long and char and the floating point types float and double char is an integral type in java so we can do arithmetic on it while boolean is not a number at all the table lists the size the default value of a field and the range of each type a primitive type also has a wrapper class which we need when the value goes into a collection as we will see in section 8 type size default fields range wrapper class byte 8 bits 0 128 to 127 byte short 16 bits 0 32768 to 32767 short int 32 bits 0 2147483648 to 2147483647 integer long 64 bits 0l 9223372036854775808 to 9223372036854775807 long float 32 bits 0 0f about 1 4e 45 to 3 4e38 positive or negative float double 64 bits 0 0d about 4 9e 324 to 1 8e308 positive or negative double char 16 bits u0000 u0000 to uffff 0 to 65535 character boolean not specified false true or false boolean the default value applies only to fields and array elements local variables have no default as section 6 shows 2 integer types byte short int and long the four integer types store whole numbers in two s complement form the standard binary form for signed numbers so each type covers as many negative values as positive ones plus zero the types differ only in size and each type has twice the bits of the type before it so long covers far more values than int we use int for whole numbers by default and long when the value can pass about 2 1 billion such as file sizes in bytes or timestamps in milliseconds the types byte and short save memory only in large arrays for example a byte that holds the content of an uploaded file 2 1 integer literals a whole number in the source code such as 255 is an int literal we add the suffix l to write a long literal and the compiler rejects an int literal outside the int range with the error integer number too large we always use an uppercase l because a lowercase l looks like the digit 1 we can write a literal in four number systems and use underscores between digits to make long numbers readable int decimal 255 255 int hex 0xff 255 int octal 0377 255 int binary 0b1111_1111 255 long population 8_100_000_000l 8100000000 byte small 100 fits 128 to 127 short medium 30_000 fits 32768 to 32767 there are no byte or short literals the compiler accepts an int literal for a byte or short variable when the value fits in the range and reports an error when it does not byte level 150 error incompatible types possible lossy conversion from int to byte the wrapper classes hold the limits and sizes as constants so we never need to type the numbers ourselves int intmin integer min_value 2147483648 int intmax integer max_value 2147483647 long longmax long max_value 9223372036854775807 int intbits integer size 32 int longbytes long bytes 8 2 2 integer overflow when the result of an integer operation does not fit in the type java keeps the lowest bits of the result and throws no exception so integer max_value 1 becomes integer min_value and the program goes on with a wrong number say a subscription app computes a 30 day trial period in milliseconds all the numbers in the expression are int literals so java multiplies them as int values and the result overflows before it is stored in the long variable writing the first number as 30l makes the whole calculation a long calculation int wrong 30 24 60 60 1000 1702967296 overflow long right 30l 24 60 60 1000 2592000000 when a wrong value must never pass unnoticed we use the exact arithmetic methods of the math class such as math addexact and math multiplyexact they throw an arithmeticexception on overflow instead of returning a wrong value try int checked math multiplyexact 30 24 60 60 1000 system out println checked catch arithmeticexception e system out println too large for int e getmessage too large for int integer overflow java has no unsigned integer types except char for the rare cases that need one such as a checksum from another system the classes integer and long have methods such as integer tounsignedstring and integer divideunsigned 3 floating point types float and double the types float and double store numbers with a fractional part such as 19 99 in the ieee 754 binary format the format stores the significant digits and the position of the decimal point separately so the point can float a float uses 32 bits and keeps about 6 to 7 significant decimal digits whereas a double uses 64 bits and keeps about 15 to 16 digits a float spends 1 bit on the sign 8 bits on the exponent and 23 bits on the fraction which limits it to about 7 significant digits a decimal literal such as 19 99 is a double for a float literal we add the suffix f and without it the compiler reports possible lossy conversion from double to float float rating 4 5f 4 5 double price 19 99 19 99 double distance 1 5e3 1500 0 float third 1 0f 3 0 33333334 double thirdd 1 0 3 0 3333333333333333 we use double for decimal numbers by default the extra precision costs only 4 more bytes per value and the math methods take and return double a float makes sense in large arrays for example the vertex data of a 3d model 3 1 precision errors the binary format cannot store most decimal fractions without a small error in the same way that 1 3 has no exact decimal form the value 0 1 is stored as the nearest binary fraction so small errors show up in sums and comparisons double sum 0 1 0 2 0 30000000000000004 boolean equal sum 0 3 false boolean close math abs sum 0 3 1e 9 true so we never compare double values with after a calculation to compare float and double values we check that the difference is smaller than a tolerance as the last line shows money is the case where these errors hurt most a shop that adds 0 10 and 0 20 to an invoice must print 0 30 not 0 30000000000000004 so we store amounts as bigdecimal and create them from strings bigdecimal total new bigdecimal 0 10 add new bigdecimal 0 20 0 30 3 2 infinity nan and division by zero a floating point division by zero does not throw an exception the result is positive or negative infinity and 0 0 0 gives nan not a number the value nan is not equal to anything not even to itself so we test it with double isnan double positive 1 0 0 infinity double negative 1 0 0 infinity double notanumber 0 0 0 nan boolean nanequals notanumber notanumber false boolean isnan double isnan notanumber true an integer division by zero behaves differently and throws an arithmeticexception try int peritem 10 0 system out println peritem catch arithmeticexception e system out println e getmessage by zero notice the meaning of min_value for the floating point types float min_value and double min_value are the smallest positive values not the most negative ones the most negative double is double max_value float floatmin float min_value 1 4e 45 smallest positive value float floatmax float max_value 3 4028235e38 double doublemin double min_value 4 9e 324 double doublemax double max_value 1 7976931348623157e308 4 the char type a char is a 16 bit unsigned integer that holds one utf 16 code unit which is one character of the unicode set from u0000 to uffff since char is an integral type every character also has a numeric code such as 65 for a we write a char literal in single quotes a unicode escape uxxxx takes four hex digits and the compiler accepts a plain number in the char range as well char letter a a char fromunicode a a char fromcode 66 b int code a 65 char next char a 1 b int plusone a 1 66 char tab t tab character notice the cast in char a 1 java turns both operands into int before the addition so the result is an int and we need the cast to store it in a char the escape sequences cover the characters that we cannot type inside quotes java has eight of them plus the unicode escape escape character b backspace t tab n line feed new line f form feed r carriage return double quote single quote backslash java 15 added s a space and a line ending escape for text blocks java also accepts octal escapes such as 101 the letter a but the unicode escape is easier to read 4 1 characters outside the 16 bit range unicode has more than 65 536 characters so one char cannot hold every character an emoji such as the smiling face needs two char values a surrogate pair a chat app that limits messages to 100 characters with length counts each emoji twice so we count code points instead string smiley ud83d ude00 one emoji int length smiley length 2 two char values int codepoints smiley codepointcount 0 smiley length 1 int maxchar character max_value 65535 5 the boolean type the boolean type has two values true and false conditions in if statements and loops must be boolean so java unlike c never treats 0 or 1 as a truth value we cannot cast a boolean to a number or a number to a boolean the compiler rejects the cast int done with the error boolean cannot be converted to int so we use the conditional operator when we need a number int stock 3 boolean instock stock 0 true boolean canship instock stock 5 false int flag instock 1 0 1 the jls does not define the size of a boolean the jvm specification says that the jvm works on boolean values as int values and stores a boolean array as a byte array with 8 bits per element 6 default values of primitive types java gives every field and every array element a default value when the object or array is created the default is zero for the numeric types u0000 for char and false for boolean a reference field such as a string starts as null the following example creates a product object without setting any field and reads the defaults class product int stock long views double price float rating char grade boolean active string name product product new product int stock product stock 0 long views product views 0 double price product price 0 0 float rating product rating 0 0 int grade product grade 0 u0000 boolean active product active false string name product name null boolean flags new boolean 3 false false false int counts new int 3 0 0 0 local variables get no default value the compiler checks that a local variable is assigned before every read and stops with an error otherwise int score system out println score error variable score might not have been initialized 7 converting between primitive types java converts a value to a larger type without a cast because no value is lost this step is called a widening conversion the opposite direction is a narrowing conversion and it needs an explicit cast because the value may not fit every arrow is a widening conversion that needs no cast but the dashed arrows to float and double can lose precision 7 1 widening conversions a widening conversion happens on assignment and when we pass a value to a method parameter of a larger type int stock 120 long bigstock stock 120 widening double asdouble stock 120 0 widening int fromchar a 65 widening widening keeps the magnitude of the value but not always every digit a float has 24 bits for the digits so an int above 16 777 216 can lose its last digits when java widens it to float int exact 16_777_217 float lossy exact 1 6777216e7 lost the last digit int back int lossy 16777216 7 2 narrowing casts a cast to a smaller integer type keeps only the lowest bits of the value a cast from double to an integer type drops the fractional part it rounds toward zero and a value outside the range becomes the nearest limit byte fromint byte 200 56 short fromlarge short 70_000 4464 int truncated int 3 99 3 int negative int 3 99 3 int clamped int 1e10 2147483647 int fromnan int double nan 0 long rounded math round 3 99 4 when we want the nearest whole number we call math round as the last line shows to round to n decimal places we use bigdecimal or string format a cast never reports that the value did not fit when the value comes from outside such as a quantity from a form we check the range before the cast and throw an exception static byte tobyteexact int value if value byte min_value value byte max_value throw new arithmeticexception value does not fit in a byte return byte value byte safe tobyteexact 300 arithmeticexception 300 does not fit in a byte for long to int the jdk has math tointexact which throws an arithmeticexception on overflow 7 3 numeric promotion in expressions java does arithmetic on int long float and double only before an operation java converts byte short and char operands to int so the sum of two byte values is an int byte a 10 byte b 20 int sum a b 30 byte byte is an int byte total byte a b 30 byte counter 10 counter 300 54 casts back to byte the compound operator contains a hidden cast to the type of the left side so counter 300 compiles while counter counter 300 does not and the result 310 wraps around to 54 8 primitive types and wrapper classes collections and generics work with objects only so a list int does not compile each primitive type has a wrapper class such as integer for int and java converts between the two for us the conversion from int to integer is called autoboxing and the conversion back is called unboxing list integer stocks new arraylist stocks add 5 autoboxing int integer int first stocks get 0 5 unboxing a wrapper variable can be null and unboxing a null throws a nullpointerexception for example a shop reads the stock of an item from a map and the item is not in the map the method get returns null so we use getordefault when the result goes into a primitive variable map string integer stockbyitem map of apple 5 integer missing stockbyitem get banana null int safe stockbyitem getordefault banana 0 0 int crash stockbyitem get banana nullpointerexception we also compare wrapper objects with equals never with the integer cache returns the same object for values from 128 to 127 so works for small values and fails for larger ones integer small1 127 integer small2 127 integer large1 128 integer large2 128 boolean samesmall small1 small2 true cached object boolean samelarge large1 large2 false two objects boolean equallarge large1 equals large2 true the wrapper classes also hold the parsing methods such as integer parseint which we use to convert a string to an int 9 primitive data types faqs 9 1 is string a primitive data type in java no string is a class in the java lang package so a string variable holds a reference java gives string special support such as literals in double quotes and the operator which makes it look like a primitive type 9 2 how much memory does a boolean take the java specifications do not fix the size the jvm works on single boolean values as 32 bit int values and hotspot stores a boolean field in one byte and a boolean array with one byte per element for a large set of flags java util bitset stores one bit per flag 9 3 why is char 16 bits in java java was designed in the early 1990s when unicode had fewer than 65 536 characters so 16 bits were enough for every character unicode grew later and since java 5 characters above uffff are stored as two char va...
|