OOP Chapter 2
OOP Chapter 2
Chapter Two
Basics in Java Programming
2.1 Variable Types and Identifiers
Java Variables
A variable designates a location in memory for storing data and computational results in the program. A
variable has a name that can be used to access the memory location. Variable names should descriptively
names.
Programs manipulate data that are stored in memory. In a high-level language such as Java, names are used to
refer to data. It is the job of the computer to keep track of where in memory the data is actually stored; the
programmer only has to remember the name. A name used in this way to refer to data stored in memory is
called a variable.
Variable is not a name for the data itself but for a location in memory that can hold data. You should think of
a variable as a container or box where you can store data that you will need to use later. The variable refers
directly to the box and only indirectly to the data in the box. Since the data in the box can change, a variable
can refer to different data values at different times during the execution of the program, but it always refers to
the same box.
In Java, the only way to get data into a variable that is into the box that the variable names are with an
assignment statement. An assignment statement takes the form:
datatype variablename = value;//variable declaration
Data type is an identifier of the variable that can tell the type of data that the variable can hold.
Naming of variables
Names are fundamental to programming. In programs, names are used to refer to many different sorts of
things. In order to use those things, a programmer must understand the rules for giving names to things and
the rules for using the names to work with those things. That is, the programmer must understand the syntax
and the semantics of names.
1|Page
Object Oriented Programming in Java Lecture note
A variable in Java is designed to hold only one particular type of data; it can legally hold that type of data and
no other. The compiler will consider it to be a syntax error if you try to violate this rule. We say that Java is a
strongly typed language because it enforces this rule.
Every programming language has its own set of rules and conventions for the kinds of names that you're
allowed to use, and the Java programming language is no different. The rules and conventions for naming
your variables can be summarized as follows:
❖ Variable names are case-sensitive.
❖ A variable's name can be any legal identifier, an unlimited-length sequence of Unicode letters
and digits, beginning with a letter.
❖ When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing
so will make your code easier to read and understand. In many cases it will also make your code
self-documenting. Also keep in mind that the name you choose must not be a keyword or
reserved word like class, main, static, void etc.
❖ If the name you choose consists of only one word, spell that word in all lowercase letters. If it
consists of more than one word, capitalize the first letter of each subsequent word.
Variable Declaration
A variable can be used in a program only if it has first been declared. A variable declaration statement is used
to declare one or more variables and to give them names. When the computer executes a variable declaration,
it sets aside memory for the variable and associates the variable's name with that memory. It tells the compiler
to allocate appropriate memory space for the variable based on its data type. Every variable has a name, a
type, a size, and a value.
A simple variable declaration takes the form:
datatype-name variable-name;
The variable-name-or-names can be a single variable name or a list of variable names separated by commas.
Good programming style is to declare only one variable in a declaration statement, unless the variables are
closely related in some way. For example:
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;//literal
2|Page
Object Oriented Programming in Java Lecture note
It is also good style to include a comment with each variable declaration to explain its purpose in the program,
or to give other information that might be useful to a human reader. For example:
double principal; // Amount of money invested.
double interestRate; // Rate as a decimal, not percentage.
3|Page
Object Oriented Programming in Java Lecture note
❖ Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using the
fully qualified name. ObjectReference.VariableName.
C. Static variable
❖ Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
❖ Only one copy of each class variable per class is created, regardless of how many objects are created
from it.
❖ Static variables are rarely used other than being declared as constants. Constants are variables that are
declared as public/private, final, and static. Constant variables never change from their initial value.
❖ Static variables are stored in the static memory. It is rare to use static variables other than declared final
and used as either public or private constants.
❖ Static variables are created when the program starts and destroyed when the program stops.
❖ Visibility is same as instance variables. However, most static variables are declared public since they
must be available for users of the class.
❖ Values can be assigned during the declaration or within the constructor. Additionally, values can be
assigned in special static initializer blocks.
❖ Static variables cannot be local.
❖ Static variables can be accessed by calling with the class name ClassName.VariableName.
❖ When declaring class variables as public static final, then variable names (constants) are all in upper
case. If the static variables are not public and final, the naming syntax is the same as instance and local
variables.
4|Page
Object Oriented Programming in Java Lecture note
There are four primitive data types for integer values, including byte, short, int, and long. They are different in
the sizes of the space they occupied in memory. The reason why Java has multiple integer (as well as,
floating-point) types is to allow programmer to access all the types support natively by various computer
hardware and let the program works efficiently.
The eight primitive data types supported by the Java programming language are:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128
and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large
arrays, where the memory savings actually matters.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -
32,768 and a maximum value of 32,767 (inclusive). As with int, the same guidelines apply: you can use
a short to save memory in large arrays, in situations where the memory savings actually matters.
int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is
generally the default choice unless there is a reason (like the above) to choose something else. This data
type will most likely be large enough for the numbers your program will use, but if you need a wider
range of values, use long instead.
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -
9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this
data type when you need a range of values wider than those provided by int.
float: The float data type is a single-precision 32-bit floating point. As with the recommendations for
byte and short, use a float (instead of double) if you need to save memory in large arrays of floating
point.
double: The double data type is a double-precision 64-bit floating point. For decimal values, this data
type is generally the default choice.
boolean: The boolean data type has only two possible values: true and false. Use this data type for
simple flags that track true/false conditions. This data type represents one bit (1 or 0) of information, but
its "size" isn't something that's precisely defined.
char: The char data type is a single 16-bit Unicode character.
5|Page
Object Oriented Programming in Java Lecture note
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Java Identifiers
All Java components require names. Names used for classes, variables and methods are called identifiers. In
Java, there are several points to remember about identifiers. They are as follows:
✓ All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
✓ After the first character, identifiers can have any combination of characters.
✓ A keyword cannot be used as an identifier.
✓ Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, value3
Examples of illegal identifiers: 123abc, emp-salary
6|Page
Object Oriented Programming in Java Lecture note
The syntax new Scanner (System.in) creates an object of the Scanner type. The syntax Scanner
input declares that input is a variable whose type is Scanner. The whole line Scanner input = new Scanner
(System.in) creates a Scanner object and assigns its reference to the variable input. An object may invoke its
methods. To invoke a method on an object is to ask the object to perform a task.
Example:
Write a java program that accepts a radius from the console to compute area of the circle.
Output:
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. The plus (+) sign is used for concatenation.
Concatenating Strings
It combines two strings if two operands are strings.
Example:
8|Page
Object Oriented Programming in Java Lecture note
Example:
class student{
string firstname=”Abel”;
String middlename=”Degu”;
Public static void main(String[] args) {
Student stud1=new Student();
System.out.println(firstname + “ ” + middlename);
System.out.println(firstname.length( ));
} }
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.
Example:
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations in the same way as they are used in algebra.
The following table lists the arithmetic operators.
Example: int A=10, B=20;
Operator description example Output
+ (Addition) Adds values A & B. A+B 30
- (Subtraction) Subtracts B from A A-B -10
* (Multiplication) Multiplies values A & B A*B 200
/ (Division) Divides B by A A/B 0
Divides left-hand operand by right
% (Modulus) B%A 0
hand operand and returns remainder.
9|Page
Object Oriented Programming in Java Lecture note
Relational Operators
The following relational operators are supported by Java language.
Example: int A=10, B=20;
Operator description example Output
Checks if the values of two operands are equal or not, if yes not
== (equal to) (A == B)
then condition becomes true. true
Checks if the values of two operands are equal or not, if values
!= (not equal to) (A != B) true
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of not
> (greater than) (A > B)
right operand, if yes then condition becomes true. true
Checks if the value of left operand is less than the value of right
< (less than) (A < B) true
operand, if yes then condition becomes true.
>= (greater than
Checks if the value of left operand is greater than or equal to the not
or (A >= B)
value of right operand, if yes then condition be comes true. true
equal to)
<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) true
equal to) value of right operand, if yes then condition becomes true.
10 | P a g e
Object Oriented Programming in Java Lecture note
Logical Operators
The following are the logical operators supported by java.
Example: A=true and B=false;
Operator description example Output
If both the operands are non-zero, then the
&& (logical and) (A && B) false
condition becomes true.
If any of the two operands are nonzero, then the
|| (logical or) (A || B) true
condition becomes true.
Use to reverses the logical state of its operand. If a
! (logical not) condition is true then Logical NOT operator will !(A && B) true
make false.
11 | P a g e
Object Oriented Programming in Java Lecture note
Assignment Operators
The following are the assignment operators supported by Java.
Operator description example
= (Simple assignment Assigns values from right side operands to left C = A + B will assign
operator) side operand. value of A + B into C
+= (Add AND assignment It adds right operand to the left operand and C += A is equivalent to
operator) assigns the result to left operand. C=C+A
-= (Subtract AND It subtracts right operand from the left operand C -= A is equivalent to
assignment operator) and assigns the result to left operand. C=C–A
*= (Multiply AND It multiplies right operand with the left C *= A is equivalent to
assignment operator) operand and assigns the result to left operand. C=C*A
/= (Divide AND It divides left operand with the right operand C /= A is equivalent to
assignment operator) and assigns the result to left operand. C=C/A
%= (Modulus AND It takes modulus using two operands C %= A is equivalent to
assignment operator) and assigns the result to left operand. C=C%A
12 | P a g e
Object Oriented Programming in Java Lecture note
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator. This operator consists
of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which
value should be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
Example:
public class example {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
}}
Unary Operators
Unary operators use only one operand. They are used to increment, decrement or negate a value.
Operator description
- Unary minus negating the values
+ Unary plus converting a negative value to positive
++ Increment operator incrementing the value by 1
-- Decrement operator decrementing the value by 1
! Logical not operator inverting a boolean value
// Java program to illustrate unary operators
public class operators {
public static void main(String[] args) {
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
boolean condition = true;
c = ++a;
System.out.println(“Value of c (++a) = “ + c);
c = b++;
System.out.println(“Value of c (b++) = “ + c);
c = --d;
System.out.println(“Value of c (--d) = “ + c);
c = --e;
System.out.println(“Value of c (--e) = “ + c);
System.out.println(“Value of !condition =” + !condition);
}
}
13 | P a g e
Object Oriented Programming in Java Lecture note
14 | P a g e
Object Oriented Programming in Java Lecture note
15 | P a g e
Object Oriented Programming in Java Lecture note
Example:
The Unicode of ‘a’ is 97, which is within the range of a byte, these implicit castings are fine:
byte b = ‘a’;
int i = ‘a’;
But the following casting is incorrect, because the Unicode \uFFF4 cannot fit into a byte:
byte b = ‘\uFFF4’;
To force assignment, use explicit casting, as follows:
byte b = (byte)‘\uFFF4’;
Any positive integer between 0 and FFFF in hexadecimal can be cast into a character implicitly. Any number
not in this range must be cast into a char explicitly.
16 | P a g e
Object Oriented Programming in Java Lecture note
2. if-else statement
The "if-else" statement is an extension of if statement that provides another option when 'if' statement
evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional_expression){
<statements>;
...;
}
else{
<statements>;
....;
}
17 | P a g e
Object Oriented Programming in Java Lecture note
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal
to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number"); }
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of
90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
} }
You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are
executed (grade = 'C';) and the remaining conditions are not evaluated.
18 | P a g e
Object Oriented Programming in Java Lecture note
3. switch statement
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an
expression that should evaluates to byte, short, char or int primitive data types, only. In a switch block there
can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch
expression is matched with each case label. Only the matched case is executed, if no case matches then the
default statement (if present) is executed.
Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
case expression n:
<statement>;
default:
<statement>;
}//end switch
Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so
code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch(day){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
19 | P a g e
Object Oriented Programming in Java Lecture note
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid
entry");
break;
}
The following code example, SwitchDemo, declares an int named month whose value represents a month.
The code displays the name of the month, based on the value of month, using the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January"; break;
case 2: monthString = "February"; break;
case 3: monthString = "March"; break;
case 4: monthString = "April"; break;
case 5: monthString = "May"; break;
case 6: monthString = "June"; break;
case 7: monthString = "July"; break;
case 8: monthString = "August"; break;
case 9: monthString = "September"; break;
20 | P a g e
Object Oriented Programming in Java Lecture note
21 | P a g e
Object Oriented Programming in Java Lecture note
value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and
increments value of i. Now again control comes back to the loop and condition is checked. This procedure
continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num " + i);
i++;
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to
true, the while statement executes the statement(s) in the while block. The while statement continues testing
the expression and executing its block until the expression evaluates to false. Using the while statement to
print the values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
} } }
2. do-while statements
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once, as shown
in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
22 | P a g e
Object Oriented Programming in Java Lecture note
The for statement also has another form designed for iteration through arrays .This form is sometimes referred
to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To
demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
} } }
In this example, the variable item holds the current value from the numbers array.
Jump Statement:
continue statement
A continue statement stops the current iteration of a loop (while, do or for) and causes execution to resume at
the top of the nearest enclosing loop. The continue statement can be used when you do not want to execute the
remaining statements in the loop, but you do not want to exit the loop itself.
The following program explains the continue statement.
public class ProgramContinue{
public static void main(String[] args) {
System.out.println(“Odd Numbers”);
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
System.out.println(i + “\t”);
}}}
break statement
The break statement terminates the enclosing loop (for, while, do or switch statement). break statement can be
used when we want to jump immediately to the statement following the enclosing control structure.
24 | P a g e
Object Oriented Programming in Java Lecture note
25 | P a g e
Object Oriented Programming in Java Lecture note
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates
an array with enough memory for ten integer elements and assigns the array to the anArray variable.
anArray = new int[10]; // create an array of integers
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of
square brackets, such as String[][] names. Here String is the data type and names is the name of
multidirectional arrays. Each element, therefore, must be accessed by a corresponding number of index
values.
In the Java programming language, a multidimensional array is simply an array whose components are
themselves arrays. A consequence of this is that the rows are allowed to vary in length, as shown in the
following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
26 | P a g e
Object Oriented Programming in Java Lecture note
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}}
Java comments
Java comments are statements that are not executed by the compiler and interpreter. The comments can be
used to provide information or explanation about the variable, method, class or any statement. It can also be
used to hide program code for specific time.
Types of Java Comments
1) Java Single line comment
The single line comment is used to comment only one line. A single-line comment begins with a // and ends at
the end of the line.
syntax example
//Comment //This is single line comment
2) Java multiline comment
This type of comment must begin with /* and end with */. Anything between these two comment symbols is
ignored by the compiler. A multiline comment may be several lines long.
syntax example
/*Comment starts
continues /* This is a
continues multi line
... comment */
Commnent ends*/
3) Java Documentation comment
This type of comment is used to produce an HTML file that documents our program. The documentation
comment begins with a /** and ends with a */.
Example
/**
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools Templates
and open the template in the editor.
*/
27 | P a g e