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.
// 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:
- Single-line comments begin with
//
. - All functions in Java are called methods.
c.circle()
calls the methodcircle
with the parameters100
,50
,50
, specifying x and y coordinates for the center, and the radius. - 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 variablec
. Then thec.circle()
method call acts on that canvas object. - The method
main
is defined using the keywordspublic static void
. The method namedmain
is special: Java starts running the code at the first line of the method namedmain
. - Method definitions are grouped into classes.
- 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.
-
Draw the outline of the face after the comment
// draw the outline of the face
. Don’t forget the semi-colons. -
Draw the eyes. Put your code for drawing the eyes after the line
// draw the eyes
. -
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 facec.fill("yellow");c.stroke("black");c.circle(100, 100, 50);// draw the mouth// draw the eyesc.draw();}}