Explore Free Java Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Fri, 24 Feb 2023 21:14:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Java Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Free Programming eBook – Programming for Beginners https://gamedevacademy.org/free-ebook-programming-for-beginners/ Tue, 09 Feb 2021 09:59:27 +0000 https://coding.degree/?p=413 Read more]]> Take your first steps into the world of programming and computer science with our fantastic programming eBook: Programming for Beginners.

Featuring content by Mohit Deshpande, this eBook will help you take your first step into the foundations you will need to make software, pursue application development, games, and more. Using the popular and stable Java programming language, you will learn about variables, loops, classes, inheritance, and a slew of other features essential for any coding project – whether you pursue programming with Java or any other programming languages.

No matter your goals, these in-demand skills will set you up for success as you enhance your careers, find new hobbies, and more!

Download the eBook here ]]>
How to Use Classes and Objects in Java https://gamedevacademy.org/java-classes-objects-tutorial/ Fri, 24 Jul 2020 15:00:54 +0000 https://androidkennel.org/?p=1895 Read more]]>

You can access the full course here: Java Foundations

Classes & Objects

Objects are code entities with state and behaviour. The state is represented by variables that make up various properties or attributes. The behaviour is managed by functions that the object can run; typically, these functions modify the state in some way. Classes act as blueprints for objects, specifying what variables an object should use to make up its state and also defining any functions the object might want to run. We can then create instances of these classes which are the objects themselves. We can think of this a bit like function construction where the class is the function definition as it describes what the object can do and the object is like calling the function because we are actually running some code found within the class. Classes also use special constructor functions to create instances and set up the initial state of the object.

An example of this might be a character in a game. Some attributes that a generic character has might be name, health, position, attack, defence, etc. and a character might be able to heal, move, attack, etc. We will implement some of these attributes and behaviours. We can declare our class and add attributes as variables called fields like this:

class GameCharacter {
  String name;
  int pos;
  int health;
}

Next, we need to add a move function that helps us change our position. Functions within a class are called methods. Because the method will be used to change the pos field of the GameCharacter, it doesn’t need to take in the current position or output a new position, we can add it below the fields like this:

void move(int byAmount) {
  this.pos += byAmount;
}

This function will be called on an instance of the class and will change its value of pos. The “this” keyword says that the pos variable to change is the one within the current class. Generally, if we are accessing fields or methods of the current class, we use the syntax:

this.fieldName
this.methodName

The final thing we need is a constructor. This is used to set the initial state of the object by taking in values for the variables that need to be set up and assigning the values. It acts like a regular function otherwise but is named the same as the class name and doesn’t need a return type so we would do something like this:

GameCharacter(String name, int pos, int health) {
  this.name = name;
  this.pos = pos;
  this.health = health;
}

Notice that we can use parameters with the same name as the fields. We distinguish between them again with the “this” keyword. Our final class looks like this:

class GameCharacter {

  String name;
  int pos;
  int health;

  GameCharacter(String name, int pos, int health) {
    this.name = name;
    this.pos = pos;
    this.health = health;
  }

  void move(int byAmount) {
    this.pos += byAmount;
  }
}

This should be declared before the Start class. Remember, a class is just the blueprint. To actually use this class, we have to create instances. The instances are objects: variables whose data type is the class itself. That means they use the class fields to keep track of their state and the class methods to change the state. We can create instances of GameCharacter in main like this:

GameCharacter gc = new GameCharacter(“Nimish”, 5, 100);

Note the “new” keyword. We created a variable of type GameCharacter and passed in the values of “Nimish” for name, 5 for pos, and 100 for health. In order to access the values of this object, we can do this:

String name = gc.name;
int pos = gc.pos;
int health = gc.health;

We can change them like this:

gc.pos = 10;
gc.health = 120;

And can call the function like this:

gc.move(10);

We can create as many instances of GameCharacter as we like and they can all have different values for name, pos, and health. If you’re comfortable with this class, try adding more fields and methods and then try creating your own custom class from scratch. Remember, you can always print out any values you want with:

System.out.println(variableName);

Transcript

What’s up, guys? Welcome to the final tutorial in our Java course. This is gonna be all about classes and objects. We’re gonna get an intro into what classes and objects are, how they relate to each other, and of course, how to use them. We’ll start by exploring what they are, then we’ll create a custom class, and then we’ll create an object of that class and learn how to use it. So let’s head to the code and get started.

All right, so starting from pretty much a clean slate again. Let’s talk about what classes and objects are. The weird thing is that we first have to know what an object is before we know what a class is, but we have to implement a class before we can use an object. Now we can actually see a class here but we haven’t really talked about what it is, so let’s start with the basics.

An object in code is essentially an entity with state and behavior, so it could represent anything. In a game, it could represent a character, for example, because a character has state. That’s gonna be basically the sum of all of its properties or attributes. And it has behavior.

For example, it can move, might be able to attack, might be able to pick things up, et cetera, so those would be objects. Essentially, with an object, we represent the state through variables. So these are all kind of properties and attributes that an object will have. If we’re going back to that video game character example, a character might have stuff like a name, might have a certain number of health, might have an inventory full of items, et cetera. Okay, so these are all gonna be properties or attributes that an object has that represent its state.

Now the behavioral aspects are executed through functions. For example, the player might be able to move around. In which case, it’s changing its position. It might be able to pick something up. In which case, it’s changing its inventory. It might be able to heal up by consuming something. In which case, it’s changing its health. So you can see that most of these behaviors are actually functions that will change the variables that represent its state.

Okay, so objects just represents clusters of data that have states and behavior. The state is maintained through variables, and there’s functions that represent the behavior, which for the most part just change the variable values.

Okay, so let’s launch into an example, and I figure we might as well use that game character example. So we’ll start by creating a class that represent that game character. We should probably create it before our Start class because we will be using it in here, although it doesn’t matter too much. Typically, but not always, we actually put classes in their own files, but for now, we’ll stick it all in the same file.

So we’ll create a class. We’ll call this something like a GameCharacter. Note the capitalization there. And this will need several components. So we need to start by adding its properties or its attributes. So it might have a String name. Don’t worry, we’ll assign a value later. It might have an int that is gonna represent the position, so int position. And it might have an integer that represents its health. This is gonna be a really, really basic representation.

Okay, what about some functions? So this game character might have a move function, which is going to, I’m gonna have it actually be a void. We don’t really need to output the final position, and I’ll explain why in a second. And it’s gonna be called move. We’ll take in a movement amount, which will be an integer, so int amount. And then what we’re gonna do is we’re gonna use this function to change the position for this particular character.

So what we need to do is we’re gonna say, this.pos += amount. There’s no need to output any values or anything because we’re changing the position of this game character. So when we use the keyword this, we just refer to anything that exists within this current class. So this.pos is referring to the position that belongs to a game character. And we need to do this with, well, we should be doing this with every attributes or every function that we’re calling within this class.

All right, so there’s actually one more component that we need here, and that’s gonna be a constructor, often called an initializer in other languages. So this is a special type of function that is going to be used to set up the initial states or the initial values. We also use this function to create instances of an object, which will be instances of a class which will be an object. So in our case, we can do so like this.

The constructor function has special syntax and it’s actually just the same name as the name of the class. We open up the brackets however, and then we’re gonna take in values for name, position, and health. So we’ll start with a String name, we’ll start with an int position, and an int health. Okay, then what we need to do is we need to assign the values.

So we’re going to say, this game character’s name is gonna be whatever name we pass in. We’re gonna say this game character’s position is gonna be whatever position we’re passing in. And the same with health, this.health is gonna be equal to health. Okay, cool. So a fair bit going on hit, let’s talk about what’s happening.

So again, we’re creating a GameCharacter class. This is going to be essentially the blueprint of a game character object.

So within our program here, we would create some objects that would be game character types. Each of them would have names, positions, and health, and they’d be able to move. So a class is really just a blueprint of an object, specifying which variables and which functions it should have. Each instance of GameCharacter, which will be an object, will have to have a name, position, and health. We’re gonna use this function that you constructed to set things up. In this case, just set up the initial values of name, position, and health. And then it can execute this move function to change its position.

Now again, realistically, a game character would have much more than this. They probably have maximum health, an inventory. They’d have more actions such as heal or attack or whatever. But we’re not gonna worry about that. Again, this is more just to demonstrate the concept. Now let’s create an instance of our GameCharacter so that we can actually use it because this is a little bit like a function implementation. It is showing you what should happen but it’s not actually doing anything yet.

So what we can do in our main function down here is create an instance of it. So this is actually defining a new data type every time we create a class. Instead of being, let’s say, an integer or a string, the variable is now going to be a GameCharacter type variable. We’ll just call this gc for short. And this is going to have to be an instance of a new GameCharacter. So we use the new to infer that we are actually creating an instance of GameCharacter. Note how it’s automatically using the constructor to tell us that we need a name, position, and health. So we just pass in some values here. Again, make sure they’re the correct type. Position will start at zero. Health, we’ll have maybe 100 health. And now we’ve created our first object.

So this object is an instance of the GameCharacter class. That means that our object has used this function to start up its name, position, and health, and it can move if it wants. So this gc variable has a name, a position, and a health of Nimish, 0, and 100 respectively. Okay, so now let’s talk about how to access the values or the state stored within this game character. We do so with the dot syntax. So in this case, gc dot, and you can already see a list of the possible options, health, name, and position. We can also call the move function.

So let’s say we just wanted to print out the game character’s health. What we could do is actually just do something like this. We do System.out.println and all we need to do is print the gc.health. Okay, so this is just gonna get whatever value of health is stored in this gc. In this case, 100, and it’s gonna print it out. So if we save this and we go to run it, we should just get 100 printed out. And indeed, we do.

Similarly, we can actually change it directly using basically the same functionality. So we could say something like gc.health is actually equal to 200. If we then run this again, we should see that the gc’s health is 200, and that’s because we’re assigning a new value to the variable that represents the game character’s state. So the game character’s value of health is now 200.

Similarly, if we wanted to call the move function, we could. So we could do gc.move. We can pass in an amount, maybe 10. And if we wanna print out the game character’s new position, we would do gc.pos. Okay, again, we can run this code and we’d see that our position is equal to 10 because we called the move function and that changes the position of the particular game character we’re working with.

Okay, so I know this can be a little bit of a confusing subject, but it doesn’t really need to be. Just remember that each instance has its own state, its own values for, in this case, health, position, and name, okay? And it has its own functions. We can create multiple instances of game characters, each with their own values, or we can have game characters with exactly the same values if we really want. Because this can be a slightly complex topic, I definitely recommend that you practice heavy with this one. This is really kind of bringing together everything that we’ve covered in the course so far into one, big, final topic. So really, as long as you understand the bits and pieces from before, you should be fine with this one.

So definitely practice a little bit. Try creating some new classes and new objects. And when you’re ready to move on, we can finish up by summarizing this course. Okay, so thanks for watching. See you guys in the next one.

Interested in continuing? Check out the full Java Foundations course, which is part of our One-Hour Coder Academy.

]]>
A Guide to Java HashMaps https://gamedevacademy.org/java-hashmap-tutorial/ Fri, 17 Jul 2020 15:00:24 +0000 https://androidkennel.org/?p=1894 Read more]]>

You can access the full course here: Java Foundations

HashMaps

With arrays and ArrayLists, we stored values at specific indexes so the position of the elements is how we identified their values. With HashMaps, we store values at keys rather than at indexes so the position of the elements doesn’t matter. This is beneficial if we want to create a mapping of keys to values. Let’s set up the inventory but with item names and quantities. We can set the keys to be the names and the values to be the quantities. We must first import the HashMap library like this:

import java.util.HashMap;

Then we can replace the inventory with this:

HashMap<String,Integer> inventory = new HashMap<>();

Note how we set the key and value in the <> and that the value is not int. It wants an object of the Integer class but for our purposes it’s exactly the same as a regular int. We have String type keys and int type values. We can then put the values into the HashMap by passing in the key and value like this:

inventory.put("Knife", 2);
inventory.put("Boots", 3);
inventory.put("Axe", 1);

Although this is technically storing 6 values we only consider 3 of those to actually be values and the other 3 are the keys. If we want to retrieve a value, we use the .get() function and pass in the key like this:

int numKnives = inventory.get("Knife");

If we go to put a value into a HashMap but it already exists, it will just replace the value at that key. If we know the key exists, we can use the replace function in the same way but put works just fine:

inventory.replace("Axe", 2);
inventory.put("Axe", 2);

There are some other functions and you can find them in the same way as with ArrayLists.

Transcript

