The Java Programming Language: Topics

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

Topics

About Java

Program Structure

Processing a Java Program

Java Essentials

Printing Information
The Java
Accepting Data
Programming
Control Structures
Language
Strings and Arrays

Methods

Return
Topics

Variables

Data Types

Identifiers

Constants Java
Operators & Expressions Essentials
Return
Topics

About Control Statements

if() Statement

switch() Statement

for() Statement
Control
while() Statement Statements
do while() statement

Return
Topics

Introduction

Creating/Using Methods

Parts of a Method

Passing Values to Methods


Methods
Related Examples

Return
Topics

About Arrays

One-Dimensional Arrays

Two-Dimensional Arrays

Return
Dealing
with
Arrays
ABOUT JAVA
What is Java ?
Java was developed by Sun Microsystems as an object-
oriented language for general-purpose business applications
and for interactive Web-based Internet applications.
Advantages of Using Java :
1. Security Features - the ability to hide details and protect
data and code.
2. Architecturally Neutral - Java can be used to write
programs that will run on any platform ( operating system ).
It can run on a wide variety of computers because it does
not execute instructions on a computer directly. Instead
Java run on a hypothetical computer known as the Java
Virtual Machine ( JVM)
ABOUT JAVA
3. Can be used to create programming solutions for wide variety
of applications.

Softwares Needed to Create and Process Java Programs:


1. Editor programs like DOS’ edit.com, Window’s Notepad.exe.
or a specialized text editor like Notepad++.
2. Compiler ( Java SDK‘s javac.exe ).
This software converts Java programs into machine code
or bytecode. Also checks syntax and semantic errors.
3. Interpreter ( Java SDK’s java.exe).
This sofware executes or runs successfully compiled Java
programs.
PROGRAM STRUCTURE
Structure of a Typical Java Program
// Import Section
import name_of_class_or_package;
// Class Declaration Section
public class class_name {
public static void main ( String[] args ) {
statement;
statement;
…..
statement;
}
}
PROGRAM STRUCTURE
where:
import name_of_class a statement that causes the specified
class to be compiled together with the main program or class.

public class class_name creates the specified class by


specifying the name of the class.

public static void main ( String[] args ) specifies the class’ main
program. Must be given if class is a stand-alone type of program.

statement is any valid Java instruction.


{} symbols which denote the start and end of a class or main().
// symbols which denote that text after these symbols are to be
treated as comments or remarks.
/* */ similar to // but used when specifying multiple line of comments
; symbol which denote the end of a particular statement.
PROGRAM STRUCTURE
Example of a Typical Java Program
/* =================================
Purpose : Prints Lines of Text on the screen
Author : R. Buesing
Date Created : June 27, 2011
Filename: PrintText.java
==================================*/
// Import Section
import java.io.*;
// Create Class
public class PrintText {
public static void main ( String[] args ) {
System.out.println(“Welcome to “);
System.out.println(“College of”);
System.out.println(“Computer Studies”);
}
}
JAVA ESSENTIALS
Identifiers are names given to variables, methods , classes,
arrays, and other user-defined objects.

Rules for giving identifiers


1. A Java identifier must begin with a letter, an underscore, or a
dollar sign.
2. It must contain only letters, digits, underscores, or dollar signs.
3. It cannot be a Java reserved word such as public or class.
4. In Java, lowercase and uppercase letters are treated
differently. Therefore, count, Count, and COUNT, are three
different identifiers.
5. A Java identifier must be descriptive.
JAVA ESSENTIALS
Examples of valid Java identifiers:
empName
PrintText
calcPay
empNo
num_1
_ratePerHr

Examples of Invalid Java identifiers:


Rate Per Hour must not contain spaces
1_num cannot start with a number
int int is a Java reserved word
emp*No. Must not contain * and .
print-Names Hypen (-) is not a legal character
JAVA ESSENTIALS
Rules for Giving Class Names
Giving name to a class involved the same set of rules but
conventional rule suggests that the first letter of each word in a
class name must start with a capital letter .
Example:
public class PrintText {
………….
}

Rules for Naming Variables and Methos


Conventional rule suggests that the first letter of the starting
word of a variable or method’s name should start with a
lowercase letter while starting letter of each succeeding words
must begin with an uppercase letter.
JAVA ESSENTIALS

Example:
public calcPay() {
float empRate;
String empName;
…..
}
JAVA ESSENTIALS
Variable is a memory location that is assigned to a particular
name. It is used as a temporary storage of data. Contents of
variable may change during program execution.

