The future has come- Hi. I do confirm that this is Java tutorial. I hate boring lectures, so CodeGym is made like an online quest game. - Have you ever played and leveled characters? Sometimes you don’t even notice how you got involved, right? Do you smell what I’m cooking? In CodeGym you also have to level a character from level 1 to 40 (and when we release the second part, up to level 80). You’ll become a good Java developer when you pass the game. - You will be able to get a Java Junior job when you complete 40 levels. That’s because CodeGym has a lot of real-world tasks. A great many. - You start with the first level. Your mission is to upgrade your character - Amigo. But let’s start small. Firstly you gotta get to the second level. Maybe you gonna like it so much that you don’t notice completing the course and will start working as a Java programmer. :) P.S. - The lectures are arranged in this way: the latest one is on top. To open a new lecture push the Green Button.
BackgroundThe game takes place in far-far future, in 3015, where robots and humans are living together on the Earth and one can travel through space. There is a spaceship that crashed on an unknown planet. Captain John Squirrels the Brave says: - The Galactic Rush spaceship suffered a serious wreck. The ship crashed into a mountain when falling and was almost completely covered with stones. A few days were spent in futile efforts to free the ship. The crew had lost all hope of returning home and began to settle in... Elly says: - A week hence, I came to find out that the planet is inhabited by... thousands of wild robots! Only they have no skills. We would like to use them to remove rocks from our spaceship, but they can do nothing. Their help would be very useful in our situation. Professor says: - A few days later I found a way out. It occurred to me to take Diego’s firmware (a robot in the crew), to reprogram it to bricklayer’s firmware and to upload it unto wild robots. - However, the ill luck seemed to pursue us. After a little research, it appeared that robots got no slots to upload firmware. They didn’t have any slot for reflashing! Bilaabo says: - Bilaabo remembered that once on our home planet I saw a robot who knew programming. He wrote a new firmware on his own. Professor says: - When Bilaabo told about it, a stroke of genius came over me. After all, once I taught a talented young robot to program in Pascal. - I ordered to catch the most talented young robot and teach him programming. Then he would be able to write a bricklayer firmware by himself and help us.
From left to right - Risha Gatesman (a bureaucrat in 16th generation), Amigo (you)Risha says: - We caught a smart specimen. Diego asked to name him Amigo, in honor of his brother, whom he had never had. - I offered Amigo metal beads for each training month and ten bucks a year for further debris removal. Diego says: - I was outraged by such a bald-faced rip-off, but the entire crew took the side of Professor and Risha. Of course, I agreed (externally) and offered to help teach Amigo. (heh heh heh!) Not least because no one teaches the robot better than another one does. - Everyone was delighted with my compliance. They also decided to participate in the new robot’s training.
1 Getting startedAmigo had jitters. He was confused, his mind racing, eyes twitching and growing cold at the thought of the last night. These strange creatures, his yesterday’s acquaintances, want something from him. Something so strange and inconceivable that even he, who considers himself the most intelligent and courageous among his peers, starts nervously chewing punchcards at the mere thought of it. They want to teach him how to code! Program with Java! Are they kidding? Even the greenest robot knows that robots are the result of the Creator’s divine disposal.
Worse yet, they don’t just say that it’s possible. They’re going to do it. And he, he gave his consent. He agreed! Why? He will become a Java programmer. Are they going to turn him into Creator?! What for? Just for fun? Where’s the catch? What if I gonna have to glitch and suffer till my battery’s dying day? The temptation was great, he just couldn’t help it. He has always been aspiring and wanted more. But no one could expect such a proposal. Of course, he tried to stall for time, but then the visitors threatened to choose another robot. Perhaps it was someone’s nasty trick? No, it rings true. He saw the proof. It really happened to him, and he agreed. Unless the visitors lie, he really will become a Java programmer. The first ever robot programmer… He is the chosen one! That’s the whole point. He will learn to program and will write programs. His own programs. Anything he wants! He will carry the light where darkness has always ruled. He will be honored, he will be worshiped. And all the dissenters… - Hi there, Amigo! I’m Risha Gatesman. I will help you with learning Java. A quiet voice took Amigo out of his train of thoughts and brought him back to the sober reality. He sits in the very heart of the visitors’ spaceship. Isn’t it rather much for just a seventh grade robot? The stranger kept talking. Well, the die is cast now. Once he’s here, he will learn. He will study hard but, for a start, he will just listen. - I’m with the Galactic Rush for many years, but I see such a planet for the first time. I would like to get to know you better. For a start, could you tell me how you learn? You study, don’t you? - Yes, we share our knowledge. We got preacher lecturers. They give their lectures, and we listen. Sometimes we make notes. Then, everyone tells a robolecturer how he picked up what he had heard. If the robolecturer likes an answer, one passes a lecture. - It’s absurd! It is no wonder that your civilization came down to ignorance. - We’re not ignorant. Whatever gave you that idea? Amigo was startled by his own impudence. Arguing with visitors? How flippant! Why, he had just made himself a promise to listen to them! - Any advanced technology is often indistinguishable from magic. - Risha paid no attention to Amigo’s outcry. - In addition, considering your level... you probably think all technologies are magic. Tell me what’s going on inside a program? - A Java program is a divine work. Is it possible to understand its essence? - Yes, Amigo, you can understand it and faster than you think. All the things seem complicated, or even worse, incomprehensible, when there’s something you don’t know. But if there’s a good teacher who will explain everything in laypeople or in layrobots terms, you’ll be amazed at how you could consider such a simple thing complicated. - Not only knowledge, but skills and principles as well are important. Though I have extensive knowledge, I’m first of all a bureaucrat, a bureaucrat in 16th generation. - And it’s really great! My bureaucrat skills helped me create the best Java lessons for you. Here is everything: problems, programs, games, tasks, pictures and even lectures. - Even (!) lectures? – There was a true astonishment in Amigo’s voice. - Yeah. It was proven in the 22nd century that a good lecture is just a little more effective than a good book. An ordinary lecture is even worse than an ordinary book. Considering that now we have rather limited training aids and can’t give you a run through a standard 28th century training simulator, we have to opt for quite simple methods. We came up with a crazy mix of games, tasks, pictures, lectures and video. - You’ve got me intrigued. - I hope so. Interest and intrigue are the basis of all learning. - «When a student gets bored, the teacher must be batted» – a quote from the 24th century education law. - What a good quote … - Yes, it is. Let’s say a movie has a bad box-office, then it’s the director’s fault and not the audience’s. If something is boring, it’s not you who are to blame. They should do exciting movies, entertaining lessons, and then they’ll have no end of the public. - I totally agree. And I am ready to have entertaining lessons! - Fine. So let’s get started. Risha voice was mesmerizing, and Amigo hanged on every word. - The program is a command set (command list). The first command runs first, then the second, third, and stuff like that. When all of the commands are executed, the program ends. - And what are commands? - It depends on the executor, on what commands the executor knows (and understands). - A dog can be given commands «Sit!», «Bark!», a cat - «Shoo!» a man - «Don’t move, or I’ll shoot!», and a robot «Work! Do get on, yo robomama!» - And yet... - Amigo now looked much more cheerful. - JVM (Java Virtual Machine) runs programs written with Java. JVM is a special program that can execute programs written with Java. - The command list is rather extensive. For example, this command displays the text «A robot is man’s best friend».
"So Creator took metal and made a robot of it in his image and likeness. And He created Java programs - souls of robots, and uploaded them onto robots, and made them alive."
- O_O - However, we won’t start immediately with commands, but with a couple of simple principles. - Knowledge of some principles may substitute for knowledge of many facts. - The first principle. - In the Java programming language, there is the practice to write each command at a new line. A semicolon shall be put at the end of the command. - Let’s say we want to display the message «A man and a robot are as thick as thieves» three times. Here’s how it will look like:
|The simplest command is:|
- The second principle. - The program consists not only of commands. - Imagine a room. The room can’t exist on its own. It’s part of some apartment. The apartment isn’t on its own too, it’s in a house. - Again, we can say that the house comprises of apartments, and apartments consist of rooms. - So far, it’s clear. - So the command is like a room. In the Java programming language, the command can’t exist on its own, it is part of a function (Java functions are also called methods). A method is part of a class. In other words, classes comprises of methods, and methods consists of commands. - So the class is an apartment house, the function / method is an apartment, and the command is a room. Do I get it right? - Yep, absolutely. Amigo looked at Risha almost reverently. This man explains to him the basics of the divine Java! And he has just understood that programs consist of classes, classes comprise of methods and methods include commands. Amigo hasn’t yet understood if it’s necessary, but he was sure this knowledge will make him the most powerful robot of the planet. Meanwhile, Risha continued: - Java programs consist of classes.There can be tens of thousands of classes. A minimal program comprises of one class. For each class, an individual file is created which name matches the name of the class. - Let’s say you’ve decided to create a class that will describe a house. So you need to create a class House, which will be in the file named House.java. - If you have decided, say, to describe a cat, then you need to create the Cat.java file to describe the Cat class in it, etc. - A file contains a Java code (text). Usually a class code consists of a class name and a class body. The class body is enclosed in curly braces. Here’s what the class House can look like (House.java file): - As yet, it’s not difficult. - Fine. Then let’s move on. The class body can contain variables (otherwise known as class data) and methods (class functions). - Will you please give me an example? - An example? Be sure! - «int a» and «int b» are variables. Are «main» and «pi» methods? - Yeah. - Are there classes with no variables? - Yep. - And with no methods? - Yes. However, the minimal program has to comprise at least of one class. This class has to contain no less than one method / function to start the program. This method must have a name main. The minimal program looks like this: - Here is the class House, the method main, but where are commands? - A minimal program does not have any commands. That’s why it’s called minimal. - I see. - A class that starts the program can have any name, but the method main the program execution starts with is always of the same type: - I got it. At least I rather think so. - Fine, let’s take a short break. What about a coffee? - I’m too young. Little robots don’t drink coffee – water is the reason why we become rusty. - So what do you drink? - Beer, whiskey, century-old rum. - So much the better. - Then, a beer moment?
|The program using three commands:|
2 Meeting Risha (continued)(an hour later) - Fine. So where were we? - Method code or something like that. - Yeah. Exactly. The method body consists of commands. You might as well say that the method is a group of commands, which was given the name (name of the method). Either way is correct. - There are various commands. Do you have any dogs here? - Only tame robowolves. - Do they follow commands? - Yeah. «Bite», «Eat up», «Kill» and «Well done! Heel!» - Ahem. What a commands! And not so many at all. - How many do you want? - In Java, there are commands for all cases. Each command describes a specific action. A semicolon shall be put at the end of each command. Examples of commands: - In fact, this is one and the same command System.out.println. And its parameters are specified in parentheses. The effect of a command can be different, depending on the parameters. - It’s very convenient. - Yeah. If you want to display the text, you must enclose it in double quotes «"». - A single quote looks like this «'», and a double one just like that «"». A double quote should not be confused with two single quotes! - The double quote is the one next to the Enter button? - Yep. Amigo’s pulse quickened from 3 up to 5 GHz, he still couldn’t believe it. He just learned how to display lines, and this was much easier than he thought. Amigo looked out of the window to switch off from his thoughts and to calm down. The leaves turned yellow. It came to his mind that the Rusty Season is coming really soon. The window enables him to see much farther than normal – visitors’ technologies were up to the mark. How can he care for leaves now? After all, by evening he learns a great deal more. However, his thoughts were out of control. Someday he will write a program in order that all robots tarry at home as the Rusty Season sets in. And this program will save thousands of robolives… - There are two variations of this command: System.out.println() and System.out.print() - If you write the command System.out.println() several times, every time the text passed will be displayed in a new line. If System.out.print(), the text will be displayed on the same line. Example: - Here’s a little remark. println command doesn’t display the text in a new line. It displays the text on the current line, but it makes the next message appear on a new line. - println() command displays the text and then adds a special invisible line feed character that results in the next message displayed from the beginning of a new line. - What does a completed program look like? - Now, attention to your screen: - Оh, that’s it! We add spaces at the end of words in order the words don’t “stick together”, right? - That’s right. You’re a smart fellow. This praise made Amigo glow with pride. - Well, here’s your first task.
|Write a program that displays «It's cool to be a programmer!».|
|Example of the text displayed:|
|It's cool to be a programmer!|
3 Meeting EllyA pretty lady with pink hair entered the cabin. «I wonder if all the human females have such hair?» - Amigo thought, but she stared him into confusion. - Hey! My name’s Eleanora Carry. I am the main pilot of the Galactic Rush. - Hi, Eleanora! – Amigo awkwardly forced himself to speak. He didn’t know why, but felt his cheeks flush, as if an oil duct somewhere inside him was damaged. - I’ll tell you about the most interesting thing in the Java language - about variables. - I’m ready to listen! What are these variables? - Variable is a thing intended for storage of data. Any data. All Java data are stored using variables. A variable is like a box. - What box? - A very usual one. Suppose you wrote on a piece of paper number 13 and put it in the box. We can now say that the box stores value 13. - In Java, every variable has its three important properties: type, name and value. - Could you tell me a little bit more? - Sure. The name is used to distinguish one variable from another. It’s like a mark on a box. - A variable type determines a type of value / data it may store. We store the cake in a cake box, shoes in a shoebox, etc. - A value is an object, data or information stored in a variable. - Tell me about the type once again. - Ok. Every object in Java has its type. For example, there may be data types such as «integer», «fractional number», «text», «Cat», «House» etc. - A variable has its own type, too. The variable may store only values of the same type the variable itself belongs to. - It’s common in real life. Various boxes are used to store various things. - To create a variable, use a «type name» command. Examples: - The two types most commonly used are integers (denoted with int) and the text (denoted with String). - What about the double type? - double are fractional (real) numbers. - You said that the variable has the three properties: type, name and value. However, there are only two of them. I have a question: how to place a value into a variable? - Going back to the boxes, imagine that you took a piece of paper, wrote “42” on it and put it in the box. Now the box stores value 42. - I see. - To place a value into a variable there is a special operation called assignment operator. It copies a value of one variable to another variable. Not moves, but copies. Just like a file on a disk. It looks like this: - For the assignment operator an equals sign «=» is used. - Once again, it’s not comparing. It’s exactly copying the value to the right of the equals sign in a variable located to the left. As a comparison, a double equals sign «==» is used. - I know how to put a cat in a variable. It’s almost like a program. - How to catch a cat: 1. Take an empty box. 2. Wait. - No, Amigo, you may put only one cat into a box. Ahem... I mean, you may put only one value in the variable. - I see. Could you give more examples on how to create variables? - OK, I’ll put it another way. To create a variable, you have to write «type name» command as follows: - Oh, now I know. - Bear in mind that you can’t create two variables with identical names in the same method. - What about the different methods? - You may. It’s like boxes standing in different houses. - May a variable have any name? - Kinda, but its name may not contain spaces, symbols +, -, etc. The best thing is to use for a variable name only characters and numbers. - Please note that in the Java language it’s important what characters you write – upper case or lower case. «int a» is not the same as «Int a». - By the way, in Java, it is possible to create a variable and assign it a value at the same time. - This helps save time and space: - That’s much better and easy to understand. - That’s what we live by. - In Java, there are two types a newbie must get himself familiar with. These are types int (integers) and String (text / strings). - int type enables storage of numbers in a variable, as well as various operations such as addition, subtraction, multiplication, division etc. - For me, it’s black and white. Is programming so simple? - Actually, yes. - That’s good. So what have you got on? - The String type enables storage of text strings. - To assign some text string in Java you have to write its text, and then enclose it in double quotes. Example: - I got it. It looks quite easy. - So here’s another interesting fact. - Strings may be combined using a plus sign «+». Example: - So, I can also add strings to numbers? - Yeah, but please know that if you add a string to a number, you always get a string. - Yes, I’ve got it from the example. - Well, if you are so quick on the uptake, then figure out how to display a variable? - Er... display a variable? Uh-uh, my mind goes blank. - It’s actually quite simple. To display something, we use the System.out.println() command and pass to it as a parameter data we want to display. - Gotcha! Now everything has become clearer. - That’s fine. Then here are the three tasks for you.
Write a program that displays 5 times «I intend to live forever. So far, so good.».
Each string should be on a new line.
|2||Write a program that displays the current year.
It’s the 31st century already, for the record.
|3||Write a program that displays «I am so clever that sometimes I don’t understand a single word of what I am saying.»|
4 Meeting Professor- Hey, Amigo. I’m Professor Hans Noodles, the Head of Science Department of the Galactic Rush company. I also supervise the project on teaching you Java. - Good afternoon, Professor Noodles. - I’d like to tell you why Java is a so great programming language. - You’ll definitely hear more than once that platform independence is Java’s undeniable advantage over other languages. What is that and how to deal with it? I’ll try to explain by telling you some background. - The fact is that computers execute primitive numerical commands only. There are dog commands like "Heel", "Shake" and so on; a dog does something on hearing them. - In computers, numbers fulfill the role of such commands: every command is encoded with a number, the code, also known as machine code. - It’s very difficult to write a program in numerical form, that’s why people invented programming languages and compilers. Such a language is understandable both to man and to compiler. A compiler is a special program, which translates the program text written in a programming language into a machine code set. - Usually a programmer writes a program with a programming language, and then starts a compiler, which uses program code files written by the programmer to make a machine code file - a definitive (compiled) program. - The resulting program may be immediately run on a computer. The drawback of this approach is that the program code depends heavily on a processor and an operating system. A program compiled on Windows won’t work on an Android phone. - So a program written and compiled for Android won’t work if I try to run it on Windows? - Yep. - But Java’s approach is much more innovative. - The Java compiler does not compile all classes into one program of machine codes.Instead, it compiles each single class not to a machine code but to a special middle code (bytecode). The compilation to machine code runs when the program starts. - Who’s then to compile a program at its start? - There’s a special program called JVM (Java Virtual Machine). When a program that consists of bytecode is executed, it is the first one that starts. And then before the program starts, JVM compiles it to the machine code. - How exciting! And what’s the object of doing that? - It’s a very smart decision, and one of the reasons of Java’s total domination. - Owing to this approach, Java programs may run on nearly any device - computers, phones, ATMs, toasters, bank cards (!). - WOW! - This approach has many advantages. That’s why all Android programs are written with Java, too. Due to development of the mobile sector, Java has a dominant position in the following areas: 1) Enterprise: heavy server-side applications for banks, corporations, investment funds, etc. 2) Mobile: mobile application development (phones, tablets), thanks to Android. 3) Web: PHP leads the field, but Java has its big chunk of the market, too. 4) Big Data: distributed computing in clusters of thousands of servers. 5) Smart Devices: programs for smart home, electronics or refrigerators with internet access. - Java isn’t just a language, but an entire system, millions of ready-made modules you can use in your program. Thousands of Internet communities and forums you can ask for help or advice. - The more you program with Java, the more you find answers to the question – «Why Java?». That’s it for today. - Thanks, Professor. It was the most interesting and inspiring lecture.
5 Meeting KimWow, another human female. But this time, with black hair. How exciting! - Hi, my name’s Kim Lee-ling. - Hi, I’m Amigo. - I know. It was me who came up with your name. It would never have occurred to Diego. I’d like to begin my lecture with a small presentation - now, attention to your screen! - Oops, a wrong flash drive. Hang on... Amigo’s thoughts raced through his mind at electron velocity. Ahem… Does she have a soft spot for robots? How exciting! And a photo on the table – is it her boyfriend? - Let’s go back to the lecture! Let me explain to you all the stuff with simple words. - Ok. - I’d like to add a few words to what Professor and Risha have said. - In Java, you may not only write the command, but also comment them directly in the code. These comments are ignored by the compiler, as if there were none at all. When the program is executed all the comments are skipped! - Would you please give me an example? - Sure: - In the class code our comment was «Now we display...». The comment starts with characters «/*», and ends with «*/». When a program is compiled, the compiler omits all the characters between /* and */ - So I may write anything there? - Yep. Usually there are various comments on code part, which is questionable or difficult to understand. There are comments of dozens of lines (usually written before methods) that describe details of methods’ work. - Another way to set a comment in the code is to use characters «//». - In so doing the comment is the code part starting with characters // to the end of the line they’re located. So there are no characters to "close" the comment. - By the way, software developers have good sense of humor, and you may find in code some interesting comments:
// I am not responsible of this code. // They made me write it, against my will.
//Dear future me. Please forgive me. //I can't even begin to express how sorry I am.
// I am not sure if we need this, but too scared to delete.
// hack for IE browser (assuming that IE is a browser)
// This isn't the right way to deal with this, but today is my last day, Ron // just spilled coffee on my desk, and I'm hungry, so this will have to do...
// Catching exceptions is for communists
// Dear maintainer: // // Once you are done trying to 'optimize' this routine, // and have realized what a terrible mistake that was, // please increment the following counter as a warning // to the next guy: // // total_hours_wasted_here = 42
// When I wrote this, only God and I understood what I was doing // Now, God only knows
// sometimes I believe compiler ignores all my comments
// I dedicate all this code, all my work, to my wife, Darlene, who will // have to support me and our three children and the dog once it gets // released into the public.
// drunk, fix later
- Yeah, comments are sometimes very funny. - I’m done. - A short but interesting lecture. Thanks, Kim.
// Magic. Do not touch.
6 Meeting Julio- Hey, Amigo. I’m Julio Siesta. - I see you’ve had a stiff job today. - How about a well-earned break? - Shouldn’t I have a lecture? - Yeah. However, the lessons have to be interesting, have you forgotten? Last time I checked there was a law on batting boring teachers! - This is a special video tutorial to… er… maintain your zest for learning and... In short, let’s have a look, put questions away for later. Turn it on!
7 Meeting Diego- Hiya, My name is Diego Carleone. I’m a robot just like you, only made at the factory in Havana, Cuba. - Hi-ya, Diego! I’ve already heard about you a lot. - How do you like the lesson? - This is the awesomest programming lesson I’ve ever had. No, even awesomer. The best lesson in my life. Better than I ever could have imagined. - That’s what we live by. - Is all the rest equally as interesting? - Even better! Boring lessons were left behind in the 21st century. Goodness me - to write with chalk on a blackboard. Nothing has changed since the 15th century. I suppose there were dinosaurs walking freely. - I guess so. What comes next? - You move to the next level! You have only 39 to complete, and you’ll become a great Java developer! Today you’ve learned:
- What are the variables
- How to display messages on the screen
- Got yourself familiar with int and String types
- What is the difference between the compilation in Java and in other languages
- How to make comments, and why do we need them
|1||Want to grab some Java?
Write a program that displays «Want to grab some Java?»
|2||I'll show you my source code if you show me yours
Write a program that displays «I'll show you my source code if you show me yours.»
|3||Nice Bolts wanna screw?
Write a program to display «Nice Bolts wanna screw?».
GO TO FULL VERSION