Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Programming Fundamentals: A Comparative Analysis of 'Hello World' Programs in C and Java -, Study notes of Computer Science

An introduction to programming by presenting the 'hello world' program in both c and java. It explains the syntax and structure of each language and highlights the similarities and differences between them. This resource is ideal for university students studying computer science or programming, particularly during their first programming course.

Typology: Study notes

Pre 2010

Uploaded on 08/16/2009

koofers-user-jy0-1
koofers-user-jy0-1 🇺🇸

10 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 2Programming by Example
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Programming by Example
C H A P T E R 2
Example is always more efficacious than precept.
—Samuel Johnson, Rasselas, 1759
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
The “Hello World” Program
One of the important influences on the
design of Java was the C programming
language, which was developed at Bell
Labs in the early 1970s. The primary
reference manual for C was written by
Brian Kernighan and Dennis Ritchie.
On the first page of their book, the
authors suggest that the first step in
learning any language is to write a
simple program that prints the message
“hello, world” on the display. That
advice remains sound today.
1.1 Getting Started
The only way to learn a new programming
language is to write programs in it. The first
program to write is the same for all languages:
Print the words
hello, world
This is the big hurdle; to leap over it you have to
be able to create the program text somewhere,
compile it, load it, run it, and find out where your
output went. With these mechanical details
mastered, everything else is comparatively easy.
In C, the program to print “hello, world” is
#include <stdio.h>
main() {
printf("hello, world");
}
The “Hello World” Program in Java
/*
* File: HelloProgram.java
* -----------------------
* This program displays "hello, world" on the screen.
* It is inspired by the first program in Brian
* Kernighan and Dennis Ritchie's classic book,
* The C Programming Language.
*/
import acm.graphics.*;
import acm.program.*;
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel( "hello, world", 100, 75 ) );
}
}
/*
* File: HelloProgram.java
* -----------------------
* This program displays "hello, world" on the screen.
* It is inspired by the first program in Brian
* Kernighan and Dennis Ritchie's classic book,
* The C Programming Language.
*/
The simple “Hello World” example illustrates several features
that are common to the programs you will see in this book.
This first few lines (everything between /* and */) are an
example of a comment, which is intended for human readers.
import acm.graphics.*;
import acm.program.*;
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel( "hello, world", 100, 75 ) );
}
}
The next two lines are the imports, which indicate what library
packages the program uses.
The last few lines in the file define the HelloProgram class,
which the extends keyword identifies as a GraphicsProgram.
A class definition in Java typically contains a series of entries.
This example has one entry, which is a method called run.
A Java method consists of a series of statements. Here, the only
statement is a call to add, which adds an object to the display.
The object to be added is indicated by supplying an argument to
the add method. Here, the argument is a new GLabel object.
In Java, objects are created by using a constructor, which consists
of the keyword new followed by the class name and arguments.
The arguments supply information that the constructor needs to
make the object, such as the string to display and the coordinates.
The next slide simulates the operation of HelloProgram so that
you can get a sense of what appears on the display.
/*
* File: HelloProgram.java
* -----------------------
* This program displays "hello, world" on the screen.
* It is inspired by the first program in Brian
* Kernighan and Dennis Ritchie's classic book,
* The C Programming Language.
*/
import acm.graphics.*;
import acm.program.*;
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel( "hello, world", 100, 75 ) );
}
}
The “Hello World” Program in Java
import acm.graphics.*;
import acm.program.*;
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel("hello, world", 100, 75) );
}
}
HelloProgram
hello, world
import acm.graphics.*;
import acm.program.*;
public class HelloProgram extends GraphicsProgram {
public void run() {
add( new GLabel("hello, world", 100, 75) );
}
}
Perspectives on the Programming Process
In his Pulitzer-prizewinning book, computer
scientist Douglas Hofstadter identifies two
concepts—holism and reductionism—that turn
out to be important as you begin to learn about
programming.
Hofstadter explains these concepts in the form of
a dialogue in the style of Lewis Carroll:
I will be glad to indulge both of you, if you will first oblige me, by telling me the
meaning of these strange expressions, “holism” and “reductionism”.
Achilles:
Crab: Holism is the most natural thing in the world to grasp. It’s simply the belief that
“the whole is greater than the sum of its parts”. No one in his right mind could
reject holism.
Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply the belief
that “a whole can be understood completely if you understand its parts, and the
nature of their ‘sum’”. No one in her left brain could reject reductionism.
A Program to Add Two Numbers
import acm.program.*;
public class Add2Integers extends ConsoleProgram {
public void run() {
println("This program adds two numbers.");
int n1 = readInt("Enter n1: ");
int n2 = readInt("Enter n2: ");
int total = n1 + n2;
println("The total is " + total + ".");
}
}
The holistic perspective is particularly useful when you are first
learning to program. When you look at a program, you should
concentrate on understanding its operation in a general way
rather than focusing on the details. Consider, for example, the
following program, which adds two integers and prints their sum:
This program is an example of a ConsoleProgram, which reads
input from the keyboard and displays characters on the screen.
Such programs are not as exciting as graphical applications but
are useful for illustrating programming concepts.
As you saw in the case of the HelloProgram example, Java
programs written using the acm.program package begin by
executing the statements in the run method.
The first statement in the program prints a message to the user
describing what the program does.
The next two statements read the input values from the user, each
of which is a whole number, which is more formally called an
integer. The input values are stored in memory cells called
variables that serve as placeholders for those values.
The next statement computes the sum by adding the values stored
in the variables n1 and n2. In this statement, the + operator
represents addition, as in standard mathematics.
The final statement in the run method displays the result. In this
statement, the + operator signifies concatenation, which consists
of combining the operands together as strings.
The next slide animates the operation of this program to illustrate
the assignment of values to variables.
import acm.program.*;
public class Add2Integers extends ConsoleProgram {
public void run() {
println("This program adds two numbers.");
int n1 = readInt("Enter n1: ");
int n2 = readInt("Enter n2: ");
int total = n1 + n2;
println("The total is " + total + ".");
}
}
pf3
pf4