Hello guys. Welcome to our tutorial on HashMaps. Here we’re going to explore a different type of collection, which will be the HashMap. This is essentially a list of key-value pairs. We’re going to start by learning how to create HashMaps. Then how to get and set HashMap elements and then just a couple of the other common operations. Let’s head to the code and get started.

All right, so before we do anything, let’s talk about what HashMaps are and where we use them. So HashMaps essentially represent lists of key-value pairs. So the benefit of using a HashMap instead of let’s say a basic array or an ArrayList, is that we no longer need to worry about the position of the elements.

So with an ArrayList or an array, the position is how we access the individual values themselves and so the position matters. However, we don’t always want that to be the case.

With a key-value pair, we don’t really care about where in the HashMap an item is. We just care about the key under which that value is stored. So we’re essentially storing two pieces of data per value. This means, in order to change a value within a HashMap or to retrieve a value, we have to know what key it’s stored under, okay? So it presents a different kind of a challenge but also helps to solve the problem of forgetting where in the ArrayList items are stored.

So in order to set up a HashMap, the first thing we need to do is import it from java.utils again. So we’re going to import java.utils.HashMap, or actually it’s util.HashMap. Okay, like so and then we can create a HashMap in a somewhat similar fashion to an ArrayList. We do a HashMap, we do the type of HashMap we want and then the name. In this case, we’ll do an inventory again but we’ll take it one step further with the name and the quantity of items, and then we’ll set this equal to a new HashMap, okay? Like so, just like with an ArrayList.

Now, the difference is that we now no longer just pass in the type, maybe a String, but we need the type of the key and the type of the value. So in this case, we’ll do String key, so this’ll be the item names, and we’ll do integer values.

Now, weirdly enough, when we’re declaring the type of integer in a HashMap or even in an ArrayList, we actually don’t do int like this, we do Integer, capital I, but otherwise it represents the same kind of data, okay? So if you’re doing an ArrayList of integers, you do an ArrayList of Integer, not an ArrayList of int. Okay. Cool.

So now let’s add some items to this inventory. We’ll do the inventory and we’ll use the put function. Okay? So the put function takes in a key and a value. In this case, the key needs to be of the type here, so we’ll do, maybe we’ll do like a Knife again and then the value. Maybe we have a couple of knives. Okay, just like before. And we’ll just add in a few more items because why not? We’ll also add in maybe a couple pairs of boots. We have three pairs of boots, perhaps. Maybe we have like one Axe or something and so on and so forth.

So the order of these items, the order in which we put them really doesn’t matter because we access the values, two, three and one based on the key that they’re stored under.

Now, in order to get something, we’re gonna do the inventory. And we’re going to use the get function. And this way, we need to input the key and this will retrieve us the value. So maybe we want whatever value stored under Knife. We wanna see how many knives we have, and this would return us, in this case, an integer, okay? Because the values are integers. So we would do int knife is going to be equal. You know what? We would actually do number of Knives is going to be equal to the result here.

Now, one thing I should point out before moving on is that the put function will insert a key and then assign the value. However, if it finds the key that already exists, for example, if I did this, put Axe of two, it’s going to find this key and then it’s just gonna replace whatever value it finds, okay? So if the key does not exist, it inserts the key and assigns a value. If the key does exist, then it just replaces the value.

Alternatively, if you know that the key exists, you can just do the inventory.replace, okay? And then we can pass in either the key and the oldValue, newValue, or I think you can actually do the key and the newValue. So in this case, it would be the Axe and then the value of two, all right? Now that’s all we’re gonna cover in this tutorial.

Similar to the ArrayList, there is a plethora of functions that you can choose from. So you can open up your inventory dot and you can see that there are a lot of functions to explore. So feel free to explore some of them. Don’t worry, you really don’t need to check out all of them. Perhaps just the specific kind of key and value pairs. For example, you need a set of just the keys or just the values. That should be good enough. When you’re ready to move on, we’ll switch topics and start talking about implementing logic and control flow with if statements. So stay tuned for that. Thanks for watching, see you guys in the next one.

Interested in continuing? Check out the full Java Foundations course, which is part of our One-Hour Coder Academy.

]]>
How to Set up an Android Project with Kotlin https://gamedevacademy.org/android-kotlin-setup-tutorial/ Fri, 04 Oct 2019 15:00:22 +0000 https://androidkennel.org/?p=1740 Read more]]>

You can access the full course here: Kotlin for Beginners

In this lesson, we’re going to create a new project in Android Studio.

Launch Android Studio and select the “Start a new Android Studio project” option:

Android Studio project setup screen

Here we see several available designs that we can use for our project and their brief descriptions at the bottom of the window. We’re going to start with the empty activity for this lesson:

Android Studio project setup with Empty Activity selected

Now, we give a name for our project (My First Kotlin App, for instance). It generates a package name from the project name, which ensures that if you publish this app in the Google Play Store it would have a unique identity. Select Kotlin as language and set the minimum API level to “Android 4.4 (KitKat)”:

Android Studio configruation with Kotlin selected as language

The minimum API level indicates the percentage out of all Android devices (which have Google Play Store installed) that are capable of running your app. We do want to target older versions of Android in order to have our app available in multiple devices, otherwise only a handful of people will be able to download and install it from Google Play. Kitkat runs on about 95% of devices and thus it is good enough for our course project.

By choosing a minimum API level, we’re also dealing with compatibility as some of the newer APIs do not run on older devices and so we need to add some extra code that targets specifically those older versions.

After Android Studio resolves dependencies and compiles our code, we should be able to visualize our empty activity project. Note that the load time gets faster the more you work on the same project.

 

Transcript

Let’s begin by choosing start a new Android Studio project. Here we’re presented with a number of templates that you can choose from. If you take a look here, we have phone and tablet templates. Each one of these is a starting point for creating different types of apps. And as you click through, you can take a look at kind of the description and get a sense for what they would do. It basically gives you a headstart into the project. You also have templates for Wear OS, for Watches, for TV, Android Audio and Android Things.

Let’s go to Phone and Tablet and choose Empty Activity, choose Next. Here we’re going to give this a name and the name we’re gonna call this is My First Kotlin App. Note that it generates a package name and the package name is based on what we call the reverse domain.

If you own a website, you have the ability to have a custom package name that’s tied to a unique value that no one else has. So, when you have a company name or some other domain that you own, you would use the reverse value of it to say com dot whatever the business name is dot and the name of the app. This makes sure that when you publish your app in the App Store, the Google Play Store, it’s going to – this ensures that when you publish your app into the Google Play Store, it will be unique across the ecosystem and others can install it on their device.

Next you have the save location, and you can keep track of this wherever you like, on your hard drive and for language, let’s go ahead and select Kotlin. Next, we choose what is called the minimum API level. If I select this, note that we have quite a few choices and they go back to quite old devices and then they go all the way up to kind of the newest device, things that are out there. You would choose an API level in order to have your app available to multiple devices. If you choose an older version, you can target more devices.

For example, if I select API 19, which is Android 4.4 or KitKat, it says your app will run on approximately 95% of devices. What that’s saying is of all the Android devices that have access to Google Play, 95% of all of these devices would be able to run this app if you targeted this minimum API level. If I select a minimum level that’s higher, that’s more recent, let’s say Android 9, then note that it says your app will run on less than 1% of devices. So, it’s telling us that there are more devices out there that are using older versions, so you can kind of experiment with this.

If I say Marshmallow, then it says 62% and go back to Lollipop, 85%, if I go back to KitKat, 95%, that’s a lot. You consider that there are hundreds of thousands of devices, millions of devices really and of those, you’re going to hit the majority of them across the entire world. This value only applies to Android devices that support Google Play.

There are hundreds and thousands of other devices that are not – there are hundreds of thousands of devices that are built much cheaper and they run a version of Android but they’re not certified to run Google Play. Google Play has minimum requirements for memory and performance. So, this value doesn’t necessarily target all these other devices that are not supported. Just keep that in mind if you’re targeting specific devices. You’ll have an opportunity to run this on everything that’s out there.

When you select a minimum API level, you’re dealing with backwards capability, meaning some of the newer APIs will work and you have to use what’s called App Compatibility. And there’s different ways that Android provides for us to do that but keep in mind that you do occasionally have to write code that targets older devices specifically by saying if this device is an older version, run this code, if it’s a newer version, run that code. And so, you do have to be aware of that.

But for the most part, Google makes it possible for you if you target an Android device from 4.4 or higher, the chances are that you’re gonna be able to run on all these devices with one set of code that you’re not gonna have to make that many customizations.

So, I’m gonna go with Android 19 and from here. We’re not going to worry about supporting Instant Apps or using AndroidX artifacts. Go ahead and choose Finish. This will then run through a few steps where it will compile and create this empty activity project for us and if you have dependencies. If you target older device APIs, it’s going to download, it may download for the first time a number of support libraries.

Once you’ve installed Android Studio, there’s a lot of things that can be downloaded to support a variety of Android versions and so, the first time you run Android Studio or the first time you may run a new project, it may take some time, so just be aware of that. As you work with Android Studio and as you work with the same project, the load time will get faster.

Interested in continuing? Check out the full Kotlin for Beginners course, which is part of our Android Development Mini-Degree.

]]>
How to Install Android Studio https://gamedevacademy.org/android-studio-tutorial/ Fri, 27 Sep 2019 15:00:26 +0000 https://androidkennel.org/?p=1734 Read more]]>

You can access the full course here: Intro to Java for Android Development

Part 1

Here we’re on a Mac. Let’s go to developer.android.com and click on Android Studio.

Android Studio developer home screen

We want to download Android Studio for Mac.

Android Studio download for Mac screen

Accept the Licence agreement and click Download.

It is a large file and may take a few minutes to download. Once it finishes downloading, double click to open the file.

Android Studio being unzipped on Mac

Next drag and drop the file on to your applications folder.

Android Studio with Applications folder being dropped onto it

If you had an older version, replace it.

Android Studio with Windows permission dialogue box

Now launch the application from your Applications folder.

If you had a previous version, you could import the previous settings or choose a clean install.

Android Studio Import settings options

Once Android Studio launches, it may prompt us with a setup wizard.

Android Studio welcome Setup Wizard

We can setup and choose our preferences. Let’s go with the Standard setup.

Android Studio install type options

Next let’s go with the Lite UI Theme.

Android Studio UI Theme options

Let’s verify the Settings and click Finish.

Android Studio Verify Settings screen

At this point, the installer will download additional required files needed to do Android development.

Android Studio downloading components screen

It may ask for for some additional permissions and when complete, will present us with the main launch screen.

Android Studio welcome screen

From here, if you wanted to open am existing or completed project, you would choose “Open an existing Android Studio project”. After having downloaded the files, we will need to unzip them and select the “MyFirstApp” folder and choose Open.

Mac desktop folder with MyFirstApp created

This opens the project in Android Studio and you have everything you need to get started with our course.

Android Studio with project open

Part 2

Here we’re on a Windows machine. Let’s go to developer.android.com and click on Android Studio.

Android developer website

We want to download Android Studio for Windows.

Android Studio windows download

Accept the Licence agreement and click Download.

Android Studio License Agreement

It is a large file and may take a few minutes to download. Once it finishes downloading, click to launch the installer.

If you had a previous version installed, it will allow you to uninstall the previous version.

Android Studio requesting to uninstall old version

Click Yes if you want to uninstall it.

Windows warning about uninstalling Android Studio

We continue, making sure that the option for Android Virtual Device is checked and click Next.

Android Studio component installation options

We confirm the installation location.

Android Studio file location installation option

We can create a shortcut.

Android Studio shortcut options

Let’s click Install.

Android Studio complete installation screen

Once that’s completed, choose Next.

Android Studio Setup finish screen

Clicking Finish will launch Android Studio.

Android Studio new project screen

We are now ready for the rest of the course. If you’d like to take a look at the completed project course code, first download and unzip it.

MyFirstApp folders for Android project

Then choose “Open an existing Android Studio Project”, navigate to the correct folder (MyFirstApp in this case) and choose OK.

Android Studio opening MyFirstApp

This opens the project and tries to compile it.

Android Studio code

If there are any dependencies (libraries etc) that the project needs, Android Studio may take a few minutes to download them.

Android Studio MyFirstApp dependencies syncing

Transcript 1

Here I am on a Mac, and if you go to developer.android.com and look for Android Studio, it’s usually here at the top. Go ahead and select that, and here, you’ll want to download Android Studio for Mac. You’ll accept the agreement and choose download. Now, it is a large file, and it may take a few minutes to download. Once that finishes, go ahead and double click to open the install file.

