Smile: a first Java program

Learn the basic structure of a Java program, while writing code to draw a smiley face.

We'll cover the following

Here is a Java program to draw a circle. We’ll dissect it in a minute. First, run it by clicking on the Run button below the code.

Press + to interact
// include educative's simple graphics library:
import com.educative.graphics.*;
class DrawCircle {
public static void main(String[] args) {
// set up a canvas for drawing:
Canvas c;
c = new Canvas(200, 200);
// call some graphics commands:
c.fill("yellow");
c.stroke("black");
c.circle(100, 100, 50);
// nothing is actually drawn on the screen until
// the `draw` method is called:
c.draw();
}
}

First things to note:

  1. Single-line comments begin with //.
  2. All functions in Java are called methods. c.circle() calls the method circle with the parameters 100, 50, 50, specifying x and y coordinates for the center, and the radius.
  3. Some method calls need an object. circle needs a Canvas object to draw with. The first few lines set up a reference to a Canvas object in the variable c. Then the c.circle() method call acts on that canvas object.
  4. The method main is defined using the keywords public static void. The method named main is special: Java starts running the code at the first line of the method named main.
  5. Method definitions are grouped into classes.
  6. Most lines of code end in a semi-colon. Method and class definitions do not.

A first program: smiley

As a warmup, write a program in the next code box that causes a yellow smiley face to be drawn on the screen. You have a 200 by 200 window available.

  1. Draw the outline of the face after the comment // draw the outline of the face. Don’t forget the semi-colons.

  2. Draw the eyes. Put your code for drawing the eyes after the line // draw the eyes.

  3. Bonus challenge: draw the mouth. Hint – draw a circle, and then erase the top part of it by drawing a yellow rectangle that covers the top of the mouth but fits within the face. (Experiment with c.rect, which takes four parameters.)

You can test your code with the Run button, and click on the second tab to compare to a sample solution when you are done.

import com.educative.graphics.*;
class Smiley {
public static void main(String[] args) {
Canvas c;
c = new Canvas(200, 200);
// Draw the outline of the face
c.fill("yellow");
c.stroke("black");
c.circle(100, 100, 50);
// draw the mouth
// draw the eyes
c.draw();
}
}