Basic Elements of Programming Language
Basic Elements of Programming Language
Basic Elements of Programming Language
1
Outline
Identifiers
Variables
Named constants
Literals
Reserved Words
Comments
Data Types
Operators
Statements
Expressions
Blocks
Name Conventions
Numeric Type Conversion
2
Identifiers
• Identifiers are the names that identify the elements such as
classes, methods, and variables in a 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.
– Example: $2, ComputeArea, area, radius, and
showMessageDialog are legal identifiers, whereas
– 2A and d+4 are not because they do not follow the rules. 3
Variables
• Variables are used to represent values that may be
changed in the program.
• Variables are for representing data of a certain type.
• The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on its
data type.
• Example: int count; double radius;
• Every variable has a scope. The scope of a variable is
the part of the program where the variable can be
referenced.
4
Named Constants
• A named constant is an identifier that represents a
permanent value.
• 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.
• The word final is a Java keyword for declaring a
constant.
• Example: final double PI=3.14159;
5
Literals
• A literal is a constant value that appears directly in a
program.
• For example, 34 and 0.305 are literals in the following
statements:
• int numberOfYears = 34;
• double weight = 0.305;
• String str = “Hello”;
6
Reserved Words
• Reserved words or keywords are words that have
a specific meaning to the compiler and cannot be
used for other purposes in the program.
7
Comments
• Comments are documents that describes what the
program is and how the program is constructed.
• Comments help programmers to communicate and
understand the program.
• Comments are not programming statements and thus are
ignored by the compiler.
• In Java, there are three types of comments:
Single Line comment: is use to comment texts on one line.
//this line prints the value of var1
Multiple Line comment: Anything enclosed by the pair /* and
*/ is considered a comment.
Javadoc Comment: javadoc comments begin with /** and end
with */. 8
Data Types
• Data types are used to determine what kind of
data is stored in memory.
• Every data type has a range of values.
9
Data Types
1. Numeric Data Types
– Java has six numeric types for integers and floating-point
numbers.
– The following lists are the six numeric data types, their
ranges, and their storage sizes.
10
Data Types
2. Character Data Type
– A character data type represents a single character.
– Example;
• char letter = 'A';
• char numChar = '4' ;
– A string literal must be enclosed in quotation marks (" ").
– A character literal is a single character enclosed in single quotation marks ('
').
– Therefore, "A" is a string, but 'A' is a character.
– For example:
• boolean n = true;
• boolean a = false; 11
Data Types
12
Operators
1. Assignment Operator(=)
– The assignment operator causes the operand
on the left side of the assignment statement to
have its value changed to the value on the
right side of the statement.
– Example:
• x=12;
• x = y;
• x = y+2;
13
Operators
2. Numeric or Arithmetic Operators
– The operators for numeric data types include the
standard arithmetic operators:
14
Operators
3. Relational Operators
– Java provides six comparison operators or relational operators.
– The following table shows the equality and relational
operators.
15
Operators
4. Logical Operators
– The logical operators can be used to create a compound Boolean expression.
– The NOT (! ) operator, which negates true to false and false to true.
– The AND (&&) of two Boolean operands is true if and only if both operands are
true.
– The OR (||) of two Boolean operands is true if at least one of the operands is
true.
– The EXCLUSIVE OR (^) of two Boolean operands is true if and only if the two
operands have different Boolean values.
16
Operators
5. Augmented Assignment Operators
– The arithmetic operators can be combined with the
assignment operator to form augmented operators.
17
Operators
6. Increment and Decrement Operators
– The increment (++) and decrement (– –) operators are for
incrementing and decrementing a variable by 1.
18
Operators
• Example: Consider the following code:
int i = 10;
int newNum = 10 * i++;
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 100
int i = 10;
int newNum = 10 * (++i);
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 110
double x = 1.0;
double y = 5.0;
double z = x-- + (++y); // The output of z is 7
19
Operators
7. Evaluating Expressions and Operator Precedence:
– Java expressions are evaluated in the same way as
arithmetic expressions.
– When more than one operator is used in an expression,
the following operator precedence rule is used to
determine the order of evaluation.
• Multiplication, division, and remainder operators are applied
first. If an expression contains several multiplication,
division, and remainder operators, they are applied
from left to right.
• Addition and subtraction operators are applied last. If an
expression contains several addition and subtraction
operators, they are applied from left to right.
20
Operators
• Example:
21
Operators
8. Object Operators:
– The new operator: is used to create an object from a
class.
– The instanceof operator: is used to test whether the
object is an instance of the specified type (class).
22
Numeric Type Conversions
25
Programming Control Structures
27
Selection …
1. One -Way if Statements
– An if statement executes the statements if the
condition is true
– A one-way if statement executes an action if and only
if the condition is true.
– The syntax for a one-way if statement is:
if (boolean-expression) {
statement(s);
}
28
Selection …
2. Two-Way if-else Statements
– An if-else statement decides which statements to
execute based on whether the condition is true or
false.
– The syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
29
Selection …
3. Nested if and Multi-Way if-else Statements
• An if statement can be inside another if statement
to form a nested if statement.
• The nested if statement can be used to implement
multiple alternatives.
• Example:
• For instance, assigns a letter grade to the variable
grade according to the score, with multiple
alternatives.
30
Selection …
31
Selection…
4. switch Statements
– A switch statement executes statements based on the
value of a variable or an expression
– Overuse of nested if statements makes a program
difficult to read.
– Due to this problem, Java provides a switch
statement to simplify coding for multiple conditions.
32
Selection…
• Syntax:
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
33
Selection…
if (x > 0)
y = 1; y = (x > 0) ? 1 : -1;
else
y = -1;
36
3. Repetitive /Loops
37
Repetitive…
1. The while Loop
– A while loop executes statements repeatedly while
the condition is true.
– The syntax for the while loop is:
while (condition) {
Statement(s);
}
38
Repetitive…
2. The do-while Loop
– A do-while loop is the same as a while loop except
that it executes the loop body first and then checks the
loop condition.
– The do-while loop is a variation of the while loop.
– Its syntax is:
do {
Statement(s);
} while(condition);
39
Repetitive…
3. The for Loop
– A for loop has a concise syntax for writing loops.
– In general, the syntax of a for loop is:
40
Repetitive…
4. for-each Loop or enhanced for loop
– Java supports a convenient for loop, known as a for-each loop, which enables
you to traverse the array sequentially without using an index variable.
– The syntax for a for-each loop is:
– You can read the code as “for each element u in myList, do the following.”
41
Repetitive…
5. Nested Loops
– A loop can be nested inside another loop.
– Nested loops consist of an outer loop and one or more inner loops.
public class MultiplicationTable {
public static void main(String[] args) {
System.out.println(" Multiplication Table");
System.out.print(" ");
for (int j = 1; j <= 9; j++)
System.out.print(" " + j);
System.out.println("\n ----------------------------------------------------------");
for (int i = 1; i <= 9; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; j++) {
System.out.print(i * j);
}
System.out.println();
}
} 42
}
Repetitive…
6. Jumping Statements
– The break and continue keywords provide additional
controls in a loop
– Example using Break
43
Jumping Statements
• Example using continue
44
Methods in Java
45
Methods in Java
• Methods can be used to define reusable code and
organize and simplify code.
46
Method…
Without Method, it needs three independent for loop.
47
Method…
Using Method, only one for loop is needed
public class TestMethod{
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 37 is " + sum(20, 37));
System.out.println("Sum from 35 to 49 is " + sum(35, 49));
}
public static int sum(int a, int b){
int result = 0;
for (int i = a; i <= b; i++)
result += i;
return result;
}
}
48
Method…
•Defining a Method:
–A method definition consists of its method name, parameters, return value type, and body.
–The syntax for defining a method is:
49
Method…
• Overloading Methods
– Overloading methods enables you to define the
methods with the same name as long as their
signatures are different.
– Method Overloading is a feature that allows a class to
have two or more methods having same name, if their
argument lists are different.
– If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
50
Overloading Method…
public class TestMethodOverloading {
public static void main(String[] args) {
System.out.println("The maximum of 3 and 4 is “ +max(3, 4) );
System.out.println("The maximum of 3.0 and 5.4 is “+ max(3.0, 5.4) );
System.out.println("The maximum of 3.0, 5.4, and 10.14 is “ + max(3.0, 5.4, 10.14) );
}
public static int max(int num1, int num2){
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2){
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2, double num3){
return max(max(num1, num2), num3);
}
51
}
Method Abstraction and Stepwise Refinement
• Method abstraction is achieved by separating the use of a method from
its implementation.
53
Array In Java
55
Single Dimensional Array
– Hence, Java provides an array that stores a fixed-size
sequential collection of elements of the same type.
– You can store all 100 numbers into an array and access
them through a single array variable.
– An array is reference variable that is used to access
the elements in an array using an index.
– Instead of declaring individual variables, such as
number0, number1, . . . , and number99, you
declare one array variable such as numbers and use
numbers[0] , numbers[1] , . . . , and numbers[99] to
represent individual variables.
– Example:
56
Single Dimensional Array
57
Single Dimensional Array
• Declaring and Creating Array Variables
Declaration array variable:
• elementType[] arrayRefVar;
• Example: double[] myList;
Creating Array:
• Unlike declarations for primitive data type variables, the
declaration of an array variable does not allocate any space in
memory for the array.
• It creates only a storage location for the reference to an array.
• You cannot assign elements to an array unless it has already been
created.
• After an array variable is declared, you can create an array by
using the new operator with the following syntax:
• arrayRefVar = new elementType[arraySize];
58
Single Dimensional Array
• Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement as:
– elementType[] arrayRefVar = new elementType[arraySize];
OR
– elementType arrayRefVar[] = new elementType[arraySize];
• Example: double[] myList = new double[10];
• To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
• For example, the following code initializes the array.
myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123; 59
Single Dimensional Array
• The above array is stored in a memory in the following manner:
60
Single Dimensional Array
• Caution:
– The new operator is not used in the array-initializer syntax.
– Splitting an array initializer would cause a syntax error.
– Example: double[] myList;
myList = {1.9, 2.9, 3.4, 3.5}; This statement is wrong.
• Processing/Accessing Array elements
– When processing array elements, you will often use a for loop
—for two reasons:
All of the elements in an array are of the same type.
Since the size of the array is known, it is natural to use a for loop.
– Assume the array is created as follows:
double[] myList = new double[10];
– The following are some examples of processing arrays.
63
Single Dimension…
1. Initializing arrays with user input values:
import java.util.Scanner;
public class ArrayInitializing{
public static void main(String[] args){
Scanner input = newScanner(System.in);
System.out.print("Enter " + myList.length + " values:");
for (int i = 0; i < myList.length; i++){
myList[i] = input.nextDouble();
}
}
}
64
Single Dimension…
2. Initializing arrays with random values: The following loop initializes the array myList
with random values between 0.0 and 100.0, but less than 100.0.
3. Displaying arrays: To print an array, you have to print each element in the array using a
loop like the following:
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
} 65
Single Dimension…
5. Finding the largest element: Use a variable named max to store the largest element. Initially
max is myList[0] . To find the largest element in the array myList, compare each element with
max, and update max if the element is greater than max.
6. Finding the smallest index of the largest element: Often you need to locate the largest element
in an array. If an array has more than one largest element, find the smallest index of such an
element.
68
Single Dimension…
9. Simplifying coding: Arrays can be used to greatly simplify coding for certain tasks.
Using Array
String[] months = {"January", "February", ...,
"December"};
System.out.print("Enter a month number (1 to 12): ");
int monthNumber = input.nextInt();
System.out.println("The month is " + months[monthNumber -
1]);
if (monthNumber == 1)
System.out.println("The month is January");
else if (monthNumber == 2)
System.out.println("The month is February");
...
else
System.out.println("The month is December");
69
Two-Dimensional Array
• Data in a table or a matrix can be represented using a two-
dimensional array.
• One-dimensional array is used to store linear collections of elements,
but two-dimensional array is used to store a matrix or a table.
• An element in a two-dimensional array is accessed through a row and
column index.
elementType[][] arrayRefVar;
OR
elementType arrayRefVar[][];
– Example: int[][]matrix; or
int matrix[][];
70
Two-Dimensional…
• Creating Two-Dimensional Arrays
– arrayRefVar = new elementType[][];
– Example: matrix = new int[5][5];
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for(int row = 0; row <matrix.length; row++){
for(int column = 0; column <matrix[0].length; column++){
matrix[row][column] = input.nextInt();
}
}
72
String Processing
73
String…
• The classes String, StringBuilder, and StringBuffer,
StringTokenizer are used for processing strings.
74
String…
• Constructing a String
– You can create a string object using
• A string literal or
• An array of characters.
– To create a string from a string literal, use the syntax:
– String newString = new String(stringLiteral);
– The argument stringLiteral is a sequence of characters enclosed inside
double quotes.
– String message = new String("Welcome to Java");
– Java treats a string literal as a String object. Thus, the following statement
is valid:
– String message = "Welcome to Java”;
– To create a string from an array of characters.
– For example, the following statements create the string "Good Day”:
char[] charArray = {'G' , 'o' , 'o' , 'd' , ' ' , 'D’ , 'a' , 'y' };
– String message = new String(charArray); 75
String…
• The StringBuilder and StringBuffer Classes
– The StringBuilder and StringBuffer classes are
similar to the String class except that the String class
is immutable.
– In general, the StringBuilder and StringBuffer
classes can be used wherever a string is used.
– StringBuilder and StringBuffer are more flexible
than String.
– You can add, insert, or append new contents into
StringBuilder and StringBuffer objects, whereas the
value of a String object is fixed once the string is
created. 76
String…
– The StringBuilder class is similar to StringBuffer except that the
methods for modifying the buffer in StringBuffer are synchronized,
which means that only one task is allowed to execute the methods.
– Use StringBuffer if the class might be accessed by multiple tasks
concurrently.
– Using StringBuilder is more efficient if it is accessed by just a
single task.
– Example: To modify strings in the StringBuilder and StringBuffer is:
String str = "Welcome";
StringBuilder sb = new StringBuilder(str);
StringBuffer sbf = new StringBuffer(str);
sb.append("To BDU");
sb.append(“To Bahir Dar University");
System.out.println(sb);
System.out.println(sbf);
77
String…
• StringBuffer
– StringBuffer is mutable means one can change the value of the object .
– The object created through StringBuffer is stored in the heap .
– StringBuffer has the same methods as the StringBuilder , but each method in
StringBuffer is synchronized that is StringBuffer is thread safe .
– Due to this it does not allow two threads to simultaneously access the same method .
– Each method can be accessed by one thread at a time .
– But being thread safe has disadvantages too as the performance of the StringBuffer
hits due to thread safe property .
– Thus StringBuilder is faster than the StringBuffer when calling the same methods of
each class.
– StringBuffer value can be changed , it means it can be assigned to the new value .
• StringBuilder
– StringBuilder is same as the StringBuffer , that is it stores the object in heap and it
can also be modified .
– The main difference between the StringBuffer and StringBuilder is that
StringBuilder is also not thread safe.
– StringBuilder is fast as it is not thread safe . 78
Difference between StringBuffer and StringBuilder
79
StringTokenizer Class
82