And from here, you will drag and drop onto your Applications folder. And if you had an older version, you’d go ahead and replace it with the newer version. After that’s finished copying, you can go ahead and launch the application from your Applications folder. If you had a previous version, you can import those settings or go ahead and choose a clean install. Once that launches, it may prompt you for a setup wizard, which allows you to set up and choose your preferences. I’ll go with Standard, go with the Light theme and finish.

At this point, it will download additional required files and get everything you need in order to do Android development. It may ask for some additional permissions, and then once that’s complete, you’ll be presented with the main launch screen. From here, if you want to open the completed project, you would choose Open an existing Android Studio project. After having downloaded the files, you’ll want to unzip them and select the MyFirstApp folder and choose Open.

And from here, you have everything you need to get started with our course.

Transcript 2

To get started, you first need to download Android Studio. If you go to your developer.android.com, and from here, you’ll usually find a reference to Android Studio, and in this instance, it’s here at the top. Go ahead and select Android Studio, and from here, you’ll go ahead and download the application. From there, you’ll agree to any requirements and press download.

Once that’s finished downloading, go ahead and double-click to launch the installer. If you have a previous version, it will go ahead and uninstall it for you. You can choose next. You can confirm if you’re okay to uninstall it. We’ll go ahead and continue, and we do want to make sure that Android virtual device is selected and choose next. Then confirm, and we can create a shortcut and choose install. Once that’s completed, go ahead and choose next, and you can go ahead and launch Android Studio for the first time.

With Android Studio installed, you’re ready for the rest of the course. If you’d like to take a look at the completed project source code, once you’ve downloaded the source code and unzipped it, you can choose open an existing Android Studio project. From here, navigate to where it is opened, and select the folder. In this case, it’s called My First App, so select folder and choose OK. From here, it’s going to open the project and begin and try to compile it.

If there are any dependencies or libraries or things that are not available within your installation, you may find that Android Studio will download a number of additional files, and that may take a few minutes before it’s ready to be run.

Interested in continuing? Check out the full Intro to Java for Android Development course, which is part of our Android Development Mini-Degree.

]]>
Zero-Day Java Guide 4 – Advanced OOP https://gamedevacademy.org/zero-day-java-guide-4-advanced-oop/ Wed, 14 Oct 2015 02:44:02 +0000 http://html5hive.org/?p=1136 Read more]]> Interfaces

There are cases in software development when we need to agree upon a contract that dictates how software components interact with each other. This allows many people to write independent code while still maintaining the core functionality of the software component. For example, all automobiles have the same basic functionality: turning and signaling, for example. Trucks and motorcycles, along with cars, can perform these functionalities as well. In Java, we call these contracts interfaces. In this section, we’re going to be looking at the syntax and use of interfaces.

Introduction to Interfaces

In order to understand how to use interfaces, let’s take a look at an interface:

public interface Operable {
    int LEFT = 1;
    int RIGHT = 2;

    void changeDirection(int direction);
    void signal(int direction);
}

Interfaces get their own separate Java file. They start with an access modifier, the interface keyword, and the name of the interface. As we can see, we can declare only constants or method signatures in an interface. Any variables we put in an interface is automatically a public static final constant, and any methods will be public and abstract. We can make methods static by adding the static modifier to a method. Note that we don’t need to provide an implementation for these method signatures. This is from the concept of the contract: any implementing class can choose to implement it however it wants!

We can make a class agree to the contract by making it implement the interface. When a class does this, the contract is enforced, and the class must implement the methods defined by the method signatures in the interface.

public class Car implements Operable {
    ...
    @Override
    public void changeDirection(int direction) {
        ...
    }

    @Override
    public void signal(int direction) {
        ...
    }

}

In the above code, we can make our Car class implement the Operable interface by adding implements Operable to our class definition. We also have to add method bodies to all of the methods signatures in the interface. We also see there’s something else above the declaration: @Override. This is called an override annotation and it tells the compiler that we’re implementing the interface’s method with this current class’s implementation. We’ll see more of this annotation when we get to inheritance.

Interfaces as Types

Moving on with the metaphor of contracts, we can actually use an interface as a reference type, even though we can’t create a new instance of a interface. The reason we can’t directly instantiate a new interface like Operable op = new Operable()  is because we need some class to implement the contract of the Operable interface. The Car class is one example since it provides method bodies. Suppose we have another class: public class Truck implements Operable {…} . We can use interfaces as a type, but we have to initialize them to a class that implements that interface.

Operable machine1 = new Car();
Operable machine2 = new Truck();

machine1.signal(Operable.RIGHT);
machine1.changeDirection(Operable.RIGHT);

machine2.signal(Operable.LEFT);
machine2.changeDirection(Operable.LEFT);

In the above code, we’re declaring two Operable variables and setting them to be different reference types, one of which is a Car and the other a Truck. Java enforces the rule that if a variable has the type of an interface, it must be set to an instance of an class that implements that particular interface. In our case, the objects are new instances of the Car and Truck class, both of which implement Operable. The only methods we can call on those objects are those that are declared in the Operable interface. This is because we don’t care about how Car or Truck implement its method, just that they are!

In this section, we covered interfaces and how we can relate them to contracts. In an interface, we can define method signatures and constants and have a class implement that interface. When it does, then the class is responsible for providing method bodies for the method signatures in the interface. We can also use an interface as a reference type as long as we set it to an object whose class implements that interface.

Inheritance

I’ve mentioned before that we can model real-world things as objects. Suppose we were modeling a zoo. We would have classes for many different animals and instances for each individual in the zoo. But we know more than just the animals themselves: we know the relationships between them. For example, we might have a zoo with reptiles and mammals. Within reptiles, we have snakes and lizards; within mammals, we have lions, tigers, and bears. All reptiles share properties between them and so do mammals. In our code, we don’t want to have to rewrite the same code many times for each mammal or reptile we decide to put in our zoo. This is where inheritance can help us. In this section, we’re going to learn more about inheritance as well as a few OOP principles that are strongly related to inheritance.

How to Use Inheritance

Let’s continue with the zoo analogy. We have mammals that share the the properties of “live birth”, “warm-blooded”, and “has fur”. In fact, big cats like tigers and lions share even more properties. This is an example of the natural hierarchy we have in the real world, and we can simulate that using inheritance. With it, we can create hierarchies that make software easier to follow and prevent us from rewriting the same code over and over again. Let’s create a class called Animal and assume it has the basic properties of all animals that belong to a zoo:

public class Animal {
    private int zooId;
    private String name;

    public Animal() {
        this.zooId = 0;
        this.name = "Unnamed";
    }

    public Animal(int zooId, String name) {
        this.zooId = zooId;
        this.name = name;
    }

    public int getZooId() {
        return zooId;
    }

    public void setZooId(int zooId) {
        this.zooId = zooId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " is speaking!");
    }
}

In the above code, we’re giving each animal an id and a name, as well as getters and setters for them. We also declare another method called speak, but we’re revisit that later. Now we can create separate Mammal and Reptile class that are subclasses of the Animal class: public class Mammal extends Animal { … }  and public class Reptile extends Animal { … }

We can make a class a subclass by saying extends after the class declaration (as opposed to implements for interfaces) and the name of the class. Regarding interfaces, a class can only extend a single class, but can implement multiple interfaces. When a class extends another class, it inherits all of the states and behaviors of its superclass. For example, if I create an instance of a Mammal, I can call someMammal.setName(“Steve”)  since setName is a public method on Animal. This also means that each subclass of Animal also retains the property of a zoo ID and a name, but, due to encapsulation, those fields are only accessible through the field’s getter and setters. If we wanted to access them directly, we could make the fields protected instead of private. As we can see, using inheritance prevents us from copying-and-pasting code from the Animal class to the Mammal and Reptile classes.

Typecasting

In Java, there might be cases where we want to treat a superclass as a specific subclass or an interface as a specific implementing class or even a double as a int. We call this conversion typecasting. When we typecast something, we’re essentially telling the compiler that we’re confident we know what we’re doing and to treat the type as another valid type. Let’s see how we can do this with primitive types:

double pi = 3.1415
int x = (int) pi;

In the above code, the value of x is going to be 3 since we’re treating pi as an int and ints can’t have decimal parts. The syntax for typecasting is to put a set of parentheses with the type that we want to convert the variable to in front of the variable we want to convert. Eclipse and any other IDE will only allow this if the types are somewhat related, else the IDE will throw an error immediately. For example, if we were going to typecast pi to a Car, Java would obviously have an issue with that! Let’s see what typecasting for reference types looks like.

Animal anAnimal = new Mammal();
Mammal steve = (Mammal) anAnimal;
Reptile kevin = (Reptile) anAnimal;

In the above code, we’re instantiating an animal and setting to a new Mammal object. We can do this because Animal is a superclass of Mammal. This is similar to why we can use an interface as a reference type by setting it to a new instance of class that implements that interface. In the second line, we typecast the animal to be a Mammal, and we’re correct and the code will work perfectly time. On the other hand, the third line will cause a runtime error because we know for a fact that anAnimal is not a Reptile. We’re illustrating here that typecasting of reference types can be dangerous unless we’re sure the type of the incoming variable is related to the type of the outgoing, typecasted variable.

Overriding and Overloading Methods

We’re going to return to methods to talk about the difference between overriding and overloading. We’ve already seen an example of overriding when we learned about implementing interfaces. We can override any of the superclass’s methods (that don’t have the final modifier) by using the exact same method signature and putting the override annotation before the method signature:

public class Mammal {
    ...
    @Override
    public void speak() {
        ...
    }
    ...
}

In the above code, the Mammal class is overriding the Animal class’s speak method. When we instantiate a new Mammal object and call the speak method, we’ll be executing the code in the Mammal class, not the Animal class.

On the other hand, method overloading is when we have a method with the same access modifier, return type, and method name, but different parameters types or a different parameter order. For example, we can declare another method speak that takes a String input parameter, for example. This is an example of method overloading, which is different than method overriding.

public class Mammal {
    ...
    public void speak(String text) {
        ...
    }
    ...
}

In the above code, we overloaded the speak method so now users can call the speak method with no parameters or pass in a String for the parameterized speak. It’s important to note that the parameter types have to be in a different order or there need to be a different number of them for overloaded to occur, else Java will throw an error saying we have duplicate methods. The parameter names don’t really matter: it’s the types and the order in which they appear as method parameters. To reiterate, method overriding occurs when a subclass defines it’s own implementation of a superclass’s method. Method overloading occurs when we have two methods with the same signature with the exception of the parameter types or the order in which they appear.

Accessing the superclass

In cases where we have a subclass, there may be times where we need to access the superclass’s methods or constructors. We already learned how to access the methods: plain old method calling. Intrinsically, we are calling the superclass’s methods by explicitly using the super keyword: super.speak() ; for example.

However, suppose we want to use the superclass’s constructors in a subclass. Instead of calling the setters for name and zooId, we just want our Mammal class to call the Animal class’s parameterized constructor since it already sets those. We’ve already seen how we can do this in previous sections, but let’s take a more in-depth look.

public class Mammal {
    ...
    public Mammal(int zooId, String name) {
        super(zooId, name);
        ...
    }
    ...
}

In the above code, we have a call to the superclass’s constructor by using the super keyword and then parentheses with the parameters, almost like a method call whose name is super. This statement will jump to the superclass’s constructor and give the id and name to the Mammal, as well as any other initialization that the Animal constructor might do. If we just wanted to call the default constructor, then we would just have the super keyword and empty parentheses. In most cases, it’s a good idea to design our software so in the constructor of subclasses, we’re calling the superclass constructor to do any generic setup, as opposed to duplicating code in each subclass.

Polymorphism

The last OOP concept we’ll talk about is that of polymorphism. In order to understand the concept, let’s suppose we have a few subclasses of Mammal: Dog, Cat, and Duck. Now let’s look at how we can use polymorphism.

Mammal fido = new Dog();
Mammal kitty = new Cat();
Mammal amy = new Duck();

fido.speak();
kitty.speak();
amy.speak();

In the above code, we declare three Animal variables and set them to be new instances of different subclasses. Again, this is completely valid since Mammal is a superclass. Note that we can only call methods on it that are defined in Mammal since that’s the type of the variable. Next we have calls to the speak method. Now Java knows that fido is a Dog, kitty is a Cat, and amy is a Duck, so when we call the speak method, Java will call that respective subclass’s overridden speak method, if it overrode it. In the case of fido, kitty, and amy, Java will call Dog, Cat, and Duck’s speak methods respectively. If they don’t exist, then Java will call the superclass’s speak method.

This language feature of Java can be incredibly helpful. In a more practical example, suppose we have a superclass called SortingAlgorithm and we have several subclasses called MergeSort, InsertionSort, and HeapSort. We can just declare a SortingAlgorithm object and assign it to a particular sorting algorithm depending on our data set. (Sorting algorithms can vary in efficiency depending on the data set.) Then, when we call something like mySortingAlgorithm.sort(…) , and Java will call the sort method of the subclass of the particular variable.

