Object Oriented Programming
(CoSc 2082)
Chapter II:
Basics in Java Programming
2 Contents
Variable types and identifiers
Constants
Number types, strings
Operators and operator precedence
Type Conversion/ Casting
3 Variable types and identifiers
Identifier: is a name given to variables, class, function, constants and others that
identifies the items from others in the computer program.
All identifiers must obey the following rules
An identifier is a sequence of characters that consists 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.
An identifier cannot be true, false, or null.
An identifier can be of any length
Variable types and identifiers
4
cont…….
Variables : are used to store values to be used later in a program. They are called
variables because their values can be changed.
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;
Here are some examples of variable declarations:
int count; // Declare count to be an integer variable;
double radius; // Declare radius to be a double variable;
double interestRate; // Declare interestRate to be a double variable;
5 Variable types and identifiers
cont…….
The examples use the data types int, double, and char.
Later you will be introduced to additional data types, such as byte, short, long, float,
char, and boolean.
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variablen;
The variables are separated by commas.
For example, int i, j, k; // Declare i, j, and k as int variables
Variables often have initial values. You can declare a variable and initialize it in one
step. Consider, for instance, the following code:
int count = 1; (int count; x=1;)
6 Reading text from the keyboard
There are different option to read values from the keyboard, one of the option is you can
use is the Scanner class.
Java uses System.out to refer to the standard output device and System.in to the standard
input device. By default the output device is the display monitor, and the input device is
the keyboard.
Java also uses System.err to display an error that was happened in the process of
program execution.
Console input is not directly supported in Java, but you can use the Scanner class to
create an object to read input from System.in, as follows:
Syntax
Scanner input = new Scanner(System.in);
7 Reading text cont…..
Reading text cont…..
8
Example:
import java.util.Scanner; // Scanner is in the java.util package
public class ComputeAreaWithConsoleInput
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();
double area = radius * radius * 3.14159;
System.out.println("The area for the circle of radius " +radius +
" is "
+ area);
}
9 Reading text cont…..
Write a Java program that reads your name, department, age and ID-number from the
keyboard and display the result using the following format:
Name: Abebe Yimer
Department: Computer Science
Age: 24
ID-Number: EVE/0341/07
Write a Java program that computes area and perimeter of a circle (Area=PI*R*R and
Perimeter=2*PI*R).
Write a program that reads a Celsius degree in double from the console, then converts it
to Fahrenheit and displays the result. The formula for the conversion is as follows:
fahrenheit = (9 / 5) * celsius + 32
10 Solution for Q1
import java.util.Scanner;//import java.util.*;
Public class first_read
{
public static void main (String [] args)
{
String name,Id,Dept;
int age;
Scanner sc=new Scanner(System.in);
System.out.println(“Please enter students information ”);
name=sc.nextLine();
Dept=sc.nextLine();
Id=sc.next();
age=sc.nextInt();
11 Cont…..
System.out.println(“Name : “ +name);
System.out.println(“Department:”+Dept);
System.out.println(“Age: ”+age);
System.out.println(“ID-Number:”+Id);
}//end of the main function
}//end of the program
12 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.
For example PI is a constant 3.14159;
Syntax for declaring a constant:
final datatype CONSTANTNAME = VALUE;
final float PI=3.14159;
13 Number types, strings
Character Data Type and Operations
14
The character data type, char, is used to represent a single character. A character
literal is enclosed in single quotation marks. Consider the following code:
char letter = 'A';
char numChar = '4';
The first statement assigns character A to the char variable letter. The second
statement assigns digit character 4 to the char variable numChar.
Computers use binary numbers internally. A character is stored in a computer as a
sequence of 0s and 1s.
15 Character Data Type cont……
Escape Sequences for Special Characters:
16 Unicode characters
A character is stored in a computer as a sequence of 0s and 1s. Mapping a character
to its binary representation is called encoding. There are different ways to encode a
character.
Java supports Unicode, an encoding scheme established by the Unicode
Consortium to support the interchange, processing, and display of written texts in
the world’s diverse languages.
A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal
digits that run from \u0000 to \uFFFF.
If no Geez font is installed on your system, you will not be able to see the Geez
characters in your computer system.
Example: System.out.println(‘\u7654’);
System.out.println(‘\u1234’);
17
The String Type
The char type represents only one character. To represent a string of characters, use the data
type called String.
For example, the following code declares the message to be a string with value “Welcome to Java”.
String message = "Welcome to Java";
String is actually a predefined class in the Java library.
The plus sign (+) is the concatenation operator if one of the operands is a string. If one of the operands is a
nonstring (e.g., a number), the nonstring value is converted into a string and concatenated with the other string.
Here are some examples:
// 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
18
The String type cont….
Write a Java program that reads a name, father name and G. Father name and display a full
name. Sample output
Please enter a Name: Temesgen
Please enter a Father Name: Yalew
Please enter a Grand Father Name: Ibrahim
Full Name: Temesgen Yalew Ibrahim
19 Programming Errors
Programming errors are unavoidable, even for experienced
programmers. Errors can be categorized into three types: syntax errors,
runtime errors, and logic errors.
Syntax Errors:- errors that occur during compilation are called syntax
errors or compile errors. Syntax errors result from errors in code
construction, such as mistyping a keyword, omitting some necessary
punctuation, or using an opening brace without a corresponding closing
brace.
These errors are usually easy to detect, because the compiler tells you
where they are and what caused them.
20 cont
Runtime errors are errors that cause a program to terminate abnormally.
They occur while a program is running if the environment detects an operation that is
impossible to carry out. Input errors typically cause runtime errors.
Logic errors occur when a program does not perform the way it was intended to.
Errors of this kind occur for many different reasons.
[email protected]
21 Debugging
Syntax, runtime and logic errors are called bugs.
The process of finding and correcting errors is called debugging.
A common approach is to use a combination of methods to narrow down
to the part of the program where the bug is located.
You can hand-trace the program (i.e., catch errors by reading the
program), or you can insert print statements in order to show the values
of the variables or the execution flow of the program.
This approach might work for a short, simple program. But for a large,
complex program, the most effective approach is to use a debugger utility
(software).
22 Operators and operator precedence
23 Operators & operator precedence example
class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
System.out.println("5 + 2 * 3 - 1 = " +result);
result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);
result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = ++x + 3 ;
System.out.println("result = " +result); } }
24 Augmented Assignment Operators
The operators +, -, *, /, and % can be combined with the assignment operator to
form augmented operators.
Very often the current value of a variable is used, modified, and then reassigned
back to the same variable. For example, the following statement increases the
variable count by 1:
count = count + 1;
Java allows you to combine assignment and addition operators using an
augmented (or compound) assignment operator. For example, the preceding
statement can be written as:
count +=1;
The += is called the addition assignment operator
25 Type Conversion/ Casting
It is easy to change int values are converted to double values when necessary. On the other hand,
there are obviously times when you want to consider a double as an integer. Numeric
conversions are possible in Java, but of course information may be lost.
Conversions in which loss of information is possible are done by means of casts.
The syntax for casting is to give the target type in parentheses, followed by the variable name.
For example:
double x = 9.997;
int nx = (int) x;
char cb='a';
int cd=(int)cb;
26 Casting in Java
[email protected]
27
[email protected]
28
[email protected]
29
[email protected]
30
[email protected]
31
32
Next Chapter III
Decision and Repetition
Statements
33 Quiz
1. Write a program that reads the following information and prints a payroll
statement:
Employee’s name
(e.g., Chala Bedassa)
Number of hours worked in a day (e.g., 8)
Hourly pay rate (e.g., 20)
Tax rate (e.g., 20%)
Calculate a net salary using (net=30 *hours_worked*pay_rate*(1-tax_rate))
2. Write a Java program that reads three numbers from the keyboard and
compute there sum, Product, and average.
(4 pts.)
[email protected]34
1. Write principles of object oriented programming paradigm?
(2 pts.)
2. Why we use object oriented programming instead of a procedural programming
language?
(2 pts)
3. Write characteristics of Java programming language?
(3 pts.)
4. Compare and contrast Java programming language with C++. (3 pts.
Bonus)
[email protected]