0% found this document useful (0 votes)
13 views

Text, Date, Time and Numeric Objects Part 1 (Transcript)

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Text, Date, Time and Numeric Objects Part 1 (Transcript)

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Let's take a look at how Java handles text, date, time, and numeric objects.

In this particular less


on, we're examining how can we handle text values, not just individual chars-- primitive chars-- b
ut actual text, multiple characters, using classes such as String and StringBuilder. So we're starti
ng the cases for using String and StringBuilder.
Then we're looking at different primitive wrapper classes. So for every primitive like int, byte, shor
t, whatever, we have a wrapper class that represents the primitive value as an actual object. So
we look at that and why do we use primitives and what's the point of that.
And also we look at a conversion between text and primitive types. You know, when the user, for
example, types in some text and you
want to express it within Java as a number. Or vise versa-- if you've got some number maybe an
d you want to output it to the user as text, right?
We also look at an interesting class which is specifically designed to handle decimal math in Jav
a. It's called BigDecimal. There's another one called BigInteger. But basically, as you're probably
aware, the primitives are not necessarily decimal, right?
So they handle numeric operations-- that could be binary, octal, hex, whatever, yeah? But big de
cimal is a class
that's specifically designed to cater for decimal math, and it may be handy for us to do that.
And also, we'll look at ways in which we express date and time values. And finally, because we d
eal with the ways in which different numbers and dates are represented as text, then we need to
think of localization. Because the way you represent number as text depends on the language an
d the country, and so is dates. So we have to consider formatting and localization topics.
And that should cover really all the basic types that you usually use in business programming. Yo
u
know, text, numbers, and dates, right? This is kind of the core of any business logic of the applic
ation, I guess.
So first, let's start with a string. String is a class that represents a sequence of characters. Not jus
t one char as a char primitive, but a sequence of characters. It's a class that's not a primitive.
Thus it actually has more to it than simply holding a value, like a primitive state. So you could inv
oke various operations upon a string. It has different functions that you could utilize to handle the
behaviors of the text.
Just like any other object, string can be instantiated using a new operator. It can create an instan
ce of string using the new operator. However, actually advised not to do it. String has a unique o
wn way of being initialized by simply typing text enclosed in double quotes. So that piece of text e
nclosed in double quotes. It's actually a recommended approach.
And the reason why it's recommended approach-- well, it has to do with the way strings are alloc
ated in Java memory. Apparently, Java virtual machine performs some optimization around string
handling. And that is, it's called string internment.
And the idea is that Java virtual machine will try to maintain a single copy of a string literal, and th
en use that single copy of a string literal from different places in a program. There's a special are
a of memory called String Pool where these string literal constants are stored.
And you may reference the same string literal from different places in a program. You don't need
to recreate it over and over again. So for example, if I just say double quotes hello, that allocates
that hello text in that String Pool. If
I later say string a equals and I type the same text, actually it does not allocate memory for that t
ext again.
Instead, it simply references variable A to point to the same memory where the text has been pla
ced earlier. So it reuses the same text over and over again. So if you say b equals a, that will res
ult in b referencing exact same memory as the a variable. c equals hello again. They all point to t
he same memory chunk that contains that text.
You can use new operator with a string. For example, you can create a char array. We'll study ar
rays later, so never mind the syntax. But yeah, OK, you can create a
char array. And then you can initialize string as using an array of characters.
Or you can use new operator, new string around the double quoted text, yeah? Whichever way.
That switches these two new operators, essentially switch off the internment. They will allocate n
ew memory containing the text, rather than reference previous memory that contain the text.
You can call intern operation, which will basically create a version of a string which is interned. S
o if you are using the inter operations, that basically means that the variable c and d are actually
pointing to the same string object, rather than to two different string objects, because they can sh
are, right?
It's
the same text. It's the word hello, right? So you have to be kind of mindful about it. This is a mem
ory optimization. If in two different places in a program you need exactly the same string literal, w
hy allocate it twice? You know, what's the point?
You may say, well, what if I try to modify it in some way, yeah? What if I try to change it? Well, th
at's kind of interesting question, right? Because apparently, as we'll find out from the next page, s
tring objects cannot be changed. They are immutable.
When you create a certain text-- when you allocate that memory to contain the text-- that string lit
eral is never changed ever. Any attempt to modify it-- every time you call some operation and yo
u say, you know, concatenate, subtract, substring, whatever, yeah? So any attempt to change it
will basically result in the creation of another string. The original memory that contained the origin
al string literal will not be affected in any way.
So that's why the string can actually be shared by different variables, because it's reliable, it's ess
entially mutable, it never changes. Any attempt to change it will just create a new one. So operati
ons such as, for example, trim, concat, lowercase, uppercase, and so on-- any operations on a st
ring never modify the actual original.
They always create a new copy, which is modifying text. But it will be an independent memory ar
ea with an independent value in it. So trim, for example, trims the leading
and trailing spaces. Concat was a continuation of two strings.
Actually, instead of concat, you can use a plus sign. It works exactly the same. No difference at a
ll whatsoever. So you can say a.concat World or a plus World. Doesn't matter. They basically ref
erence the exact same case, where Hello World is concatenated together, that produce the same
result.
You can reassign string references as much as you like. For example, in this case, here's String
a, which equals Hello. And there's some leading and trailing spaces. And then you trim. So obvio
usly, you produce a new string technically-- completely new string-- which has no leading and trai
ling spaces.
But then you can take that new string and assign it back to variable a. So a now references the v
alue of Hello with no spaces in front and behind. That did not destroy the original value. That still
is present in the String Pool-- the Hello with spaces.
If nothing references it, it eventually will be gone because it's eligible for garbage collection. But
we'll talk about it later. But the point is, the original value technically isn't really immediately gone.
You just simply say, now a references some other string. But the original string still stays in a stri
ng pool until it's cleaned out from memory at some later stage, if nothing references that string an
ymore.
So you could perform conversions to lower
or uppercase. Just basically produce a new string, but in different case. There's some other functi
ons like contains, for example. So you can check if
a String d contains the letter W, and if true or false.
Well, in this case, false, because it's uppercase W. And obviously, after you convert it to lowerca
se, and that's lowercase w. Please note that the variable c still references the mixed case string,
yeah? When you call c.toLowerCase, c is still referencing whatever it was referencing.
It's the d string that's referenced the lowercase equivalent. Could you reassign c here instead of
declaring new variable d? Yeah, you could have. You could have done the
same trick as was done here when you trimmed a. You could have reassigned variable c, sure. B
ut we declared a new variable d in this case. It's entirely up to you.
With a plus sign, you can get into a little bit of trouble if you think about it, because in the express
ion, what if you're doing plus as arithmetic and as concatenation? Well, the order of evaluation is
from left to right.
So if you've got the plus sign here, 1 plus 1, that would be arithmetic, because 1 and 1 are numb
ers, right? So it will be evaluated as 2. And then concatenate it with a string u. So that will be 2u,
right? And then if you do it
the other way around-- if the first plus here is concatenation, so that would produce u1. And then
you concatenate again with 1, so that would produce u11.
If you want it to be any other way, well, just use round brackets. Whatever is inside your braces
will be evaluated first, hence you change the order of precedence within that expression. So thes
e are the basics of string manipulation.
Now, string indexing. If you want to access specific characters within a string, you can. But you n
eed to know how they're indexed. The string index starts at 0. It's an integer index, and it basicall
y says, the first letter is at position 0. Second letter is position 1, et cetera.
You can find out how many letters you've got in a string in total by calling the method length. So t
hat tells you the number of positions, basically-- the number of characters. But remember, the las
t valid position is essentially length minus 1, because the counter started at 0, not at 1.
You can apply various operations to a string using these indexes. For example, substring, where
you can designate the beginning index and
the end index. Please note that a substring operation, the beginning is inclusive to the result, and
the end index is not inclusive to the result.
So for example, if you take the substring to
a length, you don't end up with an invalid index, because length, remember, is plus 1 to the last v
alid position. So the substring does not take the last position. That's kind of the idea.
So for example, in this case, from 0 to 5, I'm taking h, e, l, l, o, but I'm not taking the position 5. S
o substring from 0 to 5 results in the word Hello without taking that W into the result.
You can find out the occurrence of certain characters within a string using
an indexOf operation. So for example, indexOf o will look for the first occurrence of o, which is th
e position 4. If you tell indexOf to start looking from a certain position-- look for o starting at positi
on 5-- that will find the next occurrence of o, which is the position 6. So
it returns an integer position number.
There's a reverse of indexOf, which is lastIndexOf. It's doing the same thing, but starting at the e
nd rather than beginning. The lastIndexOf l is 8, and an indexOf l is 2. indexOf a character that is
not present within a string yields you the response of minus 1.
Well, you know, index starts from 0. So minus 1 clearly is an impossible index. So if you're lookin
g for a letter a in Hello World, well, there is no a in Hello World. So you get
minus 1 as an indicator of an absence of whatever you are looking for.
charAt a given position-- so charAt position 0 yields you H, for example. Length, as I say, it's the t
otal number of characters within a string. And what if you tried to do charAt, say, for example, po
sition 10, in this case? Well, length is 10, but the last valid position is 9. And trying to get beyond
the boundaries of that index-- beyond 0 to length minus 1-- will get you StringIndexOutOfBounds
Exception. Basically, if you have a problem, it will throw you an error.
OK, we'll talk about exception handling later. But for you to know, yeah, that's how you can easily
produce one, by not checking the boundaries of a string and just sort of wandering in with an inva
lid index position.
Now, string, as you probably observed already, is convenient. It has some basic text manipulatio
n operations. But it's immutable. So all of these different actions, like substring, for example, or tri
m or lowercase or uppercase, they always produce a new string, which may not be very efficient i
f you need to handle a significant volume of text with lots of different manipulations.
If you need to like manipulate, count, add, and remove characters and reposition stuff and things
like that. String will keep creating new string objects for you upon every attempt to update it, to ch
ange it in any way, because it's immutable. It's read-only.
So instead, because it's not particularly optimal-- flooding your memory with all these string objec
ts-- you may consider that for complex text manipulation cases, you would probably would like to
use a class that is not immutable.
An example that is StringBuilder. StringBuilder is basically a mutable equivalent of string. It kind
of behaves very similar to string. Actually, lots of operations are exactly the same. But StringBuild
er also gives you extra operations that string doesn't have, which actually modify the content.
So operations on StringBuilder don't produce new instances of StringBuilder. No, they modify tha
t particular instance of StringBuilder. StringBuilder can be initialized just as an empty StringBuilde
r object. If you do the empty initialization-- if you don't parameterize how you initialize StringBuild
er-- by default, it will create you a StringBuilder of 16 character capacity, but actually will out incre
ment as necessary.
So it will add more capacity to its internal storage as required. You may initialize the StringBuilder
with specific capacity. Again, it will grow beyond that capacity if needed. The capacity is purely tu
ning things.
So if you feel like you can predict the overall amount of text you need to put into it, to prevent me
mory rescaling, you better tell it. But if you get it wrong, that's not a problem. It will not fail you in
any way, except performance-wise, probably.
And of course, you can initialize StringBuilder with some predefined text. You can put kind of initi
al text into it as a string. Right, so it has some methods that are exactly the same as in string clas
s, like substring, indexOf, charAt. They kind of work the same.
But then you also have methods that actually change content-- append, insert, delete, reverse. T
hey're are not available on string. They're kind of unique StringBuilder behaviors, because they u
pdate the contents within that builder.
So here's an example. We'll allocate a new StringBuilder object, and then
we'll append the word tea to it. So initially it was kind of empty. There was no characters per
se in it, right? But then you add a word tea, and then you add append s that goes at the end.
So we've got teas. Then we've got insert. Oh, that's interesting. Position number, position 3. And
then you insert. What do you want to insert? m. So what will happen is at position 3, we slot in th
e m character. And any other characters beyond that will be pushed forward in that StringBuilder.
So kind of insert in the middle, and we push whatever after it forward. You can delete the range o
f characters, for example. So remove positions from 2 to 4. Please note, just like with a substring,
the lower bound is inclusive to the result, the upper bound is not inclusive to the result.
So delete from position 2 to position 4 will delete positions 2 and 3. So that's letter a and m. So in
stead of the word teams, you end up with the word tes. Reverse basically spells whatever is in a
StringBuilder backwards. So we get set instead.
You could check the length. That's actually the amount of characters you have in StringBuilder. A
nd then you also could check capacity. Capacity is how many characters can you put in before th
e rescaling will be required. Yeah? But rescaling happens automatically, if necessary.
Also what you can do, of course, you can insert spaces. But you cannot jump positions. So if you'
ve got the last valid position is 2, right? So that's the letter t. If you're trying to do the insert at posi
tion 4, then it seems like you just jump position 3. You can insert space at position 3. That's perfe
ctly fine. You can do that.
But you cannot just not do anything with it, and immediately try to jump beyond-- keep the positio
n, go to position 4. That will result in StringIndexOutOfBoundsException. So StringBuilder insists
on you filling something into these positions without jumping the index.

You might also like