In this section, we learned about how we can create relations between classes using inheritance. We learned how to use inheritance in Java code through the extends keyword. In addition, we went even further to learn how we could tell the compiler to treat a particular variable as another class type. Revisiting methods, we differentiated method overriding, which is when a subclass implements a superclass’s method, and overloading, which is when two methods have almost the same signatures, with the exception of different parameter types. We also learned how we can access the superclass’s methods and constructors with the super keyword. Polymorphism is the last of the OOP concepts we covered, where Java will know what implementing/subclass method to call.

 

Over the course of this book, we’ve come a long way from learning variables and variable types! We quickly moved on to operators and decision and looping control flow statements, like if-then statements and while loops. Moving from concrete to more abstract, we transitioned into object-oriented programming. Along with objects, we covered member variables, access modifiers, and methods. Interfaces and inheritance were covered next as well as typecasting and polymorphism.

Towards the beginning of this book, we came in with barely any knowledge on Java but we’ve learned so much as we progressed on our journey. However, this isn’t the end of our journey. There are still many more concepts, structures, and topics in Java that are really interesting and useful. Consider this book as just the springboard for your next Java project, further learning, or your next journey.

“For the wise man looks into space and he knows there is no limited dimension.” – Lao Tzu

]]>
Zero Day Java Guide 3 – Object-Oriented Programming https://gamedevacademy.org/zero-day-java-guide-3-object-oriented-programming/ Wed, 14 Oct 2015 02:42:00 +0000 http://html5hive.org/?p=1127 Read more]]> Introduction to Objects

Object-oriented programming (shortened to OOP) applies the concepts of real-world objects to programming. For example, think of an object near you: a pen, a chair, a computer. All of these things can be modeled in an OOP language like Java. In this section, we’re going to move from low-level, concrete structures like control flow, variables, and loops to more abstract structures like objects. We’ll talk about the principle behind OOP, then move on to classes and instances.

Object-Oriented Programming

As mentioned before, objects are the fundamental structure to OOP. For example, take a car. We know that a car has a chassis color, make, model, and other properties. With cars, we can also accelerate, decelerate, change gears, and perform other actions. In other words, each object has a state and a behavior. This is true in programming as well, except we call state “member variables” and behavior “methods”. We’ll talk more about member variables in the next section, but, conceptually, we use them to hold the state or properties of an object. We’ll also learn more about methods later, but they allow us to represent behaviors or actions of an object.

OOP languages like Java and C++ have many benefits over functional programming languages like C:

  1. Modularity and Reusability: We can easily reuse components from one project to another project. Suppose we were writing a zoo program and we created a representation of a whale. We can easily reuse this component in another project related to marine biology, for example. In fact, we can even have generic types where the component itself can be modularized to a particular type. In the case of a Java List, we can have a list of anything so it is considered a generic type.
  2. Software Design: We can design very complicated systems and applications using the concepts of OOP. For example, suppose we were writing a weather station app that pulled data from the web. Instead of having one giant main method that sets up the connection, pulls the weather data from the web, parses it, and displays it, we could write a software component, perhaps called WeatherFetcher, to pull data from the web and parse it. The main method would just display the data pulled down by the WeatherFetcher. This drastically simplifies our main method and makes it easier to debug.
  3. Encapsulation: We’ll talk more about encapsulation later, but the principle behind it is to only allow access to variables if it is absolutely necessary. In our previous example with the weather station app, our main method doesn’t need to know how the WeatherFetcher grabs data from the web, just that it does and returns us data in a known format that we can display. It prevents everyone from having access to everyone’s data. If some data is corrupt, it become very difficult to determine exactly what is corrupting data. With encapsulation, we can narrow down exactly what operations are modifying the data.

These just illustrate a few of the many benefits of OOP. In this section, we covered an introduction to OOP. We learned that objects have states and behaviors. Now we’re going to focus on how we can implement this concept of how OOP is implemented in Java.

Classes and Instances

Let’s go back to the car analogy. A car of a particular make and model is made in a factory in an assembly line and they all come out to be the same initially. Then they’re sold off to customers who may use them very frequently or very infrequently. After they’re sold, now each car might have a different number of miles on it, a different type of brake fluid, or even a different color!

We can shift this conceptual analogy to a more concrete analogy in Java using classes. A class is a blueprint for a conceptual object. Think of it like the car specifications given to the factory. In Java, we use a class to define all of the states and behaviors an object can have.

An instance is a realization of a class. For example, suppose we have a car variable called bobsCar . This variable might have started out the same as danielsCar , but, after some time in the program, they might have a different state.

For the next few sections, we’re going to be referring to this following Car class. We’ll be looking at all of the components of this class, and, by the end, we’ll know everything there is to know about the Car class, as well as how to create an instance of it and actually use it!

public class Car {
    private String color;
    private String make;
    private String model;
    private int gear;
    private boolean running;
    private int speed;

    public static final int MAX_SPEED = 200;
    public static final int MAX_GEAR = 9;

    private static int numberOfCars = 0;

    public Car() {
        this.color = "Black";
        this.make = "Unknown make";
        this.model = "Unknown model";
        this.gear = 1;
        this.running = false;
        this.speed = 0;
        numberOfCars++;
    }

    public Car(String color, String make, String model) {
        super();
        this.color = color;
        this.make = make;
        this.model = model;
    }

    public String getColor() {
        return this.color;
    }

    public String getMake() {
        return this.make;
    }

    public String getModel() {
        return this.model;
    }

    public int getGear() {
        return this.gear;
    }

    public boolean isRunning() {
        return this.running;
    }

    public int getSpeed() {
        return this.speed;
    }

    public static int getNumberOfCars() {
        return numberOfCars;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void startCar() {
        if (!this.running) {
            this.running = true;
        }
    }

    public void stopCar() {
        if (this.running) {
            this.running = false;
            this.gear = 1;
            this.speed = 0;
        }
    }

    public void changeGear(int gear) {
        if (gear > 0 && gear <= MAX_GEAR) {
            this.gear = gear;
        }
    }

    public void accelerate(int amount) {
        int sum = this.speed + amount;
        if (this.running && sum <= MAX_SPEED) { 
            this.speed += amount; 
        } 
    } 

    public void decelerate(int amount) { 
        int diff = this.speed - amount; 
        if (this.running && diff >= 0) {
            this.speed -= amount;
        }
    }
}

Primitive and Reference Types

Several times in this text, I’ve made the point that something only applies to “primitive types” for example. Since we’re going to be looking into OOP, this section is going to look at what’s actually going on under the hood with our computer’s memory when we’re writing our program. We can imagine our computer’s member to be a giant table of little cells that have addresses and values.

java Reference-Types

As we see above, a primitive type is one whose value is stored directly in some block of memory. On the other hand, a reference type is one that has a pointer to another block of memory. A pointer is essentially a variable that holds the address of some other block of memory. In Java, any class is a reference type and the primitive types are the ints, booleans, chars, and other types of variables discussed in the variable type section.

Reference-Variables

This is significant because, depending on the kind of type, different operators and modifiers have a different effect. For example, remember back to the operators section. I said that the assignment operator, for primitive types, sets the value of one side to that of the other. However, for reference types, it creates an alias to the same block of memory. An alias is just another name for something. That means two variables now point to the same block of memory: changing one variable will alter the memory and any alias will do the same thing. This usually results in dangerous situations where we don’t know what is changing a variable might do to other alias. Imagine using a backup program having dangerous aliasing that just overwrites every backup with the most current one!

In this section, we learned about object-oriented programming and its benefits over functional programming languages. We can use OOP to abstractly represent and use software components. What makes these components objects are that they have a state and behavior. We’ll be referring back to that Car class for the next few sections. We also learned about what actually happens when we declare a primitive and reference variables. Primitive types are types whose values are stored directly in the block of memory; reference types are those that point to another block of memory where other values are stored. Pointers are just that: variables that hold a memory address to a cell, and therefore point to another block of memory.

Member Variables

In this section, we’re going to look at the first portion of the Car class that starts with what seems to be variable declarations. They’re not quite just variables, but, more specifically, they’re called member variables or fields. In our concept of an object, they represent the state or properties. We’ll learn how to declare and access these variables as well as the different types of access modifiers that we can apply on them and their effects on our member variables.

Declaring Member Variables

We can seen an example of declaring a member variable in the Car class:

private String color;

The first thing we need is to define a scope or access modifier, but we’ll talk more about these in later. Essentially, the private modifier makes the field only visible to the class it’s declared in. The next part looks just like a plain variable declaration: a type and a variable name. It’s really this simple to declare member variables! To summarize, we have a String member variable called color that represents the color of the particular car.

Accessing Member Variables

Similar to our predicament in previous sections, now that we have member variables, we actually want to do something with them. We need to access them in the class to check variables or perform basic operations. For example, let’s look at the the code that starts the car:

public void startCar() {
    if (!this.running) {
        this.running = true;
    }
}

This code is wrapped in what we call a method, but those will be discussed in the next section. In this block of code, however, we are checking to make sure the car is not running, then we are starting up the car by setting the running field to be true. This demonstrates both accessing a field and modifying it as well.

We see another keyword in that block of code however: this . The this keyword corresponds to the current instance of a class being acted upon. For example, suppose we have bobsCar. In our class, this.running will refer to bobsCar  or any other instance that we create of the Car class. Calling a method on an instance like bobsCar.startCar()  will change bobsCar’s boolean field running to true. Fields don’t have to be prefixed with the this  but there are cases, especially with constructors, that it is needed to differentiate a method parameter and the class’s member variable.

Access modifiers

Access-Modifiers

If we look at the statements that declare our member variables, we notice that before we actually state the type of those variables, we have this keyword private as well as the public keyword. We call these keywords access modifiers because using a particular one limits the scope of a field. The private modifier is the most restrictive access modifier since it restricts the visibility of a variable to just the class it’s defined in. On the other hand, the least restrictive access modifier is the public modifier since it allows the variable to be visible outside out of the class. We’ll see why this is generally a bad idea when we get to encapsulation. There also exists the very discouraged default modifier which allows access inside the package; the protected modifier only allows access to subclasses, but we’ll learn more about subclasses when we get to inheritance.

It turns out all variables in Java have a scope, or visibility. One of the simplest ways to determine variable scope is through the nearest set of curly braces. Take the following code snippet as an example:

int sum = 0;
for (int i = 1; i <= 100; i++) { 
    if (i % 5 == 0) { 
        sum += i; 
    } 
}

The above code sums up all of the numbers between 1 to a hundred that are divisible by five. Note that the scope of the sum  variable is the entire code snippet, which is why we can access it in the loop. On the other hand, the scope of the counter variable is limited to the for loop. Trying to access it outside the for loop would cause an error since that variable disappeared after the ending curly brace of the for loop.

Additional modifiers

public static final int MAX_SPEED = 200; 
public static final int MAX_GEAR = 9; 
private static int numberOfCars = 0;

In addition to the access modifiers that we have, we also have the static and final modifiers. The final modifier, for primitive types, makes the value of the variable immutable, or unable to be changed. In our case, we’re using it in conjunction with the static modifier to declare the constants MAX_SPEED  and MAX_GEAR . Reference variables, on the other hand, can still be modified, but you can’t re-assign the reference to another variable or new memory.

Static-Variables

A static variable essentially means that each instance of a particular class shares the same variable. They’re also called class variables since there’s only one per class, not one per instance. The above image illustrates this concept. This is why it makes sense to have a variable like numberOfCars . Each instance’s numberOfCars  variable points to the same thing. Conventionally, we access these static variables through the class name rather than an instance variable for this exact reason. We don’t need an instance to access a variable whose value is the same for all instances!

When we combine the static and final modifiers, we can declare variables to be constant. Final makes the variable immutable and static makes each instance share the same value. It wouldn’t be a constant if each instance had its own! By declaring the constant as public, we can allow other classes to access, or we can declare it as private and only allow our class to access it.

In this section, looked at member variables and how they’re used in our classes to hold the state of an object. We can simply declare one inside of our class like we would any other variable, except we have to be careful about access modifiers that we assign to it. Public means the variable can be seen by anyone and everyone, which is generally a bad idea. On the other hand, private means the variable is only visible within our own class. By declaring a variable to be static, we make sure that only one copy exists per class, not per instance, and, by making a variable final, we say that its value cannot be changed.

Methods

In this section, we’re going to talk about how to write methods. Other programs may call these subroutines or functions, but they’re essentially the same thing: a (parameterized) block of code that executes and may or may not return a value. They make our code easier to read and provide the foundation for the OOP principle of encapsulation that we’ll talk about later.

Simple Methods

To talk about methods, let’s first define a very simple method that takes in a number and returns the square:

public double squareNum(double x) { 
    return x * x; 
}

Breaking down this syntax, we first need an access modifier to tell us the visibility of this method. Then we can have a return type or not (denoted by void). In our case, this method’s return type is double. Next we have the name of the method. Method names follow the same convention as variable names: camelCase. Afterwards comes any input parameters or empty parentheses if the method doesn’t accept any parameters. The code block comes next; it’s a bit of code that is separate from any other method. However, if we said that the method had a return type, we need give back that return type by saying “return “ then a variable or value that corresponds to the return type. Methods can be more or less complicated than this one. Take a look at the following methods:

public void printSomething(String something) { … } 
private double hypotenuse(double a, double b) { … } 
public void sayHello() { … }

All of the above methods have different method signatures. The signature of a method comes from the line that declares it and includes the access modifier, return type, name, and the types of the parameters it takes in the order that they appear.

Method Parameters

As we’ve seen before, methods can take in any number of parameters of different types. Once we have a method with parameters, we can treat those parameters like any other variable and perform operations on them like in the previous squareNum(double)  method. When we’re calling a method, we can pass in either a variable or the value itself. Let’s see how we can actually call the method in code:

int val = 5; 
System.out.println(squareNum(val)); // should give us 25 

System.out.println(squareNum(5)); // should also give us 25

Both of the above ways work fine. The first approach uses a variable to hold the value then passes in that variable; the second approach simply substitutes the value of that variable to the method. Inside of the method, x  has a value of 5 in both cases. For primitive types, the value is only copied, so any changes to the parameter won’t affect the variable that we passed into the method. This is called pass-by-value. On the other hand, if we were using a mutable reference type, like a Java List or StringBuilder, then changes done to the parameter would be reflecting in the variable. This is called pass-by-reference because the parameter points to the same memory that the variable does so changing one will affect the other.

Constructors

When we instantiate a new object, all of the fields, whether public or private, of that instance are set to the default value. For primitive types, this isn’t an issue. However, the default value of any reference type is what we call null. This means that there isn’t any computer memory for that reference variable to point anywhere. Trying to do anything with a variable that’s null is going to result in Java throwing an error. To prevent this, we have special methods called constructors that allow us to initialize an object’s fields with values right when we instantiate it. Let’s look at a few of Car’s constructors:

public Car() { 
    this.color = "Black"; 
    this.make = "Unknown make"; 
    this.model = "Unknown model"; 
    this.gear = 1; 
    this.running = false; 
    this.speed = 0; 
    numberOfCars++; 
} 

public Car(String color, String make, String model) { 
    super(); 
    this.color = color; 
    this.make = make; 
    this.model = model; 
}

We notice that there are two constructors: one without parameters and one with parameters. The constructor without parameters is called the default constructor, and the one with parameters is called the parameterized constructor. These special methods essentially initialize all of the fields when a new instance is created like so:

Car car = new Car(); 
Car stingray = new Car(“Red”, “Chevrolet”, “Corvette Stingray");

The first instance of Car is a black car of an unknown make and model. It’s in first gear, isn’t running, and has a speed of zero. The second instance uses the parameterized constructor so the color, make, and model are both set immediately; hence, the second instance will have everything the first instance has (thanks to the call to super() that we’ll discuss later) with the exception of the color, make, and model.

Encapsulation

Encapsulation

We use many devices today that we don’t fully understand or have control of. Think of a car or computer. We don’t have direct access to the fuel injector or to the transistors on our computer’s chips. Instead, we only have access to some portions of the computer and car. The principle is the same with encapsulation, also called data hiding. To implement the concept in code, we make all of the fields private so they can’t be accessed by the outside world. Instead, we use methods called getters and setters allow access to these private variables. One reason that we can’t let others access to a class’s data is so that users can’t set the data values to invalid values, like setting the gear to a negative value.

public void changeGear(int gear) { 
    if (gear > 0 && gear <= MAX_GEAR) {
        this.gear = gear;
    }
}

We can see in the above code that we only set this Car’s gear to be method parameter’s gear only if it falls within the valid bounds of what we define to be a Car’s gear.

Getters and Setters

In the previous section, we learned about encapsulation and data hiding. Let’s take a look at an example of getters and setters from our Car class:

public String getMake() {
    return this.make;
}

public String getModel() {
    return this.model;
}

public void setMake(String make) {
    this.make = make;
}

public void setModel(String model) {
    this.model = model;
}

You can see why we call them getters and setters! The getter is used to retrieve the value of the field, and the setter is used to set the value of the field. We can use getters and setters to do any kind of input validation before changing the internal state or any nice formatting before outputting the internal state.

In this section, we discussed methods. We can use them as subroutines to segment our code. They can return values or void, meaning they don’t return a value, and they can have any number of parameters. We also learned how we can initialize fields using constructors. In addition, we discussed the important concept of OOP: encapsulation. Finally, we discussed getters and setters, an example of how we can implement encapsulation. They can be used to retrieve the value of a field and set the value of a field.

]]>
Zero-Day Java Guide 2 – Operators and Control Flow https://gamedevacademy.org/zero-day-java-guide-2-operators-and-control-flow/ Wed, 14 Oct 2015 02:22:46 +0000 http://html5hive.org/?p=1050 Read more]]> Operators

