CST 338 - Week 1 - A Cup of Warm Java



The Coding Bat exercises were a fun way to get reacquainted with some of the basic features of Java. I imagine that going through them over time will help me to get familiar with more advance features and "gotchas" of the language.

I would use the example of Java String-1 `withoutEnd` because it led me down an interesting rabbit hole and provided nice value that I will describe here.

I have a lot of experience writing Javascript, so the basic prompt seemed very simple: "Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2."

Easy enough, I know in Javascript I would use the `slice` method. So I simply looked up what the equivalent would be in Java which was the `substring` method. Using the `.length()` method was familiar to me, so that came naturally -- easy enough right?

Well sorta.

This is where my rabbit hole came into play. I know that using `.slice()` in Javascript creates a new "copy" (shallow copy, but memory and pointers in Javascript is a whole extra 10 blog posts) ... so I was curious if Java does the same.

As it turns out `String` objects in Java are ENTIRELY immutable. How crazy is that! So once you create a string you can no longer modify it. Even simple methods like `.concat()` which you would assume mutate a string -- do not. This is actually really different from what I am used to. And this also lead me to ask -- why is this? This lead to another rabbit hole around concurrent programming in Java and how many of design decisions of the language are done with "thread safety" in mind. That is to say, because the language supports concurrent operations sharing the same memory the immutability makes it easier to avoid sticky situations (this is a simplification lol).

Anyhow -- all of this is to say many Coding Bat exercises walked me down a similar rabbit hole. The solutions themselves were relatively simple because I know other languages. Coming at each problem with a point of reference helped immensely and most took one to two tries. The real value I found was in trying to understand "WHY" the code worked the way it did, and even a simple string exercise gave me a deeper piece of value. 

Comments

Popular posts from this blog

CST 300 - Week 4 - Writing With Purpose

CST 300 - Week 2 - More than just a draft

CST 300 - Week 3 - Things You Should Know