Common Uses of Variables:


• To store data that is accepted from an input device like
keyboard .
• To hold the intermediate results of processing.
• To store data that are frequently used by the program.

Note : All Java variables must be declared before they are used.
JAVA ESSENTIALS
Declaring a Variable:
The general format for declaring a variable is:
data_type variable_list;

Where:
data_type must be any valid Java data type
variable_list is one or more identifiers separated by comma.

Examples:
int n1, n2, sum = 0;
float profit = 5000, sales, income;
double population;
char mi, answer;
boolean status;
JAVA ESSENTIALS
Assigning Value to a Variable:
• During declaration
Example:
int n1 = 10 ;
final float grade = 1.75f ; // constant variable
char middle = 'A‘ ;
• Using Assignment statement
Example:
int n1;
float grade;
char middle;
n1 = 10; grade = 1.75F; middle = 'A';
JAVA ESSENTIALS
• Using input statement
Example:
String answer ;
Scanner in = new Scanner(System.in);
System.out.print(“Enter your answer : “);
answer = in.nextLine();

Local Variables - these are variables that are declared inside a


particular method or block, Local variables can only be referenced
by statements that are inside the method or block in which they are
declared.
Example: void calc() {
int n1, n2, sum;
n1 = 5; n2 = 10; sum = n1+n2;
}
JAVA ESSENTIALS

Constants in Java refer to fixed values that may not be altered by


the program. They can be of any data type as shown below:

Data type Examples


char 'a' , ‘=' , '9‘
byte 5, 10, 100, -50, -250
short 500, -123, 5556, 1000
int 1000000 , -5555123 , 2221000 , -23412315
float 123.23f, -500.25F, 10000.01F
double 123.23 , 12312333 , -0.9876324
string "abc" , "text" , "a"
boolean true, false
JAVA ESSENTIALS
Backslash constants are constants that have special meaning to
Java .
Code Meaning
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote character
\0 Null
\\ Backslash
\v Vertical tab
\a alert
JAVA ESSENTIALS
Java is very rich in built-in operators. An operator is a symbol that
tells the compiler to perform specific mathematical or logical
operations.

Types of Operator:
1. Arithmetic operators The precedence of arithmetic
- Subtraction operators
highest ++ --
+ Addition - ( unary minus )
* Multiplication */%
/ Division lowest +-
% Modulus division
-- Decrement by 1
++ Increment by 1
JAVA ESSENTIALS
2. Relational Operators are symbols used when building
a condition.
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal
3. Logical Operators are symbols used when combining
two or more conditions.
&& AND ( all conditions must be true )
|| OR ( at least one condition must be true )
! NOT ( reverses result of operation )
JAVA ESSENTIALS
4. Assignment ( = ) is a symbol used when assigning a
value to a variable or an array.
Expressions
Operators, constants, and variables are the constituents of
expressions. An expression in Java is any valid combination of
those pieces.
Example:
n1+n2
n1 > n2
( prelim + midterm + finals ) / 3
getGross() * .15f + basetax
JAVA ESSENTIALS
Data Type defines the set of values that a variable can store, along
with the set of operations that can be performed on that variable.

Types of Data Type


1. Primitives are data types whose state represents a
number, a character, or true or false indicator.

2. Reference types are data types for referencing classes,


arrays, strings, and interfaces.
JAVA ESSENTIALS
8 Primitive Data Types
Data Type Description Keyword
Boolean true or false boolean
Byte 8-bit twos complement integer with values from - 128 to +127 byte
Short Int 16-bit twos complement integer with values ranging from -32,768 to short
+ 32,767
Character 16-bit Unicode characters from \u0000 to \uFFFF. For char
alphanumerics, these are the same as ASCII with high byte set to 0.
Integer 32-bit twos complement integer with values between - int
2,147,483,648 to +2, 147, 483,647.
Long Int 64-bit twos complement integer with values between long
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
Floating-point A 32-bit single precision floating-point numbers float
Double A 64-bit double precision floating-point numbers double
Floating-point
OUTPUT-RELATED INSTRUCTIONS

Printing information on the screen ( console environment )


Using the System class
Format: System.out.println(value);
System.out.print(value);
System.out.printf(“format_code”,value);
where:
System is the name of a class that contains a collection of
objects that can be used to do tasks related to input and
output operations.
out is the name of an object representing the console.
println(), print(), printf() are methods associated with the
object out that can be called to print information on the
screen.
OUTPUT-RELATED INSTRUCTIONS