In the previous sections, we learned how to create and use Java variables and arrays. Now that we can store data as variables, we need to perform operations on them, such as adding or multiplying. In this section, we’ll look at the basic mathematical operators that we can perform on all of the Java number types. Then we’ll move on to the very important concept of mix-mode math: what if we have a statement with integers and floats? Towards the end of this section, we’ll move on to operations that can be performed on a single variable and operations that return a boolean value.

2.1 – Operator Precedence

The above table shows the order of precedence when we have a statement with multiple operators. This table is here solely for reference. Operators on the above table are the ones we’ll be looking at though more operators exist.

Basic Arithmetic Operators

2.2 – Arithmetic Operators

We’re very familiar with the operators in this section since we learned almost all of them back in grade school. The above table shows the arithmetic operators that we might encounter in Java. We’re already familiar with the operators for addition, subtraction, multiplication, and division. It is important to note that all of these operators are what we call binary operators, as opposed to unary operators, because they require two operands, or inputs. It doesn’t make sense to perform addition on a single number!

Perhaps the one operator we might not be as familiar with is the remainder operator, denoted by a percent sign. (This is not to be confused with the modulus. They’re not quite the same thing!) The remainder operator simply returns the remainder of an integer division. We’ll talk more about integer division in the next section, but, suppose we have a statement like 8 % 3. We expect this to return two because three goes into eight two times and leaves a remainder of two. The remainder operator, in the case of x % 3, can return any integer in range of values from 0 to (3-1). To generalize this, if have x % y, then the remainder can be anywhere from 0 to (y-1). As we’ll see later on, this operator is particularly useful in determining the parity of a number. In other words, it helps us determine whether an integer is even or odd. The expression to do so is x % 2, where x is any integer variable. We expect this to return zero if x is divisible by two and therefore even, and we expect this to return something that isn’t zero if the number is odd.

One misconception about the assignment operator is that it is the same as the “equals” sign in mathematics. Let’s look at an example of why this is not the case. Suppose we have the following Java statements:

int x = 1;
x = x + 3;

From our previous knowledge, we know that we are declaring an integer called “x” and assigning it the value of one. The next line is particularly interesting because it makes perfect sense to Java but no sense in mathematics. How can x be equal to x plus three? How can any number be equal to three more than itself? It can’t! This is precisely the reason it doesn’t make sense to interpret this as being a purely mathematical statement. However, to the Java compiler, this statement is clear: set the new value x to be the old value of x plus three. After that line executes, x will have a value of four. For primitive types anyway, this is exactly what the assignment operator does. It takes the value of the right-hand side and puts it in the variable on the left-hand side. This works a bit differently for reference types, such as Strings, but we’ll get to that when we talk about objects towards the end of this book.

Speaking of Strings, the addition operator serves another purpose if the two operands are Strings. The operator will perform an addition of sorts on the two String in the sense that it will concatenate them together. In other words, the addition operator also serves as the concatenation operator where it will combine the two Strings together into a single String. Let’s look at an example:

String hello = “Hello";
String world = “ World!”;
String helloWorld= hello + world;

In the above example, we have two Strings that we set to be “Hello” and “ World!” The String resulting from their concatenation will be “Hello World!” Note the space at the beginning of the world String. Spaces are characters and aren’t added automatically, so we have to add them to a String whenever necessary.

2.3 – Compound Assignment Operators

In some cases, we can combine the assignment operator with another arithmetic operator to form a compound assignment operator. These operators are really no more than a short-hand way of performing basic operations where we are changing the variable by some literal or constant.

int x = 1;
x = x + 1;
x += 1;

The last two statements do exactly the same thing: they increment the value of x by one. When we get to unary operators, we’ll see an even shorter way of denoting this.

In this section we learned about the basic arithmetic operators that we can use to perform operations on two variables. These operators include addition, subtraction, multiplication, division, and remainder. The remainder operator simply returns the remainder of an integer division (i.e. 17 % 6 = 5.) This assignment operator is different than the “equals” relation in mathematics because takes the value of the right-hand side and stores it in the variable on the left-hand side. The addition operator becomes the concatenation operator when both operands are Strings; the operator combines two Strings together and returns a single one.

Mix-Mode Math

In this section, we’re going to look a the dangers of incorrectly using the arithmetic operators and interpreting Java to be mathematics. To give an example, let’s look at the following Java statement

double x;
x = 1 / 2;

Mathematically speaking, x should have a value of 0.5. However, if we print the value of this variable out to the console (using System.out.println(x)), we’ll see that the value is actually zero.

But why is this the case? If we remember from our chart of variable types, we know that a double can have a decimal value, but that doesn’t appear to be the case here. This is because division is tricky in Java in the sense that the type of the result of the division depends on the types of operands it receives. In this case, we are dividing two integers, therefore Java gives us back an integer. But we know integers can’t have decimal parts so Java discards, or truncates, anything after the decimal point as opposed to rounding up or down. If we remember back to the table of variable types, they were arrange in a specific manner. Doubles and floats are at the top of the food chain when it comes to Java types. This is because if we insert a double into our statement, Java will convert the entire result to a double. This doesn’t just work for doubles, but also for any “superset” variable type. Essentially, we can fit any number variable into a double, but we can’t fit a double into an int since it is a “subset” of double. In other words, double is the largest, most general set and every number type is a smaller subset of double.

Sets-of-Numbers

This is particularly useful when it comes to division. Let’s fix our previous statement so that it correctly returns a double:

int x;
x = 1.0 / 2;

Note the difference here: we’re using 1.0 instead of just 1, and, by doing so, returning a value of 0.5 instead of 0. This is because adding a decimal point to 1 converts it to a double. Now, Java sees that we are dividing a double by an int, and, since doubles are a superset of ints, the entire division returns a double. To use another example, suppose we wanted to add two shorts, but we weren’t getting the expected result. We could add a short and an int, and Java will return us an int since ints are a superset of shorts.

Unary Operators

2.5 – Unary Operators

This section explores Java’s unary operations. The differ from the arithmetic operators and conditional operators (that we’ll talk about in the next section) because they only require a single operand, hence the name unary. There are some things to note when using these that we’re going to cover more in depth in this section. To start off, the unary minus operator simply returns the opposite of the given number type. However, it does not change the value of the operand. To see this, let’s look at an example:

int x = 5;
int y = -x;
System.out.println(x);
System.out.println(y);

We see that x still return positive five and y returns negative five. This means that the unary minus operator didn’t change the value of x, but it returned the the opposite value, from positive to negative and negative to positive.

Another important concept to grasp is the positioning of the increment and decrement operators. Saying ++x is different than saying x++. Placing the that operator before the variable means the operator is in the prefix position, and placing that operator after the variable means the operator is in the postfix position. If the increment or decrement operator is in the prefix condition, it means that the value of x will be incremented and the expression (++x) will return that new value of x. However, if the increment or decrement operator is in the postfix condition, then x will be incremented AFTER returning it’s value. In other words, the expression (x++) will return x, then increment it by one. For one line statements, the position doesn’t affect the result.

int x = 1;
x++;
++x;

In the above code snippet, the two statements do exactly the same thing: increment the value of x by one. However, suppose we run the following code.

int x = 1;
System.out.println(++x);
System.out.println(x++);
System.out.println(x);

