Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

Bahria University Karachi Campus

CSC- 210
Object Oriented Programming

Lecturer
Sameena Javaid

https://sites.google.com/site/sameenajavaidcs
Bahria University Karachi Campus

LECTURE 2
JAVA FUNDAMENTALS

OUTLINE

• Basic elements of Java


• I/O statements in Java
• Selection statements in Java
• Repetition statements in Java
• Arrays in Java
• Methods in Java
Bahria University Karachi Campus

BASICS OF JAVA
Bahria University Karachi Campus

PROGRAM TEMPLATE FOR SIMPLE C++ PROGRAM

Header files
Include a sequence
of header files.

Global Variables &


Function Declaration
Give a descriptive
name to the main class.
Return Type
Main Method Name
Parameter

int main (void){

Method Body
Include a sequence of
instructions.
return 0;
}
Bahria University Karachi Campus

Program Template for simple JAVA Program

Import Statements
Include a sequence
of import statements.

Class Name
Give a descriptive
public class {
name to the main class.

Return Type
Modifier Method Name
Modifier Parameter

public static void main (String[] args){

Method Body
Include a sequence of
instructions.
}
}
Bahria University Karachi Campus

PACKAGES
• 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.
Bahria University Karachi Campus

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 to one another yet still restrict access
for types outside the package.
Bahria University Karachi Campus

ORGANIZING CLASSES WITH PACKAGE


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.
package bahria.academics;
class Student { }

package bahria.academics;
class Lecturer { }
Bahria University Karachi Campus

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{ }
• In the preceding code snippet, the PackageDemo class
belongs to test package.
Bahria University Karachi Campus

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{
}
• In the preceding code snippet, the Demo class can
access the classes inside test package.
Bahria University Karachi Campus

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 modeling real world objects which
have similar attributes
Bahria University Karachi Campus

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!");
}
}
Bahria University Karachi Campus

Hello World in C++ and JAVA

Hello.cpp HelloWorld.java

#include <iostream>
using namespace std;
public class HelloWorld {
int main() { public static void main(String [] args) {

cout << "Hello World!" << System.out.println(“Hello World!”);


endl;
} //main end
return 0;
} //main end } //class end

In java Class Name and FileName should be same as in HelloWorld.java


Bahria University Karachi Campus

Keyboard Input in C++ and JAVA


input.cpp Input.java

#include <iostream> import java.util.Scanner;


using namespace std;
public class Input {
int main() { public static void main(String [] args) {
int a,b; int a,b;
Scanner input = new
cout << “Enter the values of a and b" Scanner(System.in);
<< endl; System.out.println(“Enter the values of a and
cin>>a>>b; b”);
cout<<“a =“<<a<<“b=“<<b; a = input.nextInt();
return 0; b = input.nextInt();
} System.out.println(“a =“+a+”b=“+b);
} //main end
//main end }//class end
Bahria University Karachi Campus

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);
}
}
Bahria University Karachi Campus

Sample Program (cont…)


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
Bahria University Karachi Campus

Sample Program (cont…)


Import is used to include
import java.util.Scanner; external packages in your code
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);
}
}
Bahria University Karachi Campus

Sample Program (cont…)


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.
Bahria University Karachi Campus

Sample Program (cont…)

import java.util.Scanner;
class MyClass {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
int num1;
new reserved word is
System.out.println(“Enter 1stused
Value: "); an
to create
num1=input.nextInt(); object of the class…
System.out.println(“Number Entered = " +
num1);
}
}
Bahria University Karachi Campus

Sample Program (cont…)

System.in is an
import java.util.Scanner; input stream
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);
}
}
Bahria University Karachi Campus

Sample Program (cont…)


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.
Bahria University Karachi Campus

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

nextLine () reads an entire line of keyboard input


Bahria University Karachi Campus

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: int countDays, $total, _total, total5;
double priceOfItem;

• Constant is used to represent a fixed value


• Eg: public static final int PASSING_MARK = 50;
• Keyword final indicates that the value cannot change
Bahria University Karachi Campus

Guidelines on how to name classes,


variables, and constants:
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
Bahria University Karachi Campus

COMMENTS
Java supports three types of comments:
Delimeter Use
// Used for commenting a single line

/* ————— */ …………………..
Used for commenting a block of code
/** —————*/ ………………*/
Used for commenting a block of code
Bahria University Karachi Campus