Partial preview of the text

Download Programming Fundamentals: A Comparative Analysis of 'Hello World' Programs in C and Java - and more Study notes Computer Science in PDF only on Docsity!

Chapter 2—Programming by Example The Art and Science of An Introduction

ERIC S. ROBERTS^ Java^ to Computer Science

Programming by Example

C H A P T E R 2 Example is always more efficacious than precept. —Samuel Johnson, Rasselas, 1759

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

The “Hello World” Program

One of the important influences on the

design of Java was the C programming

language, which was developed at Bell

Labs in the early 1970s. The primary

reference manual for C was written by

Brian Kernighan and Dennis Ritchie.

On the first page of their book, the

authors suggest that the first step in

learning any language is to write a

simple program that prints the message

“hello, world” on the display. That

advice remains sound today.

1.1 Getting Started language is to write programs in it.^ The only way to learn a new programming The first program to write is the same for all languages: Print the words hello, world This is the big hurdle; to leap over it you have to be able to create the program text somewhere, compile it, load it, run it, and find out where your output went. With these mechanical details mastered, everything else is comparatively easy. In C, the program to print “hello, world” is #include <stdio.h> main() { printf("hello, world"); }

The “Hello World” Program in Java

  • File: HelloProgram.java

  • This program displays "hello, world" on the screen.
  • It is inspired by the first program in Brian
  • Kernighan and Dennis Ritchie's classic book,
  • The C Programming Language. / import acm.graphics.; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); } }
  • File: HelloProgram.java

  • This program displays "hello, world" on the screen.
  • It is inspired by the first program in Brian
  • Kernighan and Dennis Ritchie's classic book,
  • The C Programming Language. */

The simple “Hello World” example illustrates several features

that are common to the programs you will see in this book.

This first few lines (everything between /* and */) are an

example of a comment , which is intended for human readers.

import acm.graphics.; import acm.program.; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); } }

