Welcome!

Related Topics: Java IoT

Java IoT: Article

Teaching Kids Programming: Even Younger Kids Can Learn Java

One day my son Dave (10) showed up in my office with my rated 'R' Java tutorial in his hands

My solution to the problem? I've written my own e-book on it: Java Programming for Kids, Parents and Grandparents. Dave became my first kid student and this has helped me a lot to understand the mentality of the little people.

This is what I've learned while working on this project:

  • Most of the programming tasks require minimal knowledge of arithmetic and algebra skills. To start programming, a kid needs to understand what x = y+2 means. Another important concept to understand is an if statement.

     

  • Kids develop the abstract reasoning abilities by the fourth-fifth grade, and they also easily perform such tasks as browsing the Web, downloading and installing software. Dave have learned how to type, compile and run Java programs in Eclipse IDE in no time.

     

  • Kids learn much faster than adults, but they do not have "previous programming experience", which may actually be a good thing, because they do not have to switch from a procedural to object-oriented way of thinking. After learning about inheritance, Dave called my wife a superclass.

     

  • Adults are responsible creatures, and they can keep doing boring operations much longer that kids. Programming lessons with kids have to be short. One or two 45-minute lessons per week is enough. High school kids should be able to study more, but I do not have such experience yet.

     

  • Some people suggest using Logo as a first programming language for kids, mainly because it has a tool that lets you program with pre-drawn shapes like dogs and turtles. There is an opinion that REALbasic is also good for young programmers. Yes, this language has such concepts as objects, inheritance, casting and overloading, but who uses this language in the real world? Some recommend using Python. The syntax of these languages is not that much easier than Java. There are also plenty of people who write nostalgically about their first Atari computer...

     

  • Illustrations help. In my book I've included lots of color cartoon-like characters that are like a Java-fabric softener .

     

  • Kids like to see immediate results and enjoy playing with shorter programs, for example a class Fish has a method dive(int howDeep). Let me try to call this method several times with different arguments...

     

  • Graphical programming is the most fun, and even a fairly large program like Calculator, Tic-Tac-Toe or Ping Pong can be explained to children.

     

  • There is a middle school in Berkley, CA where six graders start learning Java. This school is equipped with Sun Server and multiple workstations. There is a long waiting list of kids that want to get accepted into this school.

Now I'd like to offer you a fragment from my e-book Java Programming for Kids, Parents and Grandparents. I hope you'll agree with me that even younger kids can learn Java.

Java programs consist of classes that represent objects from the real world. Even though people may have different preferences as to how to write programs, most of them agree that it's better to do it in a so-called object-oriented style. This means that good programmers start with deciding which objects have to be included in the program and which Java classes will represent them. Only after this part is done, they start writing Java code.

Classes and Objects

 

Classes in Java may have methods and attributes.

Methods define actions that a class can perform.

Attributes describe the class.

Let's create and discuss a class named VideoGame. This class may have several methods, which can tell what objects of this class can do: start the game, stop it, save the score, and so on. This class also may have some attributes or properties: price, screen color, number of remote controls and others.

In Java language this class may look like this:

 

class VideoGame {
String color;
int price;

void start () {
}
void stop () {
}
void saveScore(String playerName, int score) {
}
}

Our class VideoGame should be similar to other classes that represent video games - all of them have screens of different size and color, all of them perform similar actions, and all of them cost money.

We can be more specific and create another Java class called GameBoyAdvance. It also belongs to the family of video games, but has some properties that are specific to the model GameBoy Advance, for example a cartridge type.

 

class GameBoyAdvance {
String cartridgeType;
int screenWidth;

void startGame() {
}
void stopGame() {
}
}

In this example the class GameBoyAdvance defines two attributes - cartridgeType and screenWidth and two methods - startGame() and stopGame(). But these methods can't perform any actions just yet, because they have no Java code between the curly braces.

 

In addition to the word class, you'll have to get used to the new meaning of the word object.

The phrase "to create an instance of an object" means to create a copy of this object in the computer's memory according to the definition of its class.

A factory description of the GameBoy Advance relates to an actual game the same way as a Java class relates to its instance in memory. The process of building actual games based on this description in the game factory is similar to the process of creating instances of GameBoy objects in Java.

In many cases, a program can use a Java class only after its instance has been created. Vendors also create thousands of game copies based on the same description. Even though these copies represent the same class, they may have different values in their attributes - some of them are blue, while others are silver, and so on. In other words, a program may create multiple instances of the GameBoyAdvance objects.

