You are on page 1of 36

WEEK 2

CS 201: Introduction to Object Oriented


Programming.

1
Counter Class with Main – Java
public class Counter{
private int count;

public Counter () { count = 0; }


public void increment () { count ++; }
public int getCount () { return count; }
public void printCounter(){System.out.println(“count=”+count); }

public static void main (String args [] ) {


Counter c1=new Counter();
c1.printCounter();
c1.increment();
c1.printCounter();
}
}
Algorithm
•An algorithm describes how a problem is solved by
listing the actions that need to be taken and the order of
their execution. Algorithms can help the programmer
plan a program before writing it in a programming
language. Algorithms can be described in natural
languages or in pseudocode (natural language mixed
with some programming code). The algorithm for
calculating the area of a circle can be described as
follows:
•1. Read in the circle’s radius.
•2. Compute the area using the formula: PI*rad*rad
•3. Display the result.
3
Another Example

Computing the Area of a Circle


write the program to compute the
area of the circle

4
Trace a Program Execution
public class ComputeArea { allocate memory
/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius radius is a variable


radius = 20;
that corresponds to
// Compute area memory locations.
area = radius * radius * 3.14159;
Every variable has a
// Display results name, a type, a size,
System.out.println("The area for the circle of radius " + and a value.
radius + " is " + area);
}
}

5
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius no value
double radius;
double area; area no value

// Assign a radius
radius = 20; allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

6
animation
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area no value

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

7
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius;
radius 20
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign
// Compute area it to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

8
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636

// Assign a radius
radius = 20;

// Compute area
print a message to the
area = radius * radius * 3.14159; console

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

9
Identifiers
• Identifiers are the names that identify the elements such
as classes, methods, and variables in a program.
• An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word. ( “Java Keywords”).
• An identifier cannot be true, false, or
null.
• An identifier can be of any length.

10
Variable
• Variables are used to represent values that may be changed in the program.
• Variables are for representing data of a certain type.
• To use a variable, you declare it by telling the compiler its name as well as what
type of data it can store.
• The variable declaration tells the compiler to allocate appropriate memory space
for the variable based on its data type. The syntax for declaring a variable is
• datatype variableName;

11
Variables

// Compute the first area


radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
12
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

13
Assignment Statements

x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;

14
Declaring and Initializing
in One Step

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

15
Constants
• The value of a variable may change during the execution of a
program, but a named constant,
• or simply constant, represents permanent data that never
changes.
• A constant must be declared and initialized in the same
statement. The word final is a Java keyword for declaring a
constant.
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
• Advangtages:
• Don’t have to repeat, Change only at one point, Intuitive name.

16
Numerical Data Types

Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308

17
Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

18
Integer Division

+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

19
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,

String message = "Welcome to Java";

String is actually a predefined class in the Java library just like the
System class. The String type is not a primitive type. It is known as
a reference type. Any Java class can be used as a reference type
for a variable. Reference data types will be thoroughly discussed
later on, “Objects and Classes.” For the time being, you just need
to know how to declare a String variable, how to assign a string to
the variable, and how to concatenate strings.

20
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

21
Problem: Displaying Time
Write a program that obtains hours and
minutes from seconds.

22
Obtaining Input
Many ways but will discuss two ways of obtaining input
now.

1. Using the Scanner class (console input)


2. Using JOptionPane input dialogs

23
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the methods next(), nextByte(), nextShort(),


nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int,
long, float, double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Exercise: write a program that take radius as
input from console and calculate the area.
24
NOTE

Calculations involving floating-point numbers are


approximated because these numbers are not stored
with complete accuracy. For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1. Integers are
stored precisely. Therefore, calculations with integers
yield a precise integer result.

25
Number Literals

A literal is a constant value that appears directly


in the program. For example, 34, 1,000,000, and
5.0 are literals in the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;

26
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to Celsius using the
formula:

celsius = ( 95 )( fahrenheit - 32)

27
Shortcut Assignment Operators

Operator Example Equivalent


+= i += 8 i = i + 8
-= i -= 8.0 i = i - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8

28
Increment and
Decrement Operators, cont.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

29
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names:
• Use lowercase. If the name consists of several words, concatenate all in
one, use lowercase for the first word, and capitalize the first letter of each
subsequent word in the name. For example, the variables radius and
area, and the method computeArea.

30
Naming Conventions, cont.
• Class names:
• Capitalize the first letter of each word in the
name. For example, the class name
ComputeArea.

• Constants:
• Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI and
MAX_VALUE

31
Proper Indentation and Spacing
• Indentation
• Indent two spaces.

• Spacing
• Use blank line to separate segments of the code.

32
Block Styles
Use end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}

33
Programming Errors
• Syntax Errors
• Detected by the compiler
• Runtime Errors
• Causes the program to abort
• Logic Errors
• Produces incorrect result

34
Syntax Errors
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i + 4);
}
}

35
Runtime Errors

public class ShowRuntimeErrors {


public static void main(String[] args) {
int i = 1 / 0;
}
}

36

You might also like