CSC- 210
Object Oriented Programming
LECTURE 1
JAVA FUNDAMENTALS
OUTLINE
• Basic elements of Java
• I/O statements in Java
• Selection statements in Java
• Repetition statements in Java
• Arrays in Java
Header files
Include a sequence of header files.
return 0; }
Global Variables & Function Declaration
Give a descriptive name to the main class.
int main (void){
Method Body
Include a sequence of instructions.
Return Type
Program Template for simple JAVA Program
Import Statements
Include a sequence of import statements.
public class
{
} }
Class Name
Give a descriptive name to the main class.
public static void main (String[] args){
Method Body
• Package is a container for classes .
• A package is a grouping of related types (classes and interfaces) providing access protection and name space management.
• In simple words, packages is the way we organize files into different directories according to their functionality, usability as well as category they should belong to.
WHY DO WE NEED PACKAGES?
• One can easily determine that these types are related.
• One knows where to find types that can provide task-related functions.
• The names of your types won't conflict with the type names in other packages because the package creates a new namespace.
• One can allow types within the package to have unrestricted access
ORGANIZING CLASSES WITH
PACKAGE
package bahria.academics; class Student { }
The “package” keyword provides namespace for the classes (=systematic grouping of related classes)
a. For example, the package bahria.transport can be used to store classes such as Car, Transit, Bus, Driver, etc.
b. On the other hand, the package bahria.academics can be used to store classes such as Student, Lecturer, Course, Program, etc..
If omitted, the class is automatically stored in the default package. The package statement should be declared in the first non-comment line.
PACKAGES IN JAVA
• A package is a namespace that organizes a set of related types, such as classes and interfaces.
• The syntax to create a package is:
package <package name>;
• An example to create package:
package test;
class PackageDemo{}
PACKAGES IN JAVA
• A class can access the classes in another package by importing the required package.
• The syntax to import a package is:
import <package name>.*;
• An example to import a package:
import test.*; class Demo{
}
CLASSES
•
Classes built for real world objects that cannot be
represented using available types
•
A class is an "extension" of Java
•
Definition of class:
“A group or category of things that have a set of attributes in
common.“
•
In programming: a pattern, blueprint, or template for
CLASS DECLARATION
Syntax:
class className
{
// Attributes (variables & constants) // and behaviors (methods)
}
Where
• className is the name of a reference type
•
And { } mark the boundaries of the declaration
Example
package Lecture2;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); }
Hello World in C++ and JAVA
public class HelloWorld {
public static void main(String [] args) {
System.out.println(“Hello World!”); } //main end
} //class end
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl; return 0;
} //main end
Hello.cpp HelloWorld.java
Keyboard Input in C++ and JAVA
import java.util.Scanner;
public class Input {
public static void main(String [] args) { int a,b;
Scanner input = new Scanner(System.in); System.out.println(“Enter the values of a and b”); a = input.nextInt();
b = input.nextInt();
System.out.println(“a =“+a+”b=“+b); } //main end
}//class end #include <iostream>
using namespace std;
int main() { int a,b;
cout << “Enter the values of a and b" << endl; cin>>a>>b;
cout<<“a =“<<a<<“b=“<<b; return 0;
}
//main end
Sample Program (Scanner Class)
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
This the Package which contain the classes for getting input from the user
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
Import is used to include external packages in your code
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
Here we are creating an object of the Scanner class that we have imported in out java code… where input is name of the object… by the help of this input object we are going to take input from the users.
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
new reserved word is used to create an object of the
class…
System.in is an input stream
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
input.nextInt() would take the input from the user and would assign it to a variable num1.
import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
System.out.println(“Enter 1st Value: ");
num1=input.nextInt();
System.out.println(“Number Entered = " + num1);
}
}
SCANNER CLASS METHODS
Method-Name Function
nextBoolean() reads one boolean value (true/false) nextByte() reads one byte value
nextShort() reads one short value nextInt() reads one int value nextLong() reads one long value nextFloat() reads one float value nextDouble() reads one double value
next() reads one string of non-whitespace characters
IDENTIFIER, VARIABLE, CONSTANT
• Identifier is a name that we associate with some program entity (class name, variable name, parameter name, etc.)
• Java Identifier Rule:
• May consist of letters (‘a’ – ‘z’, ‘A’ – ‘Z’), digit characters (‘0’ – ‘9’), underscore (_) and dollar sign ($)
• Cannot begin with a digit character
• Variable is used to store data in a program
• A variable must be declared with a specific data type • Eg:
• Constant is used to represent a fixed value
• Eg:
• Keyword final indicates that the value cannot change
int countDays, $total, _total, total5; double priceOfItem;
Class name: UpperCamelCase
Eg: Math, HelloWorld, ConvexGeometricShape
Variable name: LowerCamelCase
Eg: countDays, innerDiameter, numOfCoins
Constant: All uppercase with underscore
Eg: PI, CONVERSION_RATE, CM_PER_INCH
COMMENTS
Java supports three types of comments:
………..
………*/
Delimeter Use
// Used for commenting a single line
/* ————— */ Used for commenting a block of code
Type Name Size (#bytes) Range Default Value
byte 1 –128 to 127 0
short 2 –32,768 to 32,767 0
int 4 –2,147,483,648 to 2,147,483,647 0
long 8 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
0L
float 4 Negative: -3.4028235E+38 to -1.4E-45
Positive: 1.4E-45 to 3.4028235E+38
0.0f
double 8 Negative: -1.7976931348623157E+308 to
-4.9E-324
Positive: 4.9E-324 to 1.7976931348623157E+308
0.0d
char 2 '\u0000‘ to '\uffff' '\u0000' String - 2,147,483,647 characters null
boolean 1 bit true/false false
Integer Data
Types
NUMERIC DATA TYPE
CONVERSION
• When operands of an operation have differing types:• If one of the operands is double, convert the other to double
• Otherwise, if one of them is float, convert the other to float
• Otherwise, if one of them is long, convert the other to long
• Otherwise, convert both into int
• When value is assigned to a variable of differing types:
• Widening (Promotion):
• Value has a smaller range compared to the variable • Converted automatically
• Narrowing (Demotion):
• Value has a larger range compared to the variable
Conversion mistake
double d; int i;
i = 31415; d = i / 10000;
What’s the mistake? How do you correct it?
Type casting
double d; int i;
d = 3.14159;
i = (int)d; // i is assigned 3
The (int)d expression is known as type casting Syntax:
(datatype) value Effect:
value is converted explicitly to the data type stated if possible.
Q: What is assigned to i if d contains 3.987 instead?
Operator Type Category Precedence
Unary postfix expr++
expr--prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive +
-Shift shift << >> >>>
(System.out.println(Integer.toBinaryString(2 << 11));)
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? : (result = testCondition ? value1 : value2)
PROBLEM: FAHRENHEIT TO
CELSIUS
•
Write a simple Java program Temperature.Java:
• To convert a temperature reading in Fahrenheit, a real number, to
Celsius degree using the following formula:
• Print out the result
•
For the time being, you can hard code a value for the
• public class Temperature {
• public static void main(String[] args) {
• double fahrenheit, celsius;
• fahrenheit = 123.5;
• celsius = (5.0/9) * (fahrenheit – 32);
• System.out.println("Celsius: " + celsius);
• }
• }
SOLUTION: FAHRENHEIT TO
CELSIUS
• Notes:
• 5.0/9 is necessary to get the correct result (what will 5/9 give?)
• “+” in the printing statement
• Concatenate operator, to combine strings into a single string • Variable values will be converted to string automatically
• There is another printing statement, System.out.print(), which does not include newline at the end of line
Temperature.java
• Compare with C:
• printf("Celsius: %f\n", celsius);
• Output:
• Celsius:
Writing Output: The Standard Output
•
System.out is the predefined output device
• Refers to the monitor/screen of your computer
SYNTAX
//Functionality provided
System.out.print( output_string );
System.out.println( output_string );
System.out.printf( format_string, [items] );
System.out.print("ABC"); System.out.println("DEF"); System.out.println("GHI");
System.out.printf("Very C-like %.3f\n", 3.14159);
Output:
ABCDEF GHI
WRITING OUTPUT: printf()
System.out.printf(“%7.5 f”, Math.PI)
format
string number to print
field width precision
conversion code
Type Code Typical literal Sample format strings
Converted string values for output
int d 512 “%14d” “ 512”
“%-14d” “512 “
double f 1595.168001075 4388
“%14.2f” “ 1595.17”
e “%.7f” “1595.1680011”
“%14.4e” “ 1.5952e+03”
String s “Hello, World” “%14s” “ Hello, World”
“%-14s” “Hello, World “
%-14.5s” “Hello “
CLASS ACTIVITY
PROBLEM: Approximating PI
One way to calculate the PI (π) constant:
Write ApproximatePI.java to:
1.
Ask the user for the number of terms to use for
approximation
2.
Calculate π with the given number of terms
import java.util.*; // using * in import statement
public class ApproximatePI {
public static void main(String[] args) {
int nTerms, sign = 1, denom = 1; double pi = 0.0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: "); nTerms = sc.nextInt();
for (int i = 0; i < nTerms; i++) { pi += 4.0 / denom * sign; sign *= -1;
denom += 2; }
System.out.printf("PI = %.6f\n", pi); }
} ApproximatePI.java
ESCAPE SEQUENCES
Escape
Meaning
\n
New line
\t
Tab
\b
Backspace
\r
Carriage return
\\
Backslash
\'
Single quotation mark
NOTE:
The "expression" in the parentheses for an if statement
or loop
To conditionally execute more than one statement, you must create a
compound statement (block) by enclosing the statements in braces ( this is true for loops as well ):
The "expression" and “int-constant” are usually type int or char or String such as “good”:
Use the break keyword to exit the structure (avoid “falling through” other cases).
Use the default keyword to provide a default case if none of the case expressions match .
int [] scores = {85, 92, 76, 66, 94}; //collection is the array scores for ( int number : scores ) //parameter is the variable number System.out.println(number);
Write a java program to roll a die for 1000 times and calculate how many times each face appeared?
public class Die0 {
public static final int N = 1000;
public static void main(String[] args) {
Random rand = new Random();
int d1 = 0, d2 = 0, d3 = 0, d4 = 0, d5 = 0, d6 = 0; for (int k = 0; k < N; k++) {
int roll = rand.nextInt(6)+1; if (roll == 1) d1++;
else if (roll == 2) d2++; else if (roll == 3) d3++; else if (roll == 4) d4++; else if (roll == 5) d5++;
else if (roll == 6) d6++; }
System.out.println("Rolls: " + N + “\n 1: " + d1 + “\n 2: " + d2 + “\n 3: " + d3 + “\n 4: " + d4 + “\n 5: " + d5 +
“\n 6: " + d6); } }
ROLLING A DIE (Using if-else)
Write a java program to roll a die for 1000 times and calculate how many times each face appeared?
public class Die1 {
public static final int N = 1000;
public static void main(String[] args) {
Random rand = new Random();
int d1 = 0, d2 = 0, d3 = 0, d4 = 0, d5 = 0, d6 = 0; for (int k = 0; k < N; k++) {
int roll = rand.nextInt(6)+1; switch(roll){
case 1: d1++; break; case 2: d2++; break; case 3: d3++; break; case 4: d4++; break; case 5: d5++; break; case 6: d6++; break; }
System.out.println("Rolls: " + N + “\n 1: " + d1 + “\n 2: " + d2 + “\n 3: " + d3 + “\n 4: " + d4 + “\n 5: " + d5 + “\n 6: " + d6);
}} OUTPUT: Rolls: 1000 1: 172 2: 153 3: 168 4: 175 5: 174 6: 158
THE MATH CLASS
•
Package: java.lang (default)
•
Some useful
Math
methods:
• Math.pow() – To the power of • Math.sqrt() – The square root
• Math.abs() – Outputs only positive numbers
• Math.random() – Returns a double value with a positive sign, greater
than or equal to 0.0 and less than 1.0.
• Math.round() – Rounds up numbers
• Math.ceil() – Outputs the smallest number • Math.floor() – Outputs the largest number
HOW TO USE THE MATH CLASS
• You must include the class name Math each time you wish to use the
Math Class
• Example;
System.out.println(Math.pow(2,8));
Indicating you wish to output something
Calling the Math Class
Calling the function power
The
Math
class: Demo
// To find the area of the largest circle inscribed // inside a square, given the area of the square.
import java.util.*;
public class TestMath {
public static void main(String[] args) { Scanner sc = new Scanner(System.in);
System.out.print("Enter area of a square: ");
double areaSquare = sc.nextDouble();
double radius = Math.sqrt(areaSquare)/2;
double areaCircle = Math.PI * Math.pow(radius, 2); System.out.printf("Area of circle = %.4f\n",
areaCircle); }
}
TestMath.java
FUNCTIONS / METHODS
•
A program that provides some functionality can be long and
contains many statements
•
A method groups a sequence of statements and should
provide a well-defined, easy-to-understand functionality
• a method takes input, performs actions, and produces output
•
A class contains data declarations (static and instance
variables) and method declarations (behaviors)
int month; int year class Month
Data declarations
METHOD DECLARATION: HEADER
A method declaration begins with a
method header
method name
return type
parameter list
The parameter list specifies the type and name of each parameter
The name of a parameter in the method declaration is called a formal argument
class MyClass
{
static int min ( int num1, int num2 ) …
METHOD DECLARATION: BODY
The header is followed by the
method body:
static int min(int num1, int num2) {
int minValue = num1 < num2 ? num1 : num2; return minValue;
}
class MyClass {
…
…
The
return
Statement
•
The
return type
of a method indicates the type of value that the
method sends back to the calling location
•
A method that does not return a value has a
void
return type
CALLING A METHOD
•
Each time a method is called, the values of the
actual
arguments
in the invocation are assigned to the
formal
arguments
static int min (int num1, int num2)
{
int minValue = (num1 < num2 ? num1 : num2); return minValue;
}
•
In Java, C++-like function is known as
static/class method
• Denoted by the “static” keyword before return data type
• Another type of method, known as instance method will be covered later
Factorial.java public class Factorial {
// Returns n!
// Pre-cond: n >= 0
public static int factorial (int n) { if (n == 0) return 1;
else return n * factorial(n-1); }
public static void main(String[] args) {
int n = 5; // You can change it to interactive input
System.out.printf("Factorial(%d) = %d\n", n, factorial(n));
} }
TWO TYPES OF
PARAMETER PASSING
If a modification of the
formal argument
has
no
effect
on the
actual argument
,
– it is
call by value
If a modification of the
formal argument
can change
the value of the
actual argument
,
Call-By-Reference in Java
• Depend on the type of the formal argument
• If a formal argument is a primitive data type, a modification on the
formal argument has no effect on the actual argument
• this is call by value, e.g. num1 = min(2, 3);
• num2 = min(x, y);
• This is because primitive data types variables contain their values, and
procedure call trigger an assignment:
• <formal argument> = <actual argument>
int x = 2; int y = 3; int num = min (x, y); …
static int num( int num1, int num2) { … }
int x = 2; int y = 3;
Call-By-Reference in Java
• If a formal argument is not a primitive data type, an operation on the
formal argument can change the actual argument
• this is call by reference
• This is because variables of object type contain pointers to the data that
represents the object
• Since procedure call triggers an assignment
• <formal argument> = <actual argument>
• it is the pointer that is copied, not the object itself!
MyClass x = new MyClass(); MyClass y = new MyClass(); MyClass.swap( x, y);
…
static void swap( MyClass x1, MyClass x2)
{ … }
x = new MC(); y = new MC(); x1 = x;
There can be various types of methods (behavior declarations)
• access methods : read or display states (or those that can be derived)
• predicate methods : test the truth of some conditions
• action methods, e.g., print
• constructors: a special type of methods
• they have the same name as the class
• there may be more then one constructor per class (overloaded constructors)
• they do not return any value
• it has no return type, not even void
• they initialize objects of the class, using the new construct:
• e.g. m1 = new Month();
• you do not have to define a constructor
A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscripted variable or a one-dimensional array.
Creating an Array
Like any other variables, arrays must be declared and created in
the computer memory before they are used.
Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
1. DECLARE AN ARRAY
VARIABLE
Arrays in java can be declared in two ways:
i. type arrayname [ ];
ii. type[ ]arrayname;
Example:
int number[]; float slaray[]; float[] marks;
when creating an array, each element of the array receives a default value
zero (for numeric types) ,false for boolean and null for references (any
2. CREATION OF ARRAYS
After declaring an array, we need to create it in the memory. Because an array is an object, you create it by using the new keyword as follows:
arrayname =new type[ size]; Example:
number = new int[5]; marks = new float[7];
It is also possible to combine the above to steps , declaration and creation,
into on statement as follows:
type arrayname =new type[ size];
3. INITIALIZATION OF ARRAYS (1/3)
Each element of an array needs to be assigned a value; this process is known as initialization.
Initialization of an array is done using the array subscripts as follows:
arrayname [subscript] = Value; Example:
number[0] = 23; number[2] = 40;
Unlike C, java protects arrays from overruns and underruns.
3. INITIALIZATION OF ARRAYS (2/3)
• Java generates an ArrayIndexOutOfBoundsException when there isunderrun or overrun.
• The Java interpreter checks array indices to ensure that they are valid
during execution.
• Arrays can also be initialized automatically in the same way as the
ordinary variables when they are declared, as shown below:
type arrayname [] = {list of Values};
Example:
3. INITIALIZATION OF ARRAYS (3/3)
It is also possible to assign an array object to another array object.
Example:
int array1[]= {35,40,23,67,49};
int array2[];
array2= array1;
array2 is referencing the array1. Any change in Array2 will effect the array1. For Example Array2[0]=44;
System.out.println(“array1[0] =”+ array1[0]); // out will be array1 = 44
Array Length
• In Java, all arrays store the allocated size in a variable named length.
• We can access the length of the array array1using array1.length. Example:
■
Write a java program to roll a die for 1000 times and calculate how
many times each face appeared?
public class Die2 {
public static final int N = 1000;
public static void main(String[] args) { Random rand = new Random();
int[] d = new int[7];
for (int k = 1; k < N; k++) int roll = rand.nextInt(6)+1; d[roll]++;
}
System.out.println("Rolls: " + N); for (int i = 1; i < 7; i++)
System.out.println(i + ": " + d[i]); System.out.println();
} }
ROLLING A DIE (ARRAYS)
TWO DIMENSIONAL ARRAYS
• A 2-dimensional array can be thought of as a grid (or matrix) of values.
• Each element of the 2-D array is accessed by providing two indexes: a
row index and a column index
• A 2-D array is actually just an array of arrays.
• A multidimensional array with the same number of columns in every row
can be created with an array creation expression:
Example:
TWO DIMENSIONAL ARRAYS
• Like the one-dimensional arrays, two-dimensional arrays may be
initialized by following their declaration with a list of initial values
enclosed in braces. For example,
int myarray[2][3]= {0,0,0,1,1,1};
or
int myarray[][]= {{0,0,0},{1,1,1}};
• We can refer to a value stored in a two-dimensional array by using
indexes for both the column and row of the corresponding element. For
Example,
class MulTable{
final static int ROWS=12; final static int COLUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [ROWS][COLUMNS];
int i,j;
System.out.print("MULTIPLICATION TABLE");
System.out.println(" "); for (i=1; i<ROWS; i++){
for (j=1; j<COLUMNS; j++){ pro [i][j]= i * j;
System.out.printf(“%4d"+ pro[i][j]);
}
System.out.println(" " ); }
} }
MULTIPLICATION TABLE
1 2 3 4 5 6 7 8 9 10 11 2 4 6 8 10 12 14 16 18 20 22 3 6 9 12 15 18 21 24 27 30 33 4 8 12 16 20 24 28 32 36 40 44 5 10 15 20 25 30 35 40 45 50 55 6 12 18 24 30 36 42 48 54 60 66 7 14 21 28 35 42 49 56 63 70 77 8 16 24 32 40 48 56 64 72 80 88 9 18 27 36 45 54 63 72 81 90 99 10 20 30 40 50 60 70 80 90 100 110 11 22 33 44 55 66 77 88 99 110 121
MulTable.java
VARIABLE SIZE ARRAYS
• Java treats multidimensional array as “array of arrays”.• It is possible to declare a two-dimensional array as follows:
• int x[][]= new int[3][];
• x[0] = new int[2];
• x[1] = new int[4];
• x[2] = new int[3];
• This statement creates a two-dimensional array having different length
for each row as shown below:
X[0]
X[1]
X[2]
x[0][1]
x[2][2]
ARRAYS LENGTH
•
All arrays have a public field named
length
which holds
the number of elements in the array.
•
Given this declaration: int x[][][]= new int[7][5][2] ;
•
x.length
is the number of elements in the array in the first
dimension.
•
x[m].length
is the number of elements for a specific array in
the second dimension.
•
x[m][n].length
is the number of elements for a specific array
ArrayList (1/3)
• The array is a data structure that is fixed in size,
once created, the size can not be changed anymore.
• ArrayList created to address the problems faced by
Array in determining its size because it is a dynamic
ArrayList
• Declaration:
ArrayList Methods (2/3)
The following functions are often used in class Array List:
– add (element) add elements to the list
– clear () removes all elements in the list
– clone () returns the copied object in the list
– containts(element) search for elements that exist in
the list
– get (index) take element in a particular index in the list
– isEmpty () check whether the list is empty or not
– remove (index) removes the element designated in
the list
– size () number of elements in the list
Vector (1/3)
1.
Vector is another collection class in the package java.util.
2.
Vector is similar to ArrayList, except that it is
synchronized.
3.
Synchronized means that Vector is thread-safe. We will
leave out the discussion of thread-safe from this module.
4.
However, Vector is slower than ArrayList.
5.
Declaration
Vector Methods(2/3)
The following functions are often used in the Vector class:
• addElement (element) add elements to the final sequence of the vector • capacity () Returns capacity vector
• clone () returns the copied object in the vector
• containts (element) search for existing element in the vector • copyInto (element []) copy specific elements to the array • ElementAt (index) take the elements of the designated index
• insertElementAt (element, index) add an element to the designated index.
• isEmpty () check whether the vector is empty or not
• remove (index) removes the element designated in the vector • size () number of elements in the vector