println() causes the next output to appear on the next line.


printf() can be used to display formatted information on the
screen. “format_code” is a string that may contain
text to be printed or special formatting codes such as
%c, %d, %f, or %s.
Example:
float price = 1500.2156F;
int qty = 5
String desc = “TV”;
System.out.printf(“\nDescription : %s\n”, desc);
System.out.printf(“\nUnit Price : %9.2f”,price);
System.out.printf(“\nQuantity Sold : %d”,qty);
OUTPUT-RELATED INSTRUCTIONS
Example : ( save as Greeting.java ) Note:
The + sign is
public class Greeting { used to concatenate
public static void main ( String [ ] args ) or combine values
that belong to
{ int stdAge = 16; different data types.
float stdHeight = 120.5f ;
String stdName = “Tony Parker”;
System.out.print (“Hi ! I am “);
System.out.println ( stdName);
System.out.printf (“My age is %d years old“, stdAge );
System.out.print (“ and I am “ + stdHeight + “ cm. tall “);
}
}
OUTPUT-RELATED INSTRUCTIONS

Printing information on the screen ( GUI output) Using the


JOptionPane Class
Format:
JOptionPane.showMessageDialog ( parent_window,
message, title, type ) ;
where:
JOptionPane is the name of a class that contains a collection
of objects that can be used to do tasks related to GUI
input and output operations.
showMessageDialog() is a method that can be called to
print information on windows environment ( GUI ).
OUTPUT-RELATED INSTRUCTIONS

parent_window is the name of the frame or parent window


where the request is made.
message is the value to be printed
title is a string which specifies the title of the dialog window.
dialog_type specifies the type of the dialog window,
Possible entries:
• INFORMATION_MESSAGE
• QUESTION_MESSAGE
• ERROR_MESSAGE
• PLAIN_MESSAGE
• WARNING_MESSAGE

.
OUTPUT-RELATED INSTRUCTIONS
Application : ( save as GreetingGUI.java )
// Import Section
import javax.swing.JOptionPane;
public class GreetingGUI {
public static void main ( String [ ] args ) {
int stdAge = 16;
String stdName = “Tony Parker”;
JOption.showMessageDialog( null,
“Hi, I am “ + stdName +
“\nMy age is “ + stdAge,
“Greeting Program”,
JOptionPane.INFORMATION_MESSAGE);
}
}
INPUT-RELATED INSTRUCTIONS
Accepting Data From The Keyboard ( console environment )
Using the Scanner Class

The Scanner class contains a variety of methods that can be used for
accepting data from the keyboard. To access these methods, an object must
be created by using the format specified below.

Scanner variable_name = new Scanner( System.in );


Example: Scanner in = new Scanner ( System.in );

Methods associated with Scanner Class


 nextFloat() - used when accepting floating-point values
 nextInt() – used when accepting integer values
 nextDouble – used when accepting double floating-point values
 nextLine() – used when accepting string values
 next() – used when accepting string values without embedded spaces.
INPUT-RELATED INSTRUCTIONS

Example:

import java.util.Scanner;
public class GetEmployee {
public static void main ( String[] args )
float salary;
int age;
String name;
System.out.print(“Enter Name : “); name = in.nextLine();
System.out.print(“Enter Age: “); age = in.nextInt();
System.out.print(“Enter Salary : “); salary = in.nextFloat();
}
}
INPUT-RELATED INSTRUCTIONS

Accepting Data From The Keyboard Using the JOptionPane


Class’ showInputDialog() and showConfirmDialog() methods

showInputDialog() shows a message box that will prompt the


user to enter a particular string value.
showConfirmDialog() shows a message box that will ask the user to
choose an option. Typical options are YES, NO, and CANCEL option.

Syntax :
variable_name = JOptionPane.showMessageDialog (
parent_window, message, title, dialog_type ) ;

variable_name = JOptionPane.showConfirmDialog (
parent_window, message) ;
INPUT-RELATED INSTRUCTIONS
Example:
import javax.swing.JOptionPane;
public class DataEntry {
public static void main ( String [] args )
String name, strSalary; float salary; int choice;
do {
name = JOptionPane.showInputDialog( null,
"Enter your Name","Data Entry“,
JOptionPane.QUESTION_MESSAGE);
strSalary = JOptionPane.showInputDialog( null,
"Enter your salary","Data Entry",
JOptionPane.QUESTION_MESSAGE);
salary = Float.parseFloat(strSalary);
choice = JOptionPane.showConfirmDialog( null,
“Accept another record ?");
} while ( choice == JOptionPane.YES_OPTION );
}
}
CONTROL-STATEMENTS