The next two lines are the imports , which indicate what library

packages the program uses.

The last few lines in the file define the HelloProgram class,

which the extends keyword identifies as a GraphicsProgram.

A class definition in Java typically contains a series of entries.

This example has one entry, which is a method called run.

A Java method consists of a series of statements. Here, the only

statement is a call to add, which adds an object to the display.

The object to be added is indicated by supplying an argument to

the add method. Here, the argument is a new GLabel object.

In Java, objects are created by using a constructor, which consists

of the keyword new followed by the class name and arguments.

The arguments supply information that the constructor needs to

make the object, such as the string to display and the coordinates.

The next slide simulates the operation of HelloProgram so that

you can get a sense of what appears on the display.

  • File: HelloProgram.java

  • This program displays "hello, world" on the screen.
  • It is inspired by the first program in Brian
  • Kernighan and Dennis Ritchie's classic book,
  • The C Programming Language. / import acm.graphics.; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); } }

The “Hello World” Program in Java

import acm.graphics.; import acm.program.; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel("hello, world", 100, 75) ); } } HelloProgram hello, world import acm.graphics.; import acm.program.; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel("hello, world", 100, 75) ); } }

Perspectives on the Programming Process

In his Pulitzer-prizewinning book, computer

scientist Douglas Hofstadter identifies two

concepts— holism and reductionism —that turn

out to be important as you begin to learn about

programming.

Hofstadter explains these concepts in the form of

a dialogue in the style of Lewis Carroll:

I will be glad to indulge both of you, if you will first oblige me, by telling me the meaning of these strange expressions, “holism” and “reductionism”. Achilles: Crab: Holism is the most natural thing in the world to grasp. It’s simply the belief that “the whole is greater than the sum of its parts”. No one in his right mind could reject holism. Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply the belief that “a whole can be understood completely if you understand its parts, and the nature of their ‘sum’”. No one in her left brain could reject reductionism.

A Program to Add Two Numbers

import acm.program.*; public class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } }

The holistic perspective is particularly useful when you are first

learning to program. When you look at a program, you should

concentrate on understanding its operation in a general way

rather than focusing on the details. Consider, for example, the

following program, which adds two integers and prints their sum:

This program is an example of a ConsoleProgram, which reads

input from the keyboard and displays characters on the screen.

Such programs are not as exciting as graphical applications but

are useful for illustrating programming concepts.

As you saw in the case of the HelloProgram example, Java

programs written using the acm.program package begin by

executing the statements in the run method.

The first statement in the program prints a message to the user

describing what the program does.

The next two statements read the input values from the user, each

of which is a whole number, which is more formally called an

integer. The input values are stored in memory cells called

variables that serve as placeholders for those values.

The next statement computes the sum by adding the values stored

in the variables n1 and n2. In this statement, the + operator

represents addition, as in standard mathematics.

The final statement in the run method displays the result. In this

statement, the + operator signifies concatenation , which consists

of combining the operands together as strings.

The next slide animates the operation of this program to illustrate

the assignment of values to variables.

import acm.program.*; public class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } }

The Add2Integers Program

Add2Integers class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } } n1 n2 total This program adds two numbers. Enter n2: The total is 42.

25 class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } } n1 n2 total 17 25 42 Enter n1: 17

Programming Idioms and Patterns

  • Experienced programmers also often take a holistic approach

to programming. Effective programmers can recognize a

variety of common operations and have learned a standard

solution strategy for each one. The code that implements

such a solution strategy is called a programming idiom or

programming pattern. Learning to use these patterns saves

you from having to think about the nitty-gritty details.

  • As an example, it is important to think of a statement like

int n1 = readInt("Enter n1: ");

not in terms of what each part of the statement means, but

rather as a holistic pattern to read an integer from the user:

int variable = readInt(" prompt ");

Classes and Objects

  • As described in the slides for Chapter 1, Java programs are

written as collections of classes, which serve as templates for

individual objects. Each object is an instance of a particular

class, which can serve as a pattern for many different objects.

  • Classes in Java form hierarchies. Except for the class named

