Professional Documents
Culture Documents
Chapter 2 PDF
Chapter 2 PDF
Special Symbols
- some of the special symbols:
+ - * /
. ; ? ,
<= != == >=
Identifiers
- names of things such as variables, constants, and methods.
- Some identifiers are predefined (example: print, println, printf –
output and nextInt, nextDouble, next, nextLine – input data),
others are defined by the user.
- All identifiers must obey Java’s rules. It can consists of letters, digits, the
underscore character(_) and dollar sign ($), and must begin with letter,
underscore, or the dollar sign.
- Java is case sensitive – uppercase and lowercase letters are considered
different.
- Can be any length.
1
2.3 Data Types
Primitive
2 types:
i- Numerical data type
ii. Constant data type
Example:
float num;
double y = 12.456789;
Example:
boolean student;
student = true;
2
Constant data type
Example:
final int SIZE = 40;
- constant inside a class are declared with the keyword static.
Example:
public static final int SIZE = 40;
- String manipulation.
Example:
String look = “Ameera is pretty”;
String see, sub1, sub2;
int n;
see = look.toUpperCase(); //”AMEERA IS PRETTY”
see = look.toLowerCase (); //”ameera is pretty”
n=look.length(); //16
char x =look.charAt(4); //r
sub1 = look.subString(7); // is pretty
sub2 = look.subString(7,9); // is
see = look.replace(“Ameera”,”Hanna”);
//Hanna is pretty
3
2.4 Control Structures
- two types
i. Decision statement
ii. Iteration statement
Decision statement
i. if statement
syntax:
if (condition)
{
statements;
}
~ statments will be implemented only when the condition is true.
Example:
if ( age < 7)
{
System.out.println(“go to kindergarten”);
}
syntax:
if (condition)
{
Statement_1;
}
else {
Statement_2;
}
syntax:
if (condition_1)
{
Statement_1;
}
4
else if (condition_2)
{
Statement_2;
}
else …
:
:
else if (condition_n)
{
Statement_n;
}
else
Statement_m;
Iteration statement
~ while loop
~ do..while loop
~ for loop
~ nested loop
~ break and continue statement
break
continue
~ used in while, for and do..while structures.
~ when it is executed in a loop, it skips the remaining statements in the loop and
proceeds with the next iteration of the loop.
2.5 Array
5
2.5.1 Array declaration of Primitive Data Types
• Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable> [ ] //variation 2
• Array Creation
<variable> = new <data type> [ <size> ]
• Example
double[ ] rainfall;
rainfall = new double[12];
double rainfall[ ];
rainfall = new double[12];
rainfall[2] ???
• Like other data types, it is possible to declare and initialize an array at the same
time.
• Example:
int[] number = { 2, 4, 6, 8 };
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
String[] monthName = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"};