Types of Control-Statements
• Conditional statements
• Loop-control statements

Conditional Statements
These are statements that execute statement/s
based on the result of a particular condition.
condition is any comparison between two entities that
belong to the same data type.

Related Java Statements


• if() statement
• switch() statement
.
CONTROL-STATEMENTS

Loop-Control Statements
These are statements that execute statement/s
repeatedly for as long as specific condition is satisfied.

condition is any comparison between two entities that


belong to the same data type.

Related Java Statements


• for() statement
• do while() statement
• while() statement
.
CONTROL-STATEMENTS

if() statement - allows multi-way tests and can be used


for any type of comparison.
Syntax #1:
if ( conditon )
statement; Note:
else This format of if()
statement; statement must be
Example: applied if there
n1 = 5; n2 = 3; high = 0; are two alternatives
if ( n1 > n2 ) flow of action.
high = n1;
else
high = n2;
CONTROL-STATEMENTS
Syntax #2: Example:
if ( conditon1 ) gross = rate * hrs;
statement1; if ( gross > 5000 )
else if ( conditon2 ) tax = .2f * gross;
statement12; else if ( gross > 4000 )
tax = .15f * gross;
else if ( conditon3 )
else if ( gross > 3000 )
statement13; tax = .1f * gross;
else if ( conditon2 ) else if ( gross > 2000 )
statement12; tax = .05f * gross;
……. else if ( gross > 1000 )
else tax = .025f * gross;
statementN; else
tax = 0;
Note: This format of if() statement must be applied if there
are more than two alternatives flow of action.
CONTROL-STATEMENTS

Syntax #3:
if ( conditon ) Note:
statement; This format of if()
Example: statement must be
a) n1 = 5; n2 = 3; high = n1; applied if there is
if ( n2 > n1 ) only one alternative
high = n2; flow of action.

b) gross = rate * hrs; tax = 0;


if ( gross > 1000 )
tax = .1f * gross;
CONTROL-STATEMENTS

switch() statement - also handles multiple alternatives


but unlike if(), this statement can only test for
equality relationship.
Note:
Syntax :
• Type af variable
switch ( variable ) { and constants must
case constant1: statement1; match.
case constant2: statement2; • Type of variable
case constant3: statement3; must be of character
or integer data type
case constant4: statement4;
…………
case constantN: statementN;
default: statement;
}
CONTROL-STATEMENTS
Example:
a) char sexC = ‘F’;
String title = “”;
switch ( sexC ) {
case ‘F’ : title = “Ms. “; break;
case ‘M’ : title = “Mr. “; break;
}
b) int num = 5;
String word = “”;
switch ( num ) {
case 0 : word = “Zero”; break;
case 1 : word = “One”; break;
case 2 : word = “Two”; break;
}
CONTROL-STATEMENTS
for() statement - executes statements repeatedly
based on the content of a numeric variable or
counter.
Note:
Syntax : Use this statement if
for ( initialize; condition; increment ) the number of
statement; repetitions is already
known.
Example:
int counter; sum = 0;
for ( counter = 0; counter < 10; counter ++ ) {
System.out.println(“Number is “ + counter);
sum = sum + counter;
}
System.out.println(“Sum is “ + sum);
CONTROL-STATEMENTS
do while() statement - executes statements repeatedly
based on the results of a particular condition or
comparison.
Syntax :
do {
statement;
} while ( condition ) ;
Example:
int num = 1 ; sum = 0;
do {
System.out.println(“Number is “ + num );
sum = sum + num; num ++;
} while ( num <= 10 );
System.out.println(“Sum is “ + sum);
CONTROL-STATEMENTS
while() statement - executes statements repeatedly based
on the results of a particular condition or comparison.

Syntax :
while ( condition ) {
statement;
}