The first print statement would print two since the expression (++x) returns the newly incremented value of x. However, the subsequent line would print two since the expression (x++) will return the value of x, then increment it. The final line will verify this claim because it prints three. If they’re being used in a larger statement, the position of the increment and decrement operators really do matter.

In this section, we learned about the unary operators as well as some additional information about the unary minus and increment and decrement operators that can save us headaches in the future. The unary minus operator only returns the inverted value of the operand but doesn’t change the actual operand. Regarding the increment and decrement operators, positioning them in the prefix position will return the newly incremented or decremented value; however, putting them in the postfix position will return the current value of the operand and then increment or decrement that operand after the completion of the statement.

Conditional Operators

2.6 – Conditional and Relational Operators

In this section, we’re going to look at relational and conditional operators that we can apply to variables and return boolean results. These boolean results will be particularly useful in the next section when we talk about decision control flow.

Like the arithmetic operators, these should also look familiar since they are quite commonly used, but we have to be very precise in our typing. We cannot interchange these characters: => is not valid Java! Note that the equality check operator is == and not =, the assignment operator. All of these operators return boolean values: either true or false.

2.7 – Truth Table for AND and OR

The conditional operators are the conditional AND and conditional OR. We use these on two booleans operands to return another boolean. In the above figure, we see a truth table for the AND and OR operations. Simply put, the AND operator only returns true if both of the boolean operands are true; the OR operator returns true if at least one of the boolean operands are true.

If we look at the truth table, we can see that we only need a single false for AND to return false and a single true for OR to return true. These exhibit what we call short-circuiting behavior. In an AND, this means that if the first operand is false, the second one won’t even be evaluated! For an OR, if the first operand is true, the second one won’t be evaluated either.

In this section, we learned about the different types of relational operators to check for equality and inequality. It is important to note the difference between the equality check operator (==) and the assignment operator (=). We can use the conditional AND and conditional OR operators to combine two boolean statements to return a boolean that depends on both of the boolean operands.

Control Flow: Decisions

Now that we’re learned about the relational and conditional operators, we can actually use them in both decision control flow and looping constructs. In this section, we’ll focus on the portion of control flow that relates to decision making. Suppose we only want to run a block of code if a particular condition is true. We can do exactly this using decision control flow. After we learn about decision control flow, we’ll move on to looping constructs.

if-then and if-then-else

The most basic of all control flow is the if-then statement. Suppose we want to check if a number is even or odd. We can do this via the following code snippet.

int x = 29846392741;
if (x % 2 == 0) {
    System.out.println(“x is even!”);
}

In the above code, “x is even!” will only print if the condition in the if statement is true. Let’s take a look at the syntax: the first thing we need is the “if” keyword. Following the keyword, the condition is in parentheses. The condition must be a boolean statement since it can only have two possible values. Next is the code that we want to run if the condition is true in curly braces. In general, blocks of code go in curly braces. Now if the condition is evaluated to true, then the lines of code in the curly braces will execute; if the condition is evaluated to false, those lines are skipped over entirely.

The above code only print outs whether x is even or not. Suppose we want to also know when it is odd. For this, Java has a construct called if-then-else. It works in a similar fashion to the if-then construct, except we have an else case that will execute if the condition in the if statement is false.

int x = 29846392741;
if (x % 2 == 0) {
    System.out.println(“x is even!”);
} else {
    System.out.println(“x is odd!”);
}

In either case, something is printed out to the console: the parity of x, either even or odd. If the condition (x % 2 == 0) is false, then the code in the else block will execute. But now suppose we want to know the sign of a number, which is common information to know about an number. However, we know that numbers can be positive, negative, or zero (due to the trichotomy law). This is three cases, not just two! It turns out we can combine our if-then and if-then-else into a construct that will let us test as many conditions as we want.

int x = -29846392741;
if (x > 0) {
    System.out.println(“x is positive!”);
} else if (x < 0) {
    System.out.println(“x is negative!”);
} else {
    System.out.println(“x is zero!”);
}

In the above code, we use “else if (condition)” in case the first condition fails. We expect this to print “x is negative!” to the console. But let’s look more into the code. The first if condition will be checked, and, if it is true, ONLY the code in the if block will run. Suppose it is false, then control will pass to the next else if condition, and, if that is true, ONLY the code in THAT else if block will run. In the case that none of the conditionals is true, then ONLY the code in the else block will run. In other words, once some condition is met or none of the conditions are met, only one block of code executes.

In this section, we learned about the most basic control flow statements: if-then and if-then-else. These statements will execute a block of code only if a condition is met. In the case of the if-else-if-else statement, all of the else if conditions will be checked in order until one is met, or, if none are met, the else block will execute.

Switch Case

In the previous section, we learned about the basic control flow statements, including the if-else-if construct where we can run different code for different conditions. But this can get very cumbersome if we are checking many conditions and want to run many different blocks of code. In this section, we’re going to look at a shorthand way of doing exactly this using the switch-case construct.

Suppose we have the following sequence of if-else-if blocks checking the resulting value from an HTTP request. Whenever we ask for a website or send information, our web browser gets back a status code to tell us how the entire transaction went. If we get back a 200, then we know everything went fine! If not, then the status code tells us what went wrong. The code below enumerates only some of the possibilities.

int x = 200;
if (x == 200) {
    System.out.println(“Everything is OK!”);
} else if (x == 404) {
    System.out.println(“Not Found!”);
} else if (x == 301) {
    System.out.println(“Moved Permanently!”);
} else if (x == 500) {
    System.out.println(“Internal Server Error!”);
}
// And so on…
} else {
    System.out.println(“Unknown Code!”);
}

As we can see, this can get very clumsy if there are many cases. One way to combat this awkward formatting and syntax is to use a switch-case construct. The below code performs the exact same function as the above code, but looks much cleaner.

int x = 200;
switch (x) {
    case 200:
        System.out.println(“Everything is OK!”);
        break;
    case 404:
        System.out.println(“Not Found!”);
        break;
    case 301:
        System.out.println(“Moved Permanently!”);
        break;
    case 500:
        System.out.println(“Internal Server Error!”);
        break;
    default:
        System.out.println(“Unknown Code!”);
        break;
}

The first thing we need is the switch keyword and the variable that we’re switching on. This variable can be a byte, short, char, int, or even a String. However, it can’t be a long, float, or double since those types are very large, and, in the case, of floats and doubles, they can have a near-infinite number of possibilities due to the fact they store decimal numbers. Afterwards, in the block of the switch case, we can have any number of case statements. These case statements check if the value of the variable we’re switching on is equal to the value after the case keyword. Looking at the first statement, “case 200:”, we’re checking x is equal to 200. This is important to note because we can’t do checks for inequality, such as less than or not equal to.

After the colon, the control continues until it reaches the “break;” statement. This break statement is crucial because it moves the control flow out of the switch case after execute the code of a particular case. If we don’t have that break statement, we get a phenomenon called “falling through” case statements. Consider above code snippet with a few break statement removed and the value of x changed.

int x = 404;
switch (x) {
    case 200:
        System.out.println(“Everything is OK!”);
        break;
    case 404:
        System.out.println(“Not Found!”);
        // Should be a break here!
    case 301:
        System.out.println(“Moved Permanently!”);
        // And another break here!
    case 500:
        System.out.println(“Internal Server Error!”);
        break;
    default:
        System.out.println(“Unknown Code!”);
        break;
}

Removing the break statement in the 404 case will cause it to “fall through” to the cases underneath it in the switch case until it reaching a case where there is a break statement. When this code executes, the console will print out the following.

Not Found!
Moved Permanently!
Internal Server Error!

This is not what we expect! We only expected the console to print “Not Found!” instead of three lines! This is because control will go into the 404 case, but no break statement will jump control out of that case and the switch case. Control will go down to the subsequent case statements and execute code in those cases until it finally reaches a case where a break statement exists. Hopefully, this example illustrates the danger of forgetting a break statement!

That being said, there are instances where we can safely use this “fall through” phenomenon. For example, suppose we want to print out whether x is a vowel or consonant, given that x is a lowercase letter in the alphabet and not anything else. There are more than one vowel, but we want all of them to print the exact same thing. We can use the “fall through” phenomenon to our advantage and write code that looks like the following.

char c = ‘e’;
switch (x) {
    case ‘a’:
    case ‘e’:
    case ‘i’:
    case ‘o’:
    case ‘u’:
        System.out.println(“c is a vowel!”)
        break;
    case ‘y’:
        System.out.println(“c is sometimes a vowel!”)
        break;
    default:
        System.out.println(“c is a consonant!”)
        break;
}

In the above snippet, the console will correctly print “c is a vowel”. Let’s take a closer look at what is happening. We know that c is ‘e’ so the first case isn’t executed. The next case is executed, but there’s no code or break statement! Therefore, control will “fall through” to the next case, which also doesn’t have any code or a break statement! This trend will continue until we reach the ‘u’ case. We see that there is code to print to the console and a break statement to get us out of the switch case. Success! This code does exactly what we want it to do, and we’re using the “fall through” phenomenon. If c was ‘y’ or none of the above cases, only the code in those case statements would execute and then break out of the loop. We’ll look at break statements again when we talk about branching statements after for loops.

In this section, we looked at a cleaner way to display many if-else-if statements: the switch-case construct. This construct only allows us to check for equality and requires us to put break statements after the code for each case, or control will “fall through” to all subsequent cases until a break statement is encountered. However, we learned that we can use this phenomenon to our benefit if we want to have a block of code run only once for multiple cases.

Control Flow: Loops

Besides decision-making constructs, loops are the other important part of control flow. Loops allow us to run the same block of code while a condition holds true. In this section, we’ll talk about the main three loops: while, do-while, and for. In addition, we’ll also be looking at arrays agains and seeing how we can use loops in conjunction with arrays. At the end of this section, we’ll also look at branching statements, like break and continue, which allow us to manipulate control flow even more thoroughly.

while and do-while loop

The most basic of all loops is the while loop. Suppose we want to sum up all of the numbers between 1 and 100. Carl Friedrich Gauss, a very famous mathematician and child prodigy, actually did this by hand as a child in the 1700s! But let’s use a while loop instead to sum these numbers up.

int sum = 0;
int i = 1;
while (i <= 100) {
    sum = sum + i;
    i++;
}

We get the same answer Gauss did a few centuries ago! Let’s take a closer look at the code. First, we declare two integers, one to hold the sum and another as a counter variable. In this case, it is ok for us to use a single letter to use as a counter variable since that is the sole purpose of it and it is convention to use ‘i’ (for index) or ‘j’ or ‘k’ as counter variable names. Next, we have the while construct that will execute the code in the curly braces until the condition is no longer met. First, the boolean condition is checked to see if it applies, then the sum is added. If we remember back from the Operators section, we could have expressed the sum more concisely using compound assignment operators: “sum += i;”. The next line is crucial to the loop because it increments the counter. If we forgot to do this, then the loop would never end! We call this an infinite loop when the condition is always true and control never exits the loop. Our loop counter will go from one to 101, since that is the number that gets us out of the loop. What we have is the sum of all numbers between one and a hundred! Note that the condition in the while is like that of the decision-making control flow in the sense that it can be any boolean so we can use relational and conditional operators too.

Suppose we are writing a bookkeeping program that requires the user to input some price. We know that a price can only be zero or any positive number. In other words, we can’t have the user input a negative price. But we also don’t want to terminate the entire program if the user makes a mistake! What we really want is to keep asking the user for a valid price until they do. Instead of a while loop, a do-while loop would be perfect here.