Creation of a Pet
Let's design and create a class Pet. First we need to decide what actions our pet will be able to do. How about eat, sleep, and say? We'll program these actions in the methods of the class Pet. We'll also give our pet the following attributes: age, height, weight, and color.

Start with creating a new Java class called Pet in My First Project. Now we are ready to declare attributes and methods in the class Pet. Java classes and methods enclose their bodies in curly braces. Every open curly brace must have a matching closing brace:

 

class Pet{
}

To declare variables for class attributes we should pick data types for them. I suggest an int type for the age, float for weight and height, and String for a pet's color.

 

class Pet{
int age;
float weight;
float height;
String color;
}

The next step is to add some methods to this class. Before declaring a method you should decide if it should take any arguments and return a value:

 

  • The method sleep() will just print a message Good night, see you tomorrow - it does not need any arguments and will not return any value.
  • The same is true for the method eat().It will print the message I'm so hungry…let me have a snack, like nachos!.
  • The method say() will also print a message, but the pet will "say" the word or a phrase that we give to it. We'll pass this word to the method say() as a method argument. The method will build a phrase using this argument and will return it back to the calling program.

The new version of the class Pet will look like this:

 

public class Pet {
int age;
float weight;
float height;
String color;

public void sleep(){
System.out.println("Good night, see you tomorrow");
}

public void eat(){
System.out.println(
"I'm so hungry…let me have a snack, like nachos!");
}

public String say(String aWord){
String petResponse = "OK!! OK!! " +aWord;
return petResponse;
}
}

This class represents a friendly creature from the real world:

Let's talk now about the signature of the method sleep():

public void sleep()

It tells us that this method can be called from any other Java class (public), it does not return any data (void). The empty parentheses mean that this method does not have any arguments, because it does not need any data from the outside world - it always prints the same text.

The signature of the method say() looks like this:

public String say(String aWord)

This method can also be called from any other Java class, but has to return some text, and this is the meaning of the keyword String in front of the method name. Besides, it expects some text data from outside, hence the argument String aWord.

How do you decide if a method should or should not return a value? If a method performs some data manipulations and has to give the result of these manipulations back to a calling class, it has to return a value. You may say, that the class Pet does not have any calling class! That's correct, so let's create one called PetMaster. This class will have a method main()containing the code to communicate with the class Pet. Just create yet another class PetMaster, and this time select the option in Eclipse that creates the method main(). Remember, without this method you can not run this class as a program. Modify the code generated by Eclipse to look like this:

 

public class PetMaster {

public static void main(String[] args) {

String petReaction;

Pet myPet = new Pet();

myPet.eat();
petReaction = myPet.say("Tweet!! Tweet!!");
System.out.println(petReaction);

myPet.sleep();

}
}

Do not forget to press Ctrl-S to save and compile this class! To run the class PetMaster click on the Eclipse menus Run, Run..., New and type the name of the main class: PetMaster. Push the button Run and the program will print the following text:

 

I'm so hungry…let me have a snack like nachos!
OK!! OK!! Tweet!! Tweet!!
Good night, see you tomorrow

The PetMaster is the calling class, and it starts with creating an instance of the object Pet. It declares a variable myPet and uses the Java operator new:

Pet myPet = new Pet();