Object that stands at the top of the hierarchy, every class in

Java is a subclass of some other class, which is called its

superclass. A class can have many subclasses, but each class

has only one superclass.

  • A class represents a specialization of its superclass. If you

create an object that is an instance of a class, that object is

also an instance of all other classes in the hierarchy above it

in the superclass chain.

  • When you define a new class in Java, that class automatically

inherits the behavior of its superclass.

Biological Models of Class Structure

The structure of Java’s class hierarchy resembles the biological classification scheme introduced by Scandinavian botanist Carl Linnaeus in the 18th century. Linnaeus’s contribution was to recognize that organisms fit into a hierarchical classification scheme in which the placement of individual species reflects anatomical similarities. Carl Linnaeus (1707–1778)

Biological Class Hierarchy

Living Things Plants Animals Fungi Annelida Brachiopoda Arthropoda Mollusca Chordata Crustacea Insecta Arachnida Hymenoptera Formicidae Iridomyrmex purpureus Kingdom Phylum Order Class Family Genus Species Classification of the red ant Iridomyrmex purpureus Every red ant is also an animal, an arthropod, and an insect, as well as the other superclasses in the chain. Note that there can be many individual red ants, each of which is an instance of the same basic class.

The Program Hierarchy

Applet JApplet Program ConsoleProgram DialogProgram GraphicsProgram Java class hierarchies are similar to the biological class hierarchy from the previous slide. This diagram, for example, shows the hierarchy formed by the classes in the acm.program package. Every ConsoleProgram is also a Program, a JApplet, and an Applet. That means that every ConsoleProgram can run as an applet on the web.

Operations on the GObject Class

object .setColor( color ) Sets the color of the object to the specified color constant. object .setLocation( x , y ) Changes the location of the object to the point ( x , y ). object .move( dx , dy ) Moves the object on the screen by adding dx and dy to its current coordinates.

The following method calls can be made on all GObjects:

The standard color names are defined in the java.awt package:

Color.BLACK

Color.DARK_GRAY

Color.GRAY

Color.LIGHT_GRAY

Color.WHITE

Color.RED

Color.YELLOW

Color.GREEN

Color.CYAN

Color.BLUE

Color.MAGENTA

Color.ORANGE

Color.PINK

Operations on the GLabel Class

Call to Glabel constructor

new GLabel( text , x , y ) Creates a label containing the specified text that begins at the point ( x , y ).

Call to method setFont of the GLabel class

label .setFont( font ) Sets the font used to display the label as specified by the font string.

The font is typically specified as a string in the form

" family - style - size "

where

family is the name of a font family (Times,Monospaced)

style is either PLAIN, BOLD, ITALIC, or BOLDITALIC

size is an integer indicating the point size

Drawing Geometrical Objects

Calls to constructors of Grect, Goval, and GLine

new GRect( x , y , width , height ) Creates a rectangle whose upper left corner is at ( x , y ) of the specified size. new GOval( x , y , width , height ) Creates an oval that fits inside the rectangle with the same dimensions.

Call to methods defined in the GRect and GOval classes

object .setFilled( fill ) If fill is true, fills in the interior of the object; if false, shows only the outline. object .setFillColor( color ) Sets the color used to fill the interior, which can be different from the border. new GLine( x 0 , y 0 , x 1 , y 1 ) Creates a line extending from ( x 0 , y 0 ) to ( x 1 , y 1 ).

The GRectPlusGOval Program

public class GRectPlusGOval extends GraphicsProgram { public void run() { GRect rect = new GRect(100, 50, 125, 60); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(100, 50, 125, 60); oval.setFilled(true); oval.setFillColor(Color.GREEN); add(oval); } } GRectPlusGOval rect oval public class GRectPlusGOval extends GraphicsProgram { public void run() { GRect rect = new GRect(100, 50, 125, 60); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(100, 50, 125, 60); oval.setFilled(true); oval.setFillColor(Color.GREEN); add(oval); } } rect oval skip simulation

The End