double price = -1;
do {
    price = askUser(“Please enter a valid price: ");
} while (price < 0);

In the above code, assume askUser is something that asks the user for a price and return a double. We’ll be talking more about methods later. First, we set the price to an invalid value starting off. Then, we have our do-while construct. The main difference between the while and do-while loops is that the do-while loop’s condition is check AFTER the loop runs. This guarantees that the loop runs at least once, which is exactly what we want. We want to give the user a chance to enter a valid number at least once. The do-while loop will ask the user for a price first. Suppose that price is valid, then the loop condition would be false, and control would break out of the loop. Suppose it was false, then the loop condition would be true, and the loop would run again, asking the user to input a valid price again. This cycle would continue until the user finally enters a valid price. Do-while loops aren’t used as much as while or for loops, but they’re great for input validation!

In this section, we looked at two of the most basic loops: while and do-while loops. The while loop will execute the code in the curly braces until the loop condition is false. The do-while loop will do the same thing, except for the key difference that the condition is checked at the end of the loop. Code in the do-while loop is guaranteed to run at least once. This makes the loop ideal for input validation.

for loop

After looking at the basic loops, we’re going to look at a more complicated loop: the for loop. Java also includes an extension of this called for the enhanced for, or for each, loop. We’ll also look at how we can use loops to declare and manipulate arrays using both for and for each loops. To learn about these new constructs, let’s first look at something we know.

int i = 0;
while (i < 100) {
    System.out.println(“Counter is at “ + i);
    i++;
}

We know this is a while loop that will simply print out “Counter is at “ and the current value of the counter variable. Note that this loop will run a hundred times since, within the loop, the counter will run from 0 to 99 inclusive, which is a hundred times. If we had a more complicated loop, then this would take more lines. We can represent the same while loop as the following for loop. (Technically, in the above while loop, we need to wrap the whole snippet in an instance initialization block so that the counter variable’s scope expires after the loop executes.)

for (int i = 0; i < 100; i++) {
    System.out.println(“Counter is at “ + i);
}

The previous two code snippets will produce the exact same output. The for loop is a nice, compact way to represent a while loop. There are three parts to a for loop: initialization, condition, and update. The initialization is where the loop counter is created and set. Following initialization is the condition, which is the same as the while loop. Finally, we give the statement to alter the loop variable to break out of the for loop. The update step doesn’t necessarily have to increment the variable. Instead, we could increment by two or decrement by seven, but we need a way to exit the loop.

For-Loop-Parts

So far, we’ve only looked at looping being used for printing to the console, but we can also use them to initialize large arrays. If we remember back to arrays, we know that we can initialize an array using the curly braces array initialization syntax. But what if we wanted to create a blank array of a hundred elements? We certainly don’t want to have type in a hundred zeros! Luckily, we can use loops to do this job for us.

int[] data = new int[100];
for (int i = 0; i < data.length; i++) {
    data[i] = 0;
}

In the above code, we initialize an array of a hundred elements. Using a for loop, we set each of those elements to zero. Note that we can get the length of an array by calling “someArray.length”. In the for loop, we’re setting the ith element of the data array equal to zero. The counter variable i goes from 0 to the length of the array. Our condition is strictly less than instead of less than or equal to because array indices start at 0! There is no such thing as the 100th index of an array of size 100!

Suppose we now want to print out each of elements of our data array. We could write another for loop that iterates through each element and prints it. There is another type of for loop that we can use when we just need to look at the elements of an array and not change them. We call this the enhanced for or for each loop. The syntax is more concise than the standard for loop.

for (int datum : data) {
    System.out.println(datum);
}

In the above code, we’re saying that for each datum in the data array, print it out to the console. This gives us a way to iterate through an array and see each element without having to worry about the array index, length of the array, or increment conditions. We can also iterate over List, Queues, and other Java collection types.

Branching Statements

To give us more control over loops, we have these statements call branching statements. We’ve already seen one before: break. The break statement allows us to forcibly exit the nearest loop. We have another statement called the continue statement that allows us to skip the current iteration of the loop. For example, suppose we were iterating through each character of a phone number and only printing out the digits. If the user supplied us with parentheses or a hyphen, then we need to skip over it.

String phoneNumber = “012-345-6789”;
for (int i = 0; i < number.length(); i++) {
    char number = phoneNumber.charAt(i);
    if (number == ‘-‘) {
        continue;
    }
    System.out.println(number)
}

In the above code snippet, we use a for loop to iterate through the String. We’ll talk more about methods later, but we can get the length of a String by calling .length() on it (as opposed to just .length for arrays). To get a single character from a String, we can call .charAt(…) and pass in an int to get the character at that particular index. The interesting part is in the if statement. We say that if the number is actually a hyphen, we use the continue statement, skipping over this current iteration and moving on to the next one.

Now suppose we replaced that continue statement with a break. Then the program would exit the loop and stop printing to the console. The console would only show the first three digits since after those, the loop encounters a hyphen; therefore the program breaks out of the nearest loop, which is the for loop. If we had nested loops, the break statement would only get us out of the nearest, or most indented, loop.

In this section, we learned about the two branching statements: break and continue. Break allows us exit the nearest loop. Continue allows us to skip over the current iteration of the loop and move to the next iteration. These control statements will allows us finer-grain manipulation of loops.

]]>
Zero-Day Java Guide 1 – Installation and Hello Variables https://gamedevacademy.org/zero-day-java-guide-1-installation-and-hello-variables/ Wed, 14 Oct 2015 02:22:38 +0000 http://androidkennel.org/?p=1160 Read more]]> Computers can do some amazing things: track trends in data to predict the stock market, identify text and handwriting in images, and even perform delicate surgery! Ironically, the computers that we praise so much are really the dumbest invention of mankind. They can’t do any of these things by themselves; they were told very precisely how to perform these operations by a human.

At the very low level, computers can only understand binary, ones and zeros, which are incomprehensible to humans. Imagine reading this book in binary! This one of the big motivations behind why people have invented programming languages: they are human-readable, logical, and have a precise syntax that can be converted into binary to tell a computer what to do. Programmers, developers, and software engineers write source code in programming languages to build desktop apps, mobile apps, hardware interfaces, and even airplane controls!

The journey that we’re about to embark on will take us through one such programming language: Java. We’ll start our journey the same way we would start with any other programming language: building the iconic “Hello World” program. Beyond that, we’ll move on to talk about what variables are and how to define them. Building on our knowledge of variables, the next section will show us operations that we can perform on those variables. From that knowledge, we’ll use operators to make decisions in our programs and repeat code. Towards the end of this book, we’ll get to the real power behind Java: object-oriented programming.

“The journey of a thousand miles begins with one step.” – Lao Tzu

What is Java?

Java is a programming language originally developed by Sun Microsystems (now Oracle) in 1991. Specifically, James Gosling is credited with Java’s creation. Since then, it’s had many revisions and has grown to be one of the most widely-used programming languages. On GitHub.com, a popular website to host software projects, there are well over a million projects that use Java. It’s used everywhere from native desktop applications that we run on our computers to web servers that bring us our favorite websites to mobile apps that we download to our phones. This is the type of programming language where one can just create a file and start coding without having to configure any compiler to a specific system or memorizing messy terminal commands. This is even easier using other programs, called Integrated Development Environments (IDEs), to help with writing Java code.

JavaVM

Since its conception, the motto for Java has always been “Write Once, Run Anywhere.” This paradigm is becoming more standard to the world of programming languages. Decades ago, other popular languages, such as C and C++, have to be recompiled for each machine we run it on. The job of the compiler is to convert human-readable source code into binary that our computer can understand. However, Java’s compiler will convert Java source code into Java byte code, which can only be understood by the Java Virtual Machine (JVM). The JVM is installable on any major operating system: Windows, Mac OS X, Linux, and more. Therefore, a Java program can be run by any operating system that has the JVM installed. Odds are, our machine already has it installed by default. However, we’ll need to install the utilities that we can use to compile our own Java code, and, although we could type in our Java code into a text editor, we’re going to use an IDE that will make writing Java code much easier.

Eclipse and JDK Setup

JDK Setup

JDK-Download-1

JDK-Download-2

Before we can begin programming in Java, we’ll need to install the tools that allow us to compile Java source code into Java byte code to be run by the JVM. These are the Java Developer Tools (JDK), and they can be found at Oracle’s website. We need to download the latest version and the appropriate version of the JDK for our operating system: 32-bit or 64-bit (x86 and x64 respectively). Go through the installer, pressing “Next” at each step and allowing it to complete. The installer will copy the Java tools to an appropriate folder (C:Program FilesJavajdk-… on Windows for example). If we were on Mac OS X, we would already have Java and the JDK installed, even though Apple uses an earlier version of Java. To verify this, we can open a terminal and type “javac -help” and it should print out options. In order to get the same effect on Windows, we would have to add the JDK directory to our PATH environment variable, but that’s not necessary for Eclipse because Eclipse can find our JDK directory by itself if we installed it in C:Program Files for example.

Eclipse

Eclipse-Download-1

Eclipse-Download-2

After we install the JDK, we have the barebones tools to compile and run Java code. Whereas coding Java in a text editor, compiling it, and running it may work for a small number of files, to properly manage a larger project, we’ll need an Integrated Development Environment (IDE). We’ll be using Eclipse since it’s free, open-sourced, and one of the most common IDEs to start Java development. To download Eclipse, we’ll need to visit the official Eclipse website and click the “Download” button. We have to be careful which Eclipse package we download. Eclipse has many different packages for different programming languages and systems like C/C++, PHP, and web applications. We’ll need to download the “Eclipse IDE for Java Developers” package in the same architecture (32-bit or 64-bit) as our computer.

Eclipse should be a ZIP file or a DMG on Windows or Mac, respectively. After opening or mounting the archive file, we’ll either find a folder or the application executable. On Windows, we’ll move the eclipse folder somewhere else in our filesystem, and inside is the eclipse.exe file that we can create a desktop shortcut to if we want. On Mac OS X, we can simply drag-and-drop the application executable in our Applications folder.

After launching Eclipse, it will ask us for a workspace to use. We can either choose the default workspace Eclipse gives us, or we can create our own folder to act as our workspace. Within our workspace folder, we’ll store different projects created and managed by Eclipse. Developers commonly have multiple workspaces for different contexts, such as one for work and one for personal projects. For our purposes, we’ll only need a single workspace.

Eclipse

After selecting a workspace, Eclipse will have a greeting screen that you can exit out of by clicking on the ‘X’ on top-left tab. Finally, we’ll be able to see the Eclipse IDE. It might seem overly complicated at first, but all of those views will make sense very soon when we get to coding in Java. On the left, we’ll see our Package Explorer view that contains all of our projects and their related files. To the right of that is the main window where we’ll type in our Java code. Clicking on a file will open that file in the main window. At the bottom of the main window, there are several tabs such as Problems, Javadoc, Progress, and, most importantly, Console. We’ll be using the Console to view our program’s output. Right of the main window, we have our Outline view. This view keeps track of any member variables, methods, or inner classes that we have in the source code file that we’re currently editing. However, this view won’t be immediately useful when we’re talking about variables, operations, and control flow that are all contained in a single method, but this view will become invaluable when we move on to object-oriented programming.

Java Basics

Hello World

In this section, we’re going to write our very first Java program! It’s a longstanding custom to write a program that prints “Hello World!” to the console when writing our first program in a new programming language so we’ll be doing exactly that. To begin, we’ll need to create an Eclipse project first by going to File->New Java Project.

Eclipse-New-Project

We’ll name it “MyFirstJavaProject” or something similar to that. Under the JRE section, make sure that we’re using JavaSE-1.8 or whatever the latest version of Java is at the moment. The new features will become apparent towards the end of the book when we’re talking about lambda expressions, for example. We’ll click on “Finish” at the bottom to create our project. After creating that project, we should see it in our Package Explorer view on the left pane. If we expand that project, we’ll see a folder called src, which stands for “source,” that doesn’t have anything in it.

Eclipse-Package-Explorer

Let’s add a source code file. We can do this by right-clicking on the src folder and clicking New->Class. We can name this class “HelloWorld” (with no spaces).

Eclipse-New-Class-Dialog

HelloWorld-Java

Although a Java class is not quite the same as a source code file, each Java source code file can only have a single top-level construct that is the name of the Java source code file. We’ll talk more about what classes and nested classes are towards the end of this book, but keep in mind that there is a distinction between a Java class and a Java source code file. There are other fundamental Java constructs, such as interfaces, that also reside in a Java source code file, but we’ll talk more about those later as well. This difference becomes more apparent if we expand any source code file in our Package Explorer and see that the first item after we expand will be the class (or interface).

In this paragraph, I’ll just give a short description of what packages are even though we won’t be using them. A large, complicated Java project might have tens or even hundreds of Java classes or interfaces. To better organize them, Java has packages which group related classes together. For example, in the Android API, there are hundreds of packages grouping similar software components such as views, location providers, and media players. Packages are meant to contain classes that support each other or share much functionality, and they are represented in our filesystem as folders within our source directory. When we don’t specify a package, Java uses a default package and stores any classes in the default package directly in the source folder.

Anyway, after Eclipse creates our class, it’ll appear in the main window and we should see the source code for our class. The first thing we have to do is to tell Java where to start the program. We do this by using the main method. In most compiled programming languages, there is a method or function, usually called “main,” that the system, or in our case, the JVM, will look for when we tell it to run an executable file. It signifies the entry point of the entire program. This concept works because these main methods have a very particular signature. In Java, the main method, or entry point of our program, looks exactly like this:

 public static void main(String[] args) {
 }

