Docsity

Programming Fundamentals: Identifiers, Variables, Constants, and Data Types, Slides of Computer Science

Partial preview of the text

Download Programming Fundamentals: Identifiers, Variables, Constants, and Data Types and more Slides Computer Science in PDF only on Docsity!

Contents:

  • Introducing Programming with an Example
  • Identifiers
  • Variables
  • Constants
  • Primitive Data Types
  • Operators
  • Expressions
  • Programming Errors
  • Style and Documentation
  • The MyInput class

Introducing Programming with

an Example

Example 2.1: Computing the Area of

a Circle

This program reads the radius from

the keyboard and computes the

area of the circle.

ComputeArea Run

Variables

//Compute the first area

radius = 1.0;

area = radiusradius3.14159;

System.out.println("The area is "+area+" for radius "+radius);

//Compute the second area

radius = 2.0;

area = radiusradius3.14;

System.out.println("The area is "+area+" for radius "+radius);

Declaring Variables

int x; // declares x to be an

// integer variable;

double radius; // declares radius to

// be a double variable;

char a; // declares a to be a

// character variable;

Declaring and Initializing

in One Step

  • int x = 1;
  • double d = 1.4;
  • float f = 1.4;

Constants

Format:

static final datatype CONSTANT = VALUE;

Example:

static final double PI = 3.14159; static final int SIZE = 3;

Number Literals

  • int i = 34;
  • long l = 1000000;
  • float f = 100.2f;

or

float f = 100.2F;

  • double d = 100.2d

or

double d = 100.2D;

Shortcut Operators

Operator Example Equivalent

+= i+=8 i = i+

-= f-=8.0 f = f-8.

= i=8 i = i*

/= i/=8 i = i/

%= i%=8 i = i%

Numeric Type Conversion

Consider the following statements:

byte i = 100;

long l = i*3+4;

double f = i*3.1+l/2;

Primitive Data Type

  • double
  • float
  • long
  • Int
  • char
  • short
  • byte
  • boolean

Character Data Type

  • char letter = 'A';
  • char letter = '\u000A';
  • char numChar = '4';

Unicode Format

Character Escape Sequence ASCII Unicode

Backspace \b \u

Tab \t \u

Linefeed \n \u000a

Carriage return \r \u000d

Operator Precedence

  • Casting
  • ++, --
  • *, /, %
  • +, -
  • <, <=, >, =>
  • ==, !=;
  • &&
  • ||
  • =, +=, -=, *=, /=, %=

Programming Errors

  • Syntax Errors
    • Syntax Error
  • Runtime Errors
    • devided by zero, exceptions
  • Logical Errors
    • incorrect results, infinite loop