The Java Programming Language: Topics
The Java Programming Language: Topics
The Java Programming Language: Topics
About Java
Program Structure
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
if() Statement
switch() Statement
for() Statement
Control
while() Statement Statements
do while() statement
Return
Topics
Introduction
Creating/Using Methods
Parts of a Method
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.
public static void main ( String[] args ) specifies the class’ main
program. Must be given if class is a stand-alone type of program.
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.
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();
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.
.
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.
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
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.
Loop-Control Statements
These are statements that execute statement/s
repeatedly for as long as specific condition is satisfied.
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.
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
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