Chapter 2 Oop
Chapter 2 Oop
Chapter Two
Basic in Java Programming
1. Comments
Comments should be used to improve the readability of the code. Java recognizes two types of comments.
Single-Line Comments
A single-line comment can be delimited either by // or /* … */. The // is also used to comment out a line of code that
you want to skip during a particular run. The following example illustrates these uses;
/* Single-line comment */
System.out.println(“Hello World”); //End of line comment
// System.out.println(“Goodbye”);
Block Comments
A block comment or comment block is multiline comment used to describe files, methods, data structure, and
algorithms.
/*
*Multiline comment
*/
2. What is Variable?
Variable are a place where information can be stored while a program is running.
Their value can be changed at any point in the program.
In order to create a variable, you must give it name and identify what type of information it will store
Creating Variable
You must create the variable by declaring its name and the type of information it will store.
The type is listed first, followed by the name.
For example:
o in high Score;
type name
More example:
o String username;
o boolean gameOver;
o byte smallValue;
o double testGrade;
Naming Variables
The name that you choose for a variable is called an identifier.
An identifier can be of any length, but must start with:
- a letter ( a – z )
- an underscore ( _ )
- or a dollar sign ( $ )
The rest of the identifier can include any character except those used as Operators in Java such as +, -, *.
In addition, there are certain keywords reserved in the Java language which can never be used as identifiers.
Java is a case-sensitive language -the capitalization of letters must be consistent A rose in not a Rose is not a ROSE.
It is good practice to select variable names that give a good indication of the sort of data they hold.
- For example, if you want to record the size of a hat, hatSize is a good choice for a name where qqq would be a
bad choice
When naming a variable, the following convention is commonly used:
- The first letter of a variable name is lowercase.
- Each successive word in the variable name begins with a capital letter.
- All other letters are lowercase.
Here are some examples:
- pageCount
- loadFile
- anyString
- threeWordVariable
3. Statements
A statement is a simple command written in a programming language that causes something to happen.
All statements in java are separated by semicolon.
Some statements produce a value and are known as expressions.
- This means that it is a language in which each type of data is predefined as part of the programming
language
- All Variable defined in a program must be declared with one of the data types certain operations may be
allowable only with certain data types. The language compiler enforces the data typing.
Data Description
byte Variable of this kind can have a value from -128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from -32768 to 32767 and occupy 16 bits in
memory
int Variables of this kind can have a value from -2147483648 to +2147483647 and occupy 32
bits in memory
Here are some examples of when you would want to use integer types:
- Byte smallValue:
- smallValue=-55;
- short pageCount =1250;
- long bigValue = 8233371223351231513L;
Note
- In the last example we named a long integer type and the value hand an L at the end :
823337123351231514L
- That is because: if the number had been small enough to be counted as an int type instead, then the program
would have automatically considered it an int instead of a long.
- By adding an L to the end of the value the program is „forced‟ to consider the value to be of a type long even
if it was small enough to be an int
b) Floating point Data Types
There are two data type can be used to store decimal values. The one you choose to use depends on the size of the
number that we want to store.
float Variable of this kind can have a value from 1.4e(-45)to 3.4e(+38)
double Variable of this kind can have a value from 4.9e(-324)to 1.7e(+308)
Here are some example of when you would want to use floating point types:
- double g = 7.7e100;
- double tinyNumber = 5.82e-203;
- float costofBook = 49.99F;
Note: in the last example we added an F to the end of the value. Without the F, it would have automatically
been considered a double instead.
c) Boolean data type
There is a data type that can be used in situations where there are two options, either true or false.
There are called booleans.
For example
- Boolean monster Hungry=true;
- Boolean file Open=false;
- char myQuestion=‟?‟;
Note that you need to use singular quotation marks when assigning char data types otherwise. The program
might look for another variable name instead of a letter form assign an ant type instead of a number.
e) Introduction to String
Strings are a common feature in computer programming because they provide a way to store text and present
it to users. The most basic element of a string is a character. A character is a single letter, number,
punctuation mark, or other symbol.
A string is a collection of characters. You can set up a variable to hold a string value by following string
with the name of the variable, as in this statement:
String fullName = “Abdisa Gemachu Olana”,
This statement creates a string a string variable called Full Name and stores the text Ada McGrath Stewart in
it, which is the F full name of Hunters pianist. A string is denoted with double quotation marks around the
text in a java statement. These quotation marks will not be included in the string itself.
Unlike the other types of variable you have used, float, char, boolean, and so on _the name of the string type
is capitalized.
The reason for this is that are somewhat different than the other variable types in java. Strings are a special data
resource called object, and the types of all objects are capitalized. You‟ll be learning about objects during
chapter 4 “creating your first object‟ the important thing to note during this hour is that strings are different than
the other variable types, and because of this difference, string is capitalized when string are used in a statement.
The most basic way to display a string in a java program is with system out println() statement this statement
takes any strings and other variable inside the parentheses and displays their values, the following statement
displays a line of text to the system output device which is the computer monitor
The preceding statement would cause the following text to be displayed silence affects everyone in the end.
Displaying a line of text on the screen is often called printing, which is what println() stands for:
print this line: you can use the system.out.println() statement to display text within double
quotation marks and also to display variable as you will see. Put all the material you want to be
displayed within the parentheses.
Another way to display text is to call system.out.print(). This statement displays string and other
variables inside the parentheses, but unlike system out println(), it allows subsequent statement to
display text on the same line.
You can use system.out.print() several times in a row to display several thing on the same line, as in
this example:
System.out.print(“she”);
System.out.print(“never”);
System.out.print(said”)‟
System.out.print(another”);
System.out.println(“word”)‟
To display them, Java has created a special code that can be put into a string: \” whenever this code is encountered in
a string, it is replaced with a double quotation mark. For example, examine the following:
You can insert several special character into a string in this manner. The following list shows these special
characters. Note each is preceded by a backslash ( \ ).
The newline character causes the text following the newline character to be displayed at the beginning of the next
line. Look at this example
Music by
Fedasa Gurmu
When you use the System.out.println() statement and handle string in other ways you will sometimes
want to paste two string together: you do this by using the same operator that is used to add numbers +.
The + operator has a different meaning in relation to strings. Instead of trying to do some math, it pastes two strings
together. This action can causes strings to be displayed together or it can make one big strings out of two smaller
ones.
Concatenation is a word used to describe this action, because it means to link two things together. You‟ll probably
see this term in other books as you build your programming skills. So it‟s worth knowing. However, pasting is the
term used here to describe what happen, when one string and another string decide to get together.
Instead of putting this entire string on a single line which would make it harder to understand when you look at the
program later. The + operator is used to break up the text over two line of the program‟s java text file.
“The piano „is as peculiar and haunting as any film I‟ve seen.”
Although you can use the + operator to paste two string together as demonstrated in the preceding section you will
use it more often to link string and variables‟. Take a look at the following:
This example displays a unique facet about how the + operator works with drtings.it can cause variable that are not
strings to be treated just like string when they are displayed. The variable length is an integer set to the value 121. It
is displayed between the strings Running time and minutes. The Systemout.prtintln() statement is being
asked to display a string plus an enter, plus another string. This statement works because at least one part of the
group is a string.
One thing you will be testing often in your programs is whether one string is equal to another. You do this by using
equals() in a statement with both of the strings as in this example:
This example uses two different string variables. One, favorite, is used to store the name of Abdi‟s favorite
instrument: a piano. The other guess is used to store a guess as to what her favorite might be. The guess is that Abdi
prefers the ukulele.
The third line displays the text is Abdi‟s favorite instrument a followed by the value of the guess variable, and then
question mark. The fourth line displays the text Answer: and then contains something new:
Favorite.equals(guess)
This part of the statement is known as a method. A method is a way to accomplish a task in a java program. This
methods task is to determine whether one string, favorite has the same value as another string, guess. If the two
string variables have the same value the text True will be displayed if not, the text False will be will be displayed.
The following is the output of this example:
Operators are the most basic unite of a program. They perform operations on primitive data types.
Operators are special symbols used for methodical functions, assignment statements and logical comparisons
As you know, expressions are statement that produce a value. Some of the most common expressions are
mathematical and make use of operators
Today we will go over 5 different group of operators.
Arithmetic operator
Assignment operator
Relational operators
Logical operator
Increment/Decrement operators
i. Arithmetic operators
Java has 4 basic arithmetic operators. +,-,*, and /, which have the usual meanings-add, subtract, multiply, and
divide. The order of operator or precedence that applies when an expression using these operators is evaluated is the
same as you learned at school.
For example
int number= 20-3*3-9/3; Will produce the value 8
int number =(20-3)*(3-9)/3; Is equivalent to 17*(-6)/3 will produce the value -34
For example
int x = 3;
int y =5;
boolean state ;
state =(x>y);
Now state is assigned the value false because x is not greater than y
State = (15 == x*y);
Now state is assigned the value true because the product of x and y equals 15
state = (!=x*y);
Now state is assigned the value true because the product of x and y is not equal to x.
Logical operators are only used to combine expression that have a value of True or False. Because they operate
on boolean values. They are also referred to as boolean operators.
x y x&y x|y !x
x && y x || y
True True True True False
True False False True False
False True False True True
False False False False True
For example
boolean x =true
boolean y = false;
boolean state;
boolean x= true;
boolean y=false;
boolean state
boolean state;
The difference between && and is that the conditional && will not bother to evaluate the right-hand operator if the
left- hand operator is false since the result is already determined in this case to be false. The logical & operator will
evaluate both terms of the expression
|| versus |
The difference between || and | is that the conductional || will not bother to evaluate the right –hand operator if the
left-hand operator is true. Since the result is already determined in this case to be true. The logical | operator will
evaluate both terms of the expression.
As we saw in the previous examples in most cases the two operators are interchangeable. Here are examples of
where it matters operator we use.
//Do something
Here the variable count will be incremented in any event. If you use && instead of &, count will only be
incremented if the left operand of the AND operator is trues you get a different result depending on which operator
is used.
// Do something
In this case the right for the && operator will only be executed if the left operand is True-that is when count is
positive. Clearly, if we were to use & here and count happened to be zero, we will be attempting to divide the value
of total by 0, which will terminate the program.
v. Increment/Decrement operator
The increment /operator has the same effect on count for subtracting 1 count= count-1;
--count;
The increment / decrement operator has two forms.
o The prefix form ++ count, -- count
First adds 1 to the variable and then continues to any other operator in the expression
int numOrange = 5;
int numApple = 10;
int numFruit;
numFruit = ++numOrange + numApple;
numFruit has value 16
numOrange has value 6
int numOrange = 5
int numApple =10;
int numFruit;
numFruit = +++ numOrange++ + numApple;
numFruit has value 15
numOrange has value 6
Precedence of operator
Precedence specifies the order in which an operation is performed.
Consider the expression: a + b * c
The multiplication is carried out first, then the value of b * c is added to a.
Converting to integers
This method takes a string containing an in character form. It looks at those characters and calculates an int value.
That value is assigned to numb.
Exercise
Write a program which asks users for two integers. The two integers are added up the result is printed to
screen.