Let’s add this within the curly braces of the HelloWorld class. We see that Eclipse will automatically indent our code for us, which ultimately makes it more human-readable (the original purpose of a programming language anyway). This syntax might seem strange at first, but we’ll learn more about what the parts of it are when we talk about methods. For now, let’s say that this is the exact syntax of our main method. Within the curly braces, we can type our Java code, and it’ll be executed by the JVM line-by-line essentially. If we were to run our program right now, Eclipse would select the Console tab automatically and we would see a blank console. This is because we haven’t done anything in our main method yet! For us to print something out to the console, we’ll have to use to following line of code

 System.out.println(“Hello World!”);

HelloWorld-Final
It’s important that we type this out instead of copying-and-pasting it so we get a better feel for how to type Java code. It’s also important that we type out that code very precisely. As I’ve mentioned before, a programming language is very strict in it’s syntax. I’ll explain more about that line of code and console output in the next section, but all that’s left to do is to run it. We can run our code by right-clicking on the source code file in our Package Explorer and selecting Run As->Java Application.

Run-As

The console window should appear on the bottom pane with the text “Hello World!”
Congratulations! We’ve just written our first Java application!

Console-Output

Console Output

In the previous section, we wrote our very first Java application: HelloWorld. In this section, we’re going to learn more about console output and dissect our HelloWorld program, particularly the line that prints text out to the console. Throughout this book, we’ll be using the Java console to get input and display output. The console is simply a text interface where we can interact with the program and see it’s output. It’s similar to a command line or terminal, except we can’t run any standard commands on it. In fact, the earliest of computers didn’t have a graphical operating system like Windows, Mac OS X, or Linux; they just had a command line with a blinking cursor that users would type commands into!

Let’s take apart the line of our program that actually prints text to the console. If we remember from our HelloWorld program, we used the following line to print out to the console:

 System.out.println(“Hello World!”);

The first phrase we see is “System.” This is retrieving the operating system’s console streams. Next is “out.” This indicates that we want to use the standard output stream. Finally, we have the method call “println(“Hello World!);” The name of the method is “println” (short for print line). Following all method calls must be a set of parentheses that contain arguments, if any, to that method, namely “Hello World!” in our case. But “Hello World!” is what we call a String, more precisely a string of characters. To put this all together, we are telling the operating system’s standard output stream to print the line being represented as a string “Hello World!” We’ll expand our knowledge on this later, but this is essentially what the line of code does. We’ll be using it later on to print whatever we want to the console to see the consequences or results of operators or loops.

Errors

In this section, we’ll learn about the difference between compile-time and run-time errors as well as general tips on how to spot the sources of errors and how to fix them. Luckily, IDEs have grown to be very intelligent in their means to help the developer fix errors by proposing solutions. It is very important to note that the suggested solutions DO NOT necessarily align with what our intentions are. They’re simply just suggestions on how to make the error go away, not necessarily how to fix your program’s logic. We can use them for general guidance and common errors, but we shouldn’t rely on them for every error we might encounter.

There are two main types of errors that we might encounter in while writing Java code: compile-time and run-time. Compile-time errors occur when we try to run the Java program and it crashses. These kinds of errors are very easily picked up by Eclipse and any good IDE will suggest a fix for them. Attempting to run the error will cause a syntax error to occur and the entire program crashes without executing a single line of code. If our project has any compile-time errors, when we try to compile, Eclipse will ask us if we really want to compile incorrect code. This is usually a sign that we need to go back and look for compile-time errors.

Compile-time-error

On the other hand, run-time errors, as their name suggests, occur when we try to execute a Java application. Run-time errors compile perfectly fine, but, if we tried to run a Java application with a run-time error, it would crash when the JVM arrived at the byte code of the error. Any lines of code above the run-time error in the Java file will run just fine, however. Although IDEs are getting smarter and finding them, these types of errors are significantly more difficult to detect.

Run-time error

When errors occur, Eclipse will help us find the exact line that caused that error to occur. In the console output, we might see something like

Run-time-console-output

 Exception in thread “main” java.lang.SomeKindOfException: For something strange we tried to do!
 at java.lang.SomeKindOfException.someMethod(SomeKindOfException.java:55)
 …
 at HelloWorld.main(HelloWorld.java:9)

This is called the stack trace, and it’s very helpful for assessing what went wrong and where it went wrong. SomeKindOfException would obviously be replaced by a real type of exception that gives us some clue as to what went wrong. For example, if the console said FileNotFoundException, it’s intuitive to think that we were attempting to access a file that didn’t exist at a given file path. After the type of exception, there’s a short comment that explains even further. Following an exception, we’ll see a list of indented statement that start with “at” and list off method calls, source code files, and line numbers. If we click on one of those blue links, Eclipse will take us to that source code file and line number. This being said, it won’t be useful to look at Java’s Integer class, for example, since that’s probably not where the error occurred. We should skim that list of method calls until we find a class that we’ve written, like “at HelloWorld.main(HelloWorld.java:9)” for example. Clicking on that blue link will take us to line 9 in our HelloWorld.java file, the exact spot where the JVM said the error occurred. From this information, we can have a good chance at fixing the error.

In this section, we created our very first Java program that printed out “Hello World!” to the console. We then dissected our HelloWorld program to and saw how we can print anything we want to the console. In the next subsection, we looked at how we can handle any potential errors that might appear when we’re programming in Java as well as how to go about fixing them using Eclipse’s debugging tools. In the next section, we’re going to delve into Java code and talk about how we store information.

Variables

If we remember back to our algebra class, we know that, mathematically, we can have containers for information called variables. This is true in programming as well. Programmers need a way to store data in a program, and we do this through variables. In this section we’re going to learn about the different types of variables as well as how we can store multiple values in a single variable.

Variable Types

It is important to note that in Java, variables are strongly-typed, meaning that when we want to declare a variable, we must specify the type of variable it is. Java has many built-in primitive types that can hold different kinds of numbers, characters, and boolean values. From the table below, you can see that most of the Java primitive types are some kind of number. Take note that only floats and doubles can hold decimal values; the rest of the number primitive types can only hold integers, or positive and negative numbers with no decimal part.

Data-types

Now that we’ve seen all of the variable types, let’s see how we can declare a variable:

int someNumber;

The first thing that we have to do is to state the variable type; then, we need a name for the variable. This name allows us to refer to the content of that variable. We see that the statement ends with a semicolon. All statements in Java need to end with a semicolon because it tells the Java compiler that this is the end of a complete statement. In the above statement, we’re essentially declaring a space in our computer’s memory for an integer. We haven’t set it to any value, so Java will set the value to be zero, by default. In fact, zero is the default value for all number types. A character’s default value is ‘\u0000’, and boolean’s default value is false. If we wanted to declare and initialize this variable to some value like 5, we can do something like this

int someNumber = 5;

After this line, someNumber will have an integer value of 5. This statement is the longer equivalent to

int someNumber;
someNumber = 5;

We can declare multiple values and set them equal to each other as well.

int anotherNumber = someNumber; // anotherNumber has the value 5 as well

One thing to note is that, as you progress down the table of number values, the number types are allowed to hold values that are a type above. This means that a double can hold a value such as 3, even though 3 is technically an integer. However, the double will represent it as 3.0. This does not work in both directions, however, because Java will throw an error if you try to store a value of 3.14 in a variable whose type is int.

Characters and booleans are a little different than number types. For booleans, the only two possible values are true or false. chars are single-character unicode values and are denoted by single quotes.

boolean lightOn = true;
char firstLetter = ‘A’;

Variables can’t be named anything. First and foremost, we can’t name a variable after a reserved Java keyword, such as int or boolean. A variable can’t start with a number or have any whitespace in it. Although variables can start with a dollar sign and underscore, it’s against Java standard conventions. Throughout this book, we’ll be using the camelCase naming convention where the first word is lowercase and every successive word is capitalized. Also, it doesn’t help to name variables short, one-or-two-letter names such as km when you mean keyMap. The only place where that makes sense to do so is in loop counters, which we’ll get to soon! We’ve covered all of the Java primitive types, and now we’re going to move on to another useful data type called a String.

Strings

A String is a sequence of characters. That’s why it’s called a String! It’s supposed to represent a string of characters, including special characters. A String isn’t a primitive type, and we know this because String is capitalized. All of the primitive types are lowercase, but, by convention, class types are capitalized. Therefore a String is actually what we call a reference type. We can declare a String like any other variable, except the value is in double quotes.

String myFirstName = “Mohit”;

If we have two strings, we can concatenate them together using the plus operator that we’ll talk more about in the next section. We can also get the length of the string by calling an instance method on the variable called length().

String myFullName = myFirstName + “ Deshpande”;
myFirstName.length();

Suppose we wanted to store an entire file in a String. We’ll need to think of a clever way to encode things like line breaks, tabs, or quotes. Java has constructs called escape characters that we can directly insert into Strings so that when we go to print the String out to a console, we’ll see the line breaks and quotes. For example, if we wanted to insert a quote or new line.

String quote = “Neil Armstrong said \n\t\”That\’s one small step for a man, one giant leap for mankind.\” \n \\”;

If we were to print quote out to the console, it would appear something like this

Neil Armstrong said
    “That’s one small step for a man, one giant leap for mankind.”
 \

Escape-Sequences

The above table shows the most common escape sequences that Java support. When using an escape sequence, we can just type that exact sequence of characters, and Java will treat it as an escape sequence and not as just two subsequent characters. Now that we’ve covered the different types of variables, we’re going to learn how to store multiple values into a single variable.

Arrays

Let’s suppose that we want to store a list of names or a list of grades. We could create a new variable for each name or for each grade. This would get cumbersome very fast if we had 30 names, for example. We want to be able to create a single variable to store all of those values. Luckily, we have a construct in Java that allows us to do that: arrays.

Arrays

An array allows us to store multiple values in a single variable. Take the above image for example. This is roughly what an array looks like in our computer’s memory. We’re declaring an array of doubles called grades and assigning it these values. A very important concept to remember is that Java arrays are zero-indexed. This means that the first element or entry is at position zero. You can think of the index as being the distance from the first element. The distance from the first element to the first element is zero; the distance to the second element from the first element is one; and so and and so on. The length of an array is constant and cannot be changed after declaration or initialization.

double[] grades = new double[10]; // declaring an array with 10 elements
grades[0] = 90.7; // changing the 1st element
grades[1] = 87.4; // changing the 2nd element
…
grades[9] = 94.7; // changing the 10th element

The ellipsis just takes place of the other elements. This is how we can access and change values of an array, using the square bracket notation with the index inside of the brackets. As you see in the above example, this might get very cumbersome if we have a large array. For this exact reason, we can declare and initialize the array at the same time using curly braces. Note that the length of the array is still fixed since we are providing the number of elements in the curly braces.

double[] grades = { 90.7, 87.4, …, 94.7 };

We can declare an array of any type, but we are not allowed to mix types in an array. In the above example, we can’t add a String in the array of doubles. We can even declare multidimensional arrays, although we won’t be using them for our purposes. For example, suppose we wanted to store two-dimensional coordinates for a video game we’re developing. We could do the same thing with nested curly braces.

int[][] points = { {1, 2}, {3, 4}, {5, 6}, {1, 1} };
points[0][0] = 4; // set’s the x of the first ordered pair to 4: { {4, 2}, …}

Arrays are a Java construct that allow us to store multiple values into a single variable. It is important to note that Java arrays can only hold a single type and are a fixed length. They are also zero-index, meaning to access the nth element, we need to use the(n-1)th index. In other words, array elements start counting at zero.

To recap, in this section we learned about the different types of Java variables, how to declare them, and how to initialize them to values. Most of Java’s primitive data types are numbers, with the exception of chars, which are characters, and booleans, which are only true or false values. Among the number types, only floats and doubles can hold decimal values. We also learned that Strings can hold a sequence of unicode characters and are good for storing alphanumerical data such as text. After learning about the variable types, we saw how we can store multiple values in a single variable using a construct called an array. Strings and arrays are zero-indexed, meaning that the first character or element is at index zero. In the next section, we’re going to see how we can use operators to perform actions on these variables.

]]>
Free eBook – Java Programming for Human Beings https://gamedevacademy.org/free-ebook-java-programming/ Wed, 14 Oct 2015 01:06:17 +0000 http://androidkennel.org/?p=1163 Read more]]> We are happy to announce the launch of our free ebook Java Programming for Human Beings – The Ultimate Beginner’s Introduction, authored by mobile application developer, contractor and online trainer Mohit Deshpande.

The book covers the basics of the Java programming language and assumes no prior coding experience. Java is one of the most widely used programming languages these days and it’s used to create Android apps, web applications and Enterprise software.

We hope this free ebook helps you gain valuable skills and we look forward to hear about the cool stuff you’ll be building if you continue down this path.

This book is provided at no cost both in PDF and MOBI formats.

Download the ebook ]]>