DATA TYPES
Type Size Range Default
Name (#bytes) Value
byte 1 –128 to 127 0
Data Types

short 2 –32,768 to 32,767 0


Integer

int 4 –2,147,483,648 to 2,147,483,647 0


long 8 -9,223,372,036,854,775,808 to 0L
9,223,372,036,854,775,807
float 4 Negative: -3.4028235E+38 to -1.4E- 0.0f
Point Data
Floating-

45
Types

Positive: 1.4E-45 to 3.4028235E+38


double 8 Negative: -1.7976931348623157E+308 to 0.0d
-4.9E-324
Positive: 4.9E-324 to
1.7976931348623157E+308
char 2 '\u0000‘ to '\uffff' '\u0000'

String - 2,147,483,647 characters null

boolean 1 bit true/false false


Bahria University Karachi Campus

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
• Explicit type casting is needed
Bahria University Karachi Campus

TYPE CASTING
Conversion mistake
double d;
int i; What’s the mistake?
How do you correct it?
i = 31415;
d = i / 10000;

Q: What is assigned to d?
The (int)d expression is
Type casting known as type casting

double d; Syntax:
int i;
(datatype) value
d = 3.14159;
i = (int)d; // i is assigned 3 Effect:
value is converted explicitly
Q: What is assigned to i if d contains to the data type stated if
3.987 instead? possible.
Bahria University Karachi Campus

OPERATORS IN JAVA
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)
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Bahria University Karachi Campus

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:

5
celsius   ( fahrenheit  32)
9
• Print out the result

• For the time being, you can hard code a value for
the temperature in Fahrenheit instead of reading it
from user
Bahria University Karachi Campus

SOLUTION: FAHRENHEIT TO CELSIUS


• public class Temperature { Temperature.java
• public static void main(String[] args) {
• double fahrenheit, celsius; • Output:
• Celsius:
• fahrenheit = 123.5;
50.833333333333336
• celsius = (5.0/9) * (fahrenheit – 32);
• System.out.println("Celsius: " +
celsius);
• }
• } • Compare • printf("Celsius: %f\n",
with C: 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
Bahria University Karachi Campus

Writing Output: The Standard Output


• System.out is the predefined output device
• Refers to the monitor/screen of your computer

//Functionality provided
System.out.print( output_string );
SYNTAX

System.out.println( output_string );

System.out.printf( format_string, [items] );

Output:
System.out.print("ABC"); ABCDEF
System.out.println("DEF"); GHI
System.out.println("GHI"); Very C-like 3.142

System.out.printf("Very C-like %.3f\n", 3.14159);


Bahria University Karachi Campus

WRITING OUTPUT: printf()


format number to
string print

System.out.printf(“%7.5 f”, Math.PI)

conversion code
field width precision

Anatomy of a formatted print statement


Bahria University Karachi Campus

WRITING OUTPUT: printf()


Type Code Typical literal Sample Converted string
format values for output
strings
int d 512 “%14d” “ 512”
“%-14d” “512 “

double f 1595.168001075 “%14.2f” “ 1595.17”


e 4388 “%.7f” “1595.1680011”
“%14.4e” “ 1.5952e+03”

String s “Hello, World” “%14s” “ Hello, World”


“%-14s” “Hello, World “
%-14.5s” “Hello “
Bahria University Karachi Campus

CLASS ACTIVITY
PROBLEM: Approximating PI
One way to calculate the PI () constant:

4 4 4 4 4
       .........
1 3 5 7 9
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
3. Output the approximation in 6 decimal places
Bahria University Karachi Campus

CLASS ACTIVITY
SOLUTION: Approximating PI
import java.util.*; // using * in import statement

public class ApproximatePI {

public static void main(String[] args) {

4 4 4 4 4
int nTerms, sign = 1, denom = 1;
double pi = 0.0;
       .........
1 3 5 7 9
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
Bahria University Karachi Campus

ESCAPE SEQUENCES
Escape Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\\ Backslash
\' Single quotation mark
\" Double quotation mark
Bahria University Karachi Campus

SELECTION STATEMENTS (1/3)


NOTE:
The "expression" in
the parentheses for
an
if statement
or
loop
is often also
referred to as a
"condition"
Bahria University Karachi Campus

SELECTION STATEMENTS (2/3)


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 ):
Bahria University Karachi Campus

SELECTION STATEMENTS (3/3)

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 .
Bahria University Karachi Campus

REPETITION STATEMENTS (1/2)


Bahria University Karachi Campus

REPETITION STATEMENTS (2/2)

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);
Bahria University Karachi Campus

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 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; OUTPUT:
for (int k = 0; k < N; k++) { Rolls: 1000
int roll = rand.nextInt(6)+1;
if (roll == 1) d1++;
1: 152
else if (roll == 2) d2++; 2: 173
else if (roll == 3) d3++; 3: 174
else if (roll == 4) d4++; 4: 161
else if (roll == 5) d5++; 5: 167
else if (roll == 6) d6++; 6: 173
}

System.out.println("Rolls: " + N + “\n 1: " + d1 + “\n 2: " +


d2 + “\n 3: " + d3 + “\n 4: " + d4 + “\n 5: " + d5 +
“\n 6: " + d6);
} }
Bahria University Karachi Campus

ROLLING A DIE (Using switch)


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; OUTPUT:
for (int k = 0; k < N; k++) { Rolls: 1000
int roll = rand.nextInt(6)+1; 1: 172
switch(roll){
case 1: d1++; break;
2: 153
case 2: d2++; break; 3: 168
case 3: d3++; break; 4: 175
case 4: d4++; break; 5: 174
case 5: d5++; break; 6: 158
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);
}}
Bahria University Karachi Campus

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
• Math.min() – Return minimum of two numbers
• Math.max() – Return maximum of two numbers
Bahria University Karachi Campus

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 Calling the Math Calling the Arguments