Example:
int num = 1 ; sum = 0;
while ( num <= 10 ) {
System.out.println(“Number is “ + num );
sum = sum + num; num ++;
}
System.out.println(“Sum is “ + sum);
CONTROL-STATEMENTS
do while() statement - executes statements repeatedly
based on the results of a particular condition or
comparison.
Syntax :
do {
statement;
} while ( condition ) ;
Example:
int num = 1 ; sum = 0;
do {
System.out.println(“Number is “ + num );
sum = sum + num; num ++;
} while ( num <= 10 );
System.out.println(“Sum is “ + sum);
ABOUT ARRAYS
 An array is a set of memory locations represented by a
particular name. Also called subscripted variable.
 Used to store related data in memory.
 Data stored inside an array can be accessed much faster,
and in a more efficient manner.
 Arrays reduce the number of ordinary variables in a
program, resulting to a better and more efficient handling
of memory locations.
 Data stored in an array must belong to the same data
type.
 In dealing with arrays, one must be familiar with loop-
control statements such as for(), while(), and do while().
ABOUT ARRAYS

Types of Arrays
A one-dimensional array can be compared to a
table consisting of a single column and multiple
rows.
ABOUT ARRAYS

A two-dimensional array can be compared to a table


consisting of several columns and several rows.
ABOUT ARRAYS

A variable can only hold one data at a time while an array


can hold several data at a time.
ONE-DIMENSIONAL ARRAYS

Declaring One-Dimensional Arrays

Format #1: type [] array_name = { value_list } ;


Format #2: type [] array_name = new data_type[size] ;

where :
type is a keyword that specifies the type of data
the array is going to store.
array_name is an identifier representing the name
of the array
value_list is optional and may be excluded. These
are values used to initialize the specified array.
size is an integer value which specifies the max
number of values the array will store.
ONE-DIMENSIONAL ARRAYS

Example:
int [] num = new int[5];
float [] grades = { 85, 76, 80.5f, 88, 75.50f };
char [] letters = { ‘a’ , ‘b’, ‘c’, ‘d’ };
String[] names = { “MJ”, KOBE” ,”Manu” , ”Yao“ } ;
ONE-DIMENSIONAL ARRAYS
Different Ways of Assigning Values to Note:
One-Dimensional Arrays Since arrays can
1. During declaration hold several data at
the same time, a
int[] num = { 1,2,3,4,5 };
subscript or index
2. Using assignment statement must be used
int[] num= new int[5]; whenever a data is
num[0] = 1; num[1] = 2; to be assigned to an
num[2] = 3; array. A subscript is
an integer value
num[3] = 4; num[4] = 5;
representing specific
location within an
subscript array. Array subscript
starts with zero.
ONE-DIMENSIONAL ARRAYS
3. Using input statements
Example:
public static void main ( String[] args ) {
Scanner in = new Scanner( System.in );
float [] rate = new float[4]; int loc = 0;
subscript can
System.out.print(“Enter a number : “); be a variable
num[loc] = in.nextFloat();
System.out.print(“Value “ + num[loc] + “ “ +
“saved at location “ + ( loc + 1 ) );
}
ONE-DIMENSIONAL ARRAYS
Different Ways of Accessing the Contents of
One-dimensional Arrays
Examples:
1. int [] num = { 1,2,3,4,5 }; int sum;
sum = num[0] + num[1] + num[2] + num[3] + num[4];
System.out.println( sum) ;
2. float[] grades = { 70,80,90,95,65 };
System.out.println(grades[0]) ; System.out.println( grades[1]) ;
System.out.println( grades[2]) ;
System.out.println( grades[3]) ;
System.out.println( grades[3]) ;
ONE-DIMENSIONAL ARRAYS
3. float [] grades = { 70,80,90,95,65 };
Scanner in = new Scanner( System.in );
int loc; loc = in.nextInt();
System.out.print ( grades[loc]);
4. float [] grades = { 70,80,90,95,65 }, ave = 0, sum = 0;
for ( int counter = 0; counter < = 4; counter++ ) {
System.out.print ( grades[counter] + "\n" );
sum = sum + grades[counter]; }
ave = sum / counter;
System.out.print(“Average Grade is “ + ave );
ONE-DIMENSIONAL ARRAYS
Example: Given the sales and expenses of ABC Marketing Inc.
for the 1st half of 2011, create a program that will
display the output below.
View Source
Code
Sales and Expenses of ABC Marketing Inc.
From January to June, 2011
Given:
Month Sales Expenses
Month Sales Expenses Profit
1 1000.00 200.00
2 2000.00 500.00
Jan 1000.00 200.00
3 3000.00 550.00
Feb 2000.00 500.00
4 1000.00 200.00
Mar 3000.00 550.00
5 5000.00 300.00
Apr 1000.00 200.00
6 6000.00 500.00
May 5000.00 300.00
Jun 6000.00 500.00