This line declares a variable of the type Pet (that's right, you can treat any classes created by you as new Java data types). Now the variable myPet knows where the Pet instance was created in the computer's memory, and you can use this variable to call any methods from the class Pet, for example:

myPet.eat();

If a method returns a value, you should call this method in a different way. Declare a variable that has the same type as the return value of the method, and assign it to this variable. Now you can call this method:

String petReaction;

petReaction = myPet.say("Tweet!! Tweet!!");

At this point the returned value is stored in the variable petReaction and if you want to see what's in there, be my guest:

System.out.println(petReaction);

Inheritance - a Fish is Also a Pet
Our class Pet will help us learn yet another important feature of Java called inheritance. In the real life, every person inherits some features from his or her parents. Similarly, in the Java world you can also create a new class, based on the existing one.

The class Pet has behavior and attributes that are shared by many pets - they eat, sleep, some of them make sounds, their skins have different colors, and so on. On the other hand, pets are different - dogs bark, fish swim and do not make sounds, parakeets talk better than dogs. But all of them eat, sleep, have weight and height. That's why it's easier to create a class Fish that will inherit some common behaviors and attributes from the class Pet, rather than creating the classes Dog, Parrot or Fish from scratch every time.

A special keyword extends that will do the trick:

 

class Fish extends Pet{
}

You can say that our Fish is a subclass of the class Pet, and the class Pet is a superclass of the class Fish. In other words, you use the class Pet as a template for creating a class Fish.

Even if you will leave the class Fish as it is now, you can still use every method and attribute inherited from the class Pet. Take a look:

Fish myLittleFish = new Fish();
myLittleFish.sleep();

Even though we have not declared any methods in the class Fish yet, we are allowed to call the method sleep() from its superclass!

Not all pets can dive, but fish certainly can. Let's add a new method dive() to the class Fish now.

public class Fish extends Pet {

int currentDepth=0;

public int dive(int howDeep){
currentDepth=currentDepth + howDeep;
System.out.println("Diving for " + howDeep +" feet");

System.out.println("I'm at " + currentDepth +
" feet below sea level");
return currentDepth;
}
}

The method dive() has an argument howDeep that tells the fish how deep it should go. We've also declared a class variable currentDepth that will store and update the current depth every time you call the method dive(). This method returns the current value of the variable currenDepth to the calling class.

Please create another class FishMaster that will look like this:

 

public class FishMaster {

public static void main(String[] args) {

Fish myFish = new Fish();

myFish.dive(2);
myFish.dive(3);

myFish.sleep();
}
}

The method main() instantiates the object Fish and calls its method dive() twice with different arguments. After that, it calls the method sleep(). When you run the program FishMaster, it will print the following messages:

Diving for 2 feet
I'm at 2 feet below sea level
Diving for 3 feet
I'm at 5 feet below sea level
Good night, see you tomorrow

Have you noticed that beside methods defined in the class Fish, the FishMaster also calls methods from its superclass Pet? That's the whole point of inheritance - you do not have to copy and paste code from the class Pet - just use the word extends, and the class Fish can use Pet's methods!

One more thing, even though the method dive() returns the value of currentDepth, our FishMaster does not use it. That's fine, our FishMaster does not need this value, but there may be some other classes that will also use Fish, and they may find it useful. For example, think of a class FishTrafficDispatcher that has to know positions of other fish under the sea before allowing diving to avoid traffic accidents :)

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Comments (41)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Latest Stories
When you're operating multiple services in production, building out forensics tools such as monitoring and observability becomes essential. Unfortunately, it is a real challenge balancing priorities between building new features and tools to help pinpoint root causes. Linkerd provides many of the tools you need to tame the chaos of operating microservices in a cloud native world. Because Linkerd is a transparent proxy that runs alongside your application, there are no code changes required. I...
In his general session at 21st Cloud Expo, Greg Dumas, Calligo’s Vice President and G.M. of US operations, discussed the new Global Data Protection Regulation and how Calligo can help business stay compliant in digitally globalized world. Greg Dumas is Calligo's Vice President and G.M. of US operations. Calligo is an established service provider that provides an innovative platform for trusted cloud solutions. Calligo’s customers are typically most concerned about GDPR compliance, application p...
Modern software design has fundamentally changed how we manage applications, causing many to turn to containers as the new virtual machine for resource management. As container adoption grows beyond stateless applications to stateful workloads, the need for persistent storage is foundational - something customers routinely cite as a top pain point. In his session at @DevOpsSummit at 21st Cloud Expo, Bill Borsari, Head of Systems Engineering at Datera, explored how organizations can reap the bene...
"NetApp's vision is how we help organizations manage data - delivering the right data in the right place, in the right time, to the people who need it, and doing it agnostic to what the platform is," explained Josh Atwell, Developer Advocate for NetApp, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
Kubernetes as a Container Platform is becoming a de facto for every enterprise. In my interactions with enterprises adopting container platform, I come across common questions: - How does application security work on this platform? What all do I need to secure? - How do I implement security in pipelines? - What about vulnerabilities discovered at a later point in time? - What are newer technologies like Istio Service Mesh bring to table?In this session, I will be addressing these commonly asked ...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
Blockchain has shifted from hype to reality across many industries including Financial Services, Supply Chain, Retail, Healthcare and Government. While traditional tech and crypto organizations are generally male dominated, women have embraced blockchain technology from its inception. This is no more evident than at companies where women occupy many of the blockchain roles and leadership positions. Join this panel to hear three women in blockchain share their experience and their POV on the futu...
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
Cloud-Native thinking and Serverless Computing are now the norm in financial services, manufacturing, telco, healthcare, transportation, energy, media, entertainment, retail and other consumer industries, as well as the public sector. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that pro...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Docker and Kubernetes are key elements of modern cloud native deployment automations. After building your microservices, common practice is to create docker images and create YAML files to automate the deployment with Docker and Kubernetes. Writing these YAMLs, Dockerfile descriptors are really painful and error prone.Ballerina is a new cloud-native programing language which understands the architecture around it - the compiler is environment aware of microservices directly deployable into infra...