wish to output Class function (will work
something power out 28)
Bahria University Karachi Campus

The Math class: Demo


// To find the area of the largest circle inscribed TestMath.java
// inside a square, given the area of the square.
import java.util.*;

public class TestMath {


radius
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);
}
}
Bahria University Karachi Campus

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

• In Java, each method is defined within specific


class
Bahria University Karachi Campus

• A class contains data declarations (static and


instance variables) and method declarations
(behaviors)
class Month
int month;
int year Data declarations

Method declarations
Bahria University Karachi Campus

METHOD DECLARATION: HEADER


A method declaration begins with a method header
class MyClass
{ …
static int min ( int num1, int num2 )

method parameter list


name
The parameter list specifies the type
return and name of each parameter
type
The name of a parameter in the method
properties declaration is called a formal argument
Bahria University Karachi Campus

METHOD DECLARATION: BODY


The header is followed by the method body:
class MyClass
{

static int min(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}


}
Bahria University Karachi Campus

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

• The return statement specifies the value that will be


returned
• Its expression must conform to the return type
Bahria University Karachi Campus

CALLING A METHOD

• Each time a method is called, the values of the


actual arguments in the invocation are assigned
to the formal arguments
int num = min (2, 3);

static int min (int num1, int num2)


{
int minValue = (num1 < num2 ? num1 : num2);
return minValue;
}
Bahria University Karachi Campus

FUNCTION WITH A NEW NAME


• 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
public class Factorial {
// Returns n! Factorial.java
// Pre-cond: n >= 0 If n is too
public static int factorial (int n) { big, say 40,
if (n == 0) return 1;
what will
else return n * factorial(n-1);
} happen? Why?

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));
}
}
Bahria University Karachi Campus

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,
– it is call by reference
Bahria University Karachi Campus

Call-By-Value and
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 x = 2;


int num = min (x, y); int y = 3;
… int num1 = x;
static int num( int num1, int num2) int num2 = y;
{ … } { … }
Bahria University Karachi Campus
Call-By-Value and
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(); x = new MC();
MyClass y = new MyClass(); y = new MC();
MyClass.swap( x, y);
x1 = x;

static void swap( MyClass x1, MyClass x2) x2 = y;
{ … } { … }
Bahria University Karachi Campus

METHOD TYPES
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
• the value of the state variables have default value
Bahria University Karachi Campus

ARRAYS
Bahria University Karachi Campus

ONE DIMENSIONAL ARRAYS


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.
Bahria University Karachi Campus

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 non primitive types).
Bahria University Karachi Campus

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];

Example: int num[] = new int[10];


Bahria University Karachi Campus

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.

Trying to access an array beyond its boundaries will generate


an error.
Bahria University Karachi Campus

3. INITIALIZATION OF ARRAYS (2/3)


• Java generates an ArrayIndexOutOfBoundsException when
there is underrun 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:
int number[]= {35,40,23,67,49};
Bahria University Karachi Campus

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:
int size = array1.length;
Bahria University Karachi Campus

ROLLING A DIE (ARRAYS)


 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; OUTPUT:
d[roll]++; Rolls: 1000
} 1: 158
System.out.println("Rolls: " + N); 2: 169
for (int i = 1; i < 7; i++) 3: 160
System.out.println(i + ": " + d[i]); 4: 181
System.out.println(); 5: 170
} 6: 161
}
Bahria University Karachi Campus

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:
int myarray[][]= new int[3][4];
Bahria University Karachi Campus

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,
int value = myarray[1][2];
Bahria University Karachi Campus

//Application of two-dimensional Array MulTable.java


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++){
Output
pro [i][j]= i * j;
System.out.printf(“%4d"+ MULTIPLICATION TABLE
1 2 3 4 5 6 7 8 9 10 11
pro[i][j]);
2 4 6 8 10 12 14 16 18 20 22
} 3 6 9 12 15 18 21 24 27 30 33
System.out.println(" " ); 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
Bahria University Karachi Campus

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][1]

X[0]

X[1]

X[2] x[1][3]

x[2][2]
Bahria University Karachi Campus

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 in the third dimension.
Bahria University Karachi Campus

ARRAYLIST & VECTOR


Bahria University Karachi Campus

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 al = new ArrayList();


Bahria University Karachi Campus

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
– set (index, element) fill an element in the list in
accordance with the designated position.
Bahria University Karachi Campus

ArrayList Example (3/3)


Bahria University Karachi Campus

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 v = new Vector();
Bahria University Karachi Campus

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
• set (index, element)  fill an element in the vector
corresponding to the designated position.
Bahria University Karachi Campus

Vector Example(3/3)
Bahria University Karachi Campus

You might also like