Totals
Averages
ONE-DIMENSIONAL ARRAYS
Example: Create a program that will process customer orders.
Such program must automatically supply item price &
description.
View Source
Code
ABC Marketing Inc.
Order Processing Program
List of Items
Item Description Price
Item Code : 999
111 DVD Player 2000
Description : XXXXXXXXXXXXXX
222 VHS Player 1500
Unit Price : 9999.99
333 Gas Stove 800
Quantity : 999
444 TV 1000
Total Cost : 9999.99

Process another customer order ( Y/N ) ?


TWO-DIMENSIONAL ARRAYS
Preparing Two-dimensional Arrays
Format : type [ ][ ] array_name = new type[size1][size2] ;
Format : type [ ][ ] array_name = { {value_row1 },
{value_row2},
{value_row3}, ….
{value_rowN} } ;
where :
type is a keyword that specifies the type of data
the array is going to store.
array_name is an identifier representing the name
of the array
size1 is an integer value that specifies the no. of rows that
the array will have.
size2 is an integer value that specifies the no. of columns
that the array will have per row.
TWO-DIMENSIONAL ARRAYS
Example:
1. int [ ][ ] num = new int [5][5];
2. float [][] students = new float[10][20];
3. String [][] employees = new String[3][2];
4. int[][] rates = { { 100,200,300,400 },
{ 500,600,700,800 },
{ 900, 100, 200, 300 } } ;
TWO-DIMENSIONAL ARRAYS
Assigning Values to Two-dimensional Arrays
1. During declaration such as:
int[][] rates = { { 100,200,300,400 },
{ 500,600,700,800 },
{ 900, 100, 200, 300 } } ;
2. Using assignment statement such as:
a. int [ ][ ] num = new int[3][3];
num[0][0] = 1; num[0][1] = 2; num[0][2] = 3;
num[1][0] = 4; num[1][1] = 5; num[1][2] = 6;
num[2][0] = 7; num[2][1] = 8; num[2][2] = 9;

b. String [ ][ ] employees = new String[3][2];


employees[0][0] = “MJ”;
employees[0][1] = “Kobe”;
TWO-DIMENSIONAL ARRAYS
3. Using input statements such as:
a. int [ ][ ] num = new int[3][3] ,row, col;
row = 1; col = 1;
num[0][0] = in.nextInt();
num[0][1] = in.nextInt();
num[row][col] = in.nextInt();
b. String[ ][ ] employee = new String[5][2];
int loc;
loc = in.nextInt();
System.out.print ( “Enter Employee Name : “ );
names[loc][0] = in.nextLine();
System.out.print ( “Enter Phone No. : “ );
names[loc][1] = in.nextLine();
TWO-DIMENSIONAL ARRAYS
Accessing the Contents of Two-dimensional Arrays
Examples:
1. int [ ][ ] num = new num[3][3]; Note:
num[0][0] = 1; num[0][1] = 2; num[0][2] = 3; Since arrays
num[1][0] = 1; num[1][1] = 2; num[1][2] = 3; can hold several
num[2][0] = 1; num[2][1] = 2; num[2][2] = 3; data at the
same time, a
int sum1, sum2, sum3; subscript must
sum1 = num[0][0] + num[0][1] + sum[0][2]; be appended to
sum2 = num[1][0] + num[1][1] + num[1][2]; the name of the
sum3 = num[2][0] + num[2][1] + num[2][2];
array whenever
there is a need
System.out.println( sum1 ) ; to retrieve the
System.out.println( sum2 ) ; data previously
System.out.println( sum3 ) ; stored to it.
subscript
TWO-DIMENSIONAL ARRAYS
2. int[][] num = new int[3][3];
num[0][0] = 1; num[0][1] = 2; num[0][2] = 3;
num[1][0] = 1; num[1][1] = 2; num[1][2] = 3;
num[2][0] = 1; num[2][1] = 2; num[2][2] = 3;
int sum[3], total = 0 ,row;
// Compute total of each row in array num
// and assign to array sum
for ( row = 0; row <= 2; row++ )
sum[row] = num[row][0] + num[row][1] + num[row][2];
// Compute overall total
for ( row = 0; row <= 2; row++ )
total = total + sum[row];
System.out.println( total ) ;

You might also like