Download Powerpoint slides

Document related concepts
no text concepts found
Transcript
™
Java
Programming
Tutorial
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
1
Java TM Programming. Tutorial
Course Objectives
1. How to develop and write useful Java™ program.
2. Learn about Software/Program Development Cycles & Methodologies.
1. Algorithms, pseudo-code, top-down design, step-wise refinement.
2. Testing & Debugging
3. Introduction to Software Engineering, code re- use.
3. Learn to use JAVA to build software:
1. Objects and classes: design, implementation & re-use.
1. Member Data & Functions/Methods.
2. Object definition, creation.
2. Applets and Graphics.
3. Control Structures-Decisions, Iterations,
1. action selections (if, if/else,)
2. repetition with for and while constructs.
3. Arithmetic and relational operations.
4. Data types & structures:
1. Numbers, characters, static, arrays, pointers, list, stack, queues,.
2. strings, Streams, File Processing, type conversion.
5. Programming errors, traps and pitfalls.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
2
Gentle introduction to Java programming.
The primary audience are professionals and students who need to get a fast
understanding and skills required to produce practical, commercial-grade Java
applications. Though prior programming experience is not an absolute
prerequisite, exposure to logic or/and some high-level languages, objectoriented programming will be very helpful, especially during the early stage of
the training. Those with extensive programming experience, will found the
early chapters as refreshers and can skip to the more advanced Java concepts.
Of course, you can always skip back to any introductory section or any session
of choice at any time.
Tutorial
Java TM Programming.
This course is part of our e-learning software development training series. The
tutorial covers fundamentals of developing & writing re-usable software code,
as well as provides hand-on exercises particularly suited for self-paced, online Java programming training.
It is expected that students who follow through and work the exercises at the
end of each sections would have developed a strong foundation in Java
programming to be able to analyze real-life problems and design, model and
test a conceptual Java solution. The tutorial also prepares dedicated students
for more advance Java techniques, methodologies and skills needed to be a
productive Java software developer, analyst., manager, consultant with
confidence of a professional.
If you are ready, let's dig in!
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
3
Tutorial
Java TM Programming.
Course Description:
This course intends to teach you how to design and develop software using the
popular JAVA programming language.
The topics to be covered include:
•Software Development Environment.
•Structured Program Development (flowchart, pseudo-code, step-wise
refinement, divide and conquer, etc.)
•Object-Oriented Software design.
•JAVA language syntax.
• Program Control -if, if/else, while/for loops, case-switch, break, continue,
etc.
•JAVA Building blocks -Functions, Data Types (const, simple variables,
Structures, objects, classes, packages, arrays, strings, Pointers, references).
•applets, Simple Graphics, basic HTML, Basic Input/Output and Files operations.
•Arithmetic and relational operations, sorting and searching.
•Introduction to Software Engineering, code re- use.
The teaching method integrates class lecture, examples and lab exercises that
reinforce concepts discussed in lectures and assigned readings from the course
textbook. Course assignments will range from simple to moderately complex
algorithm. Throughout the quarter, quizzes, tests and projects are designed to
evaluate students' mastery of programming concepts and software development
process.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
4
Table of Contents
#1.
Programming Overview
#2
Intro. to JAVA, data types- variables, constants, arithmetic /logical operations, i/o,
functions, algorithm, simple objects/class definition,
#3
Program Flow Controls: repetition with if, if/else, do/while and for loops, Object instantiation,
constructors/destructor, Visual & Numerical info.
#4
#5
Simple data structures-array data type, strings, formatted I/O, composite data structures –
pointers,
Complex Classes, Cohesion & Coupling, Method types, Scopes , Packages, Streams, Simple
Testing & Debugging.
Interfaces, Reusable codes, Event Handling, records, lists, GUI. Applets, Graphics, HTML.
#6
Sorting & Searching methods, More data structures.
#7
Event Handling, File processing, streams
#8
Advanced Data Structures-Sets, Maps, Hash tables, Trees.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
5
Software Development Cycle (5 phases)
Modification
Requests
Develop the
Purpose
Plan for
Solution
Product
Product
Realization
inputs/outputs
Real Objects
storage need
network need
5/2/2017
Product
Planned
1.
Structures
2.
Classes
3.
Behaviors
4.
Relationships
Edit Source Code
Compile Code
Link Object Code
Test-verify/certify
Verify product
developed is
what is
planned.
Deploy
Testing
Implement
Design
Analysis
Modification Requests
Install product.
End-User uses
product (User is
happy ever after!)
Correct logic.
No run-time
errors.
Test results
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
6
Overview of Programming Environment
People –Data, Info &
Procedures
IT professionals,
analysts, testers,
programmers,
users, decision
makers. etc)
Software
Instructions
Data
Program texts
1. Programming Languages (Machine Languages, Assembly
Languages, C, C++, Java, FORTRAN, COBOL, etc)
2. Programming Tools (Editors, Compilers, Linkers, PreProcessors, loaders),
3. Programming Procedures and Methods (structured
programming, OOP, achieving, etc.)
Hardware
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
7
Programming Environment Hardware Components
Input Devices –keyboard, Mouse, joystick, optical reader,
scanner, micro-phone, etc. use for getting data into the
computer.
Output Devices –monitors, printers, papers, other
computers or machines.
Memory units –Rapid Access Memory (RAM) or primary
memory; holds data ready for immediate processing or short
term storage of data.
Arithmetic and Logic Unit (ALU) –microprocessor that
performs the data manipulation such are arithmetic,
comparison, decision making, etc.
Central Processing Unit (CPU) –Integrated
circuit / microprocessor, responsible for process
flow, coordination, data transfer, etc among the
the different components.
Secondary Memory –Hard disk, floppy
disk, tapes, CD, films, etc. for long-term
storage of data.
5/2/2017
disk
2G-RAM
cpu/alu
motherboard
all typically enclose in a box
Hard-drive
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
8
Programming Software To solve problem.
e.g. Calculate the Gross pay for an employee.
1 solution in English Language – (i.e. human communication/instruction.)
Add overtime to base pay to get Gross Pay
Or for those arithmetically inclined: base pay + overtime pay = Gross Pay
2. Software Programming
Step by step computational instructions.
Step1: Load Base pay
Step 2. Load Overtime
Step 3: Add content of steps 1 & 2
Step 4: Display result of step 3
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
9
Programming or Software development
Need to calculate gross pay:
English Language – Add Overtime to base pay
Machine Languages –computer native language is
electrical pulses represented by 0s and 1s
called bits.
E.g.1010 0000 0000 0001 + 0001 1110 0101 0011
(binary codes)
Assembly Languages –English like abbreviations to represent machine
instruction and data.
Degree Programming
Difficult
Programming Languages
Development Progression
higher
Load BasePay
Add Overtime
Store GrossPay
Low-level
early days
Interpreters
Compilers
lower
today
High-level
double GrossPay,BasePay,GrossPay, OverTime ;
GrossPay =BasePay + OverTime
Higher-Level Languages –C, Fortran, Pascal, Basic, Visual C, Ada, COBOL,
Visual C++, 4GLs. Uses syntax and grammar close human communication.
English Language – symbolic representation:
Gross Pay = Base pay + Overtime pay
future?
Automation of Software development, AI, ES, BI,
etc
5/2/2017
Q: What is the difference between an
interpreter and a compiler?
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
10
Java Programming Development –game plan.
A happy Programmer uses an:
1. An EDITOR (vi, emacs, Notepad) to create a Program text, which is
stored on disk. Java Program file has extension of .java (e.g.
myprogram.java)
2. A PRE-PROCESSOR program to perform text substitution, macro
expansion, other files inclusion. (e.g. import java.util.* The result is
stored on disk.
Hard
drive
3. A COMPILER to convert the Java high-level code into byte code and
puts the result on file with extension .class.
4. An interpreter to that converts the intermediate byte_code (the
.class file) into a particular machine's native language.
5. LOADER –puts the executable in memory
Ha
rddri
ve
5/2/2017
Primary Memory (RAM)
CPU –executes the program instructions
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
11
Steps for Writing, Compiling & Running your programs
Text editor: vi, emacs, Notepad, even MS Word but must save as ascii or plain text or inside the
editor included in your IDE package.)
Write or Edit Source Code
invoke vi Hello.java`
Save the file: with extension .java e.g. Hello.java
Java Compiler:-javac to translate source code to an intermediate code called byte-code.
javac Hello stores the result of translation in a file with the same file name as original file but with extension
.class e.g. javac Hello.java => Hello.class (Hello.class is created if javac successfully converts Hello.java)
to compile source code
invoke javac Hello`
Hello.class
to execute to test program
Invoke Java Virtual Machine (JVM): Loads the byte codes, and starts the JAVA
interpreter which in turn converts the byte codes to the machine code before
giving the codes to the operating system, which actually executes the program.
invoke java Hello`
U are super
This is the sunny day scenario.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
12
Give me a Break.
A pessimistic view that never gets out of the loopsoftware never delivered. This model also implies a
clear break between and among the phases. But this
is/should not the case in practice.
Compile
Test/Execute
Edit
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
13
A more realistic view : once the
process begins, the 3 activities
typically overlaps each other.
Edit
Execute to Test
Complile
It is usually more like this overlapped
and repetitive loops!
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
14
Loops of Writing, Compiling and Running your programs
Q: What are the activities involved in creating a computer program?
Write or Edit Source Code
Open an editor and type in the text of your
program.
Save the text in a file with a name that is a
mnemonic for your program purpose, and an
extension .java. e.g Hello.java.
The repetitive loops of
edit-compile-test
until no more bugs.
(ideally)
Compile the Source Code
sample screen of execution
Compile (translate ) your .java code with a java compiler
called javac. e.g javac Hello.java
Fix errors (bugs ) that emerge during compilation. If errors
occur, go back to edit.-Compilation errors due to syntax and
linkage error-bad java grammar-missing import classes &
files, library, incorrect java grammar, typos, bad calls, rules
violations, Unidentifiable & Unknown Objects (UUOs),
missing or bad signatures, incomplete sentences, invalid
return addresses, unknown object etc.
If no compilation error, javac Hello.java
will create Hello.class file for us. This is
the program (intermediate –byte code)
that will be interpreted by JVM program,
by invoking::
java Hello.
Run Program
Fix bugs that emerge during execution.
If no logic error, we can run our Hello.class
for ever, give it to our friends, market it and
make lots of mullah. (We keep Hello.jave for
future updates ( release 2 & gazillions $).
If errors occur, we go back to edit.
Logic errors –wrong computations.
Be happy
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
15
Writing my 1st program
Assignment:
How ?
Write a JAVA program to print "Hello World" to the screen.
Create a public class named Hello, that has one public static main (String[ ] args) method.
The body of the method i.e statement between
a beginning
{
and
a closing
} braces.
will contain the JAVA statement to print "Hello"
i.e. System.out.println("Hello");
Editing a Source Code :
Inside step 1
Inside the editor (e.g. WordPad)
Start with statement that imports pre-defined java tools
(classes or packages) that your program will need.
import java.util.*
for benefits of reader, add comments to describe your
program.
Class is the building block or foundation for everything in JAVA.
Therefore to write any program in JAVA we must write it as a
Class, i.e we must define a class for our program. More
specifically we must define a class for our object.
What is a class then?:
A class is representation of an object's behaviors and state.
Within a class that represent an object' the behaviors
are translated to methods and the state are instance variables..
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
16
Writing, Compiling and Running your 1st program
Assignment:
How ?
Write a JAVA program to print "Hello World" to the screen.
Create a public class named Hello, that has one public static main (String[ ] args) method.
The body of the method i.e statement between
a beginning
{
and
a closing
} braces.
will contain the JAVA statement to print "Hello"
i.e. System.out.println("Hello");
Editing a Source Code :
step 1
Inside the editor (e.g. WordPad)
import java.util.*
1.a Create a program class
1.b Create a class method (a.k.a function)
This a class –called Hello.
It has one behavior – main (but no state representation).
The main method here is a public interface method- behavior- by which
other objects can interact with it.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
17
Writing, Compiling and Running your 1st program
Assignment:
How ?
Write a JAVA program to print "Hello World" to the screen.
Create a public class named Hello, that has one public static main (String[ ] args) method.
The body of the method –i.e. between
a beginning
{
and
a closing,
} braces.
will contain the JAVA statement to print "Hello"
i.e. System.out.println("Hello");
Inside step 1
Editing a Source Code :
import java.util.*
1.a Create a program class
1.b Create a class method (a.k.a function)
1.c write the statement that prints "Hello World"
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
18
Editing, Compiling and Running your Hello.java program
Assignment:
Syntax Error?
Write a JAVA program to print "Hello" to the screen.
public class Hello
{ public static main (String[ ] args)
{
System.out.println("Hello");
}.}
invokes javac
errors ?
missing class opening curly
brace.
correction:
give Java it's
curly braces {
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
19
Writing, Compiling and Running your 1st program
Assignment:
Write a JAVA program to print "Hello World" to the
screen.
Syntax
How Error?
?
public class Hello
{ public static main (String[ ] args)
{
System.out.println("Hello");
}.}
Compilation: Checking grammatical errors in Source Code :
errors ?
class was misspelled.
(compiler indicates below)
correction:
change Uppercase
C to lower case:
BlueJ also highlights
the reprobate line.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
20
Assignment:
Writing, Compiling and Running a java program
to print "Hello" to the screen.
Understanding the Hello class:. class is the building block for Java program.
What is a class?
It is a template used to create an object.
Construction of Java (Hello) class.
How do you construct a class?
access_type class classname
import java.util.*
public class Hello
add method main()
What is the syntax for method definition?
access type return_type methodname(parameters)
public static void main (String[ ] args)
{
System.out.println("Hello World");
}
method body
method signature
What is an object?
5/2/2017
It is a self-contained element representing a group of features and can perform specific tasks.
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
21
Assignment:
Writing, Compiling and Running your 1st program
Create a public class named Hello, that has one public static main (String[ ] args) method.
The body of the method i.e statement between
a beginning
{
and
a closing
} braces.
will contain the JAVA statement to print "Hello"
i.e. System.out.println("Hello");
Write a JAVA program to print
"Hello" to the screen.
Hello class construct.
Understanding the Hello class.
What is the syntax for class creation?
access_type class classname
followed by the body.
a beginning
import java.util.*
{
a closing } braces.
The class body contains everything in the
class.
Q: What are methods or functions?
5/2/2017
A: Named group of statements…
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
22
Understanding the innards of your 1st program
class
specification.
A JAVA program that prints "Hello World" to the screen.
class interface
class body
Hello.java Source Code :
{
instance fields
methods.}
class interface
access_type class classname
class body
public class
Hello
class body begin
{
public static void main(String[ ] args)
main method beginning
{
main method closing
class closing
}
}
access_type class return_type methodname( parameters)
followed by the body.
a beginning
{
a closing } braces.
The method body contains java statements of the method..
5/2/2017
JAVA statement to print "Hello"
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
23
A JAVA program that prints "Hello World" to the screen.
Summary of your 1st program
Hello.java Source Code
Hello class definition or specification
access_type class classname
public class Hello
class body begin
public static void main (String[ ] args)
main method beginning
JAVA statement to print "Hello"
main method closing
class closing
access scope return_type methodname(parameters)
followed by the body.i.e.
beginning {
java statements to be performed.
a closing } braces.
The method body contains java statements of the method..
method definition or specification
5/2/2017
Hello class body contains only one method –which is an
interface, no state representation, i.e no instance fields nor
class field, and no private or inside behaviors- no other
methods-were defined for this class. Why?
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
24
Understanding your 1st program -Summary
JAVA program to print "Hello World" to the screen.
Hello.java code :
access_type class classname
public class Hello
What is the syntax for method definition?
access scope return_type methodname(parameters)
public static void main (String[ ] args)
{
System.out.println("HelloWorld");
}
method body
method signature
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
25
Writing a JAVA program that uses 2 variables to hold 2 numbers and prints out the multiplication, addition and subtraction of the numbers to the screen.
JAVA expressions: made of: key-words, reserved words user- defined words and delimiters;
import java.util.*;
/**
import statements
* Write a description of class IntDataTypeDemo here.
Comments.
*
Declarative
* @author: Tai Elemide
Input/Output
* @version: Java Tutorial 1.0 Demo -Beta 04/07/05
Manipulative
*/
Assignment;
//This program is an example of using int built-in data type.
public class IntDataTypeDemo
{
public static void main(String[] args)
{
// declare 2 variables to hold integer (whole numbers) data
int num1, num2 ; // integer data type
Comments
System.out.println("");
Output screen
num1 = 40; // Using variable num1 to hold 40 i.e assign 40 to the varaible num1
num2 = 25; // assign 40 to the varaible num1
// Use the println method from System.out class to display data.
System.out.println("Using Sytem.out.println to print data held in variables.");
System.out.println("---------------------------------------------------------");
System.out.println (""); // This line prints a blank line.
System.out.println(num1 + "*" + num2 + " is " + (num1 * num2));
System.out.println(num1 +"+" + num2 + " is " + (num1 + num2));
System.out.println(num1 +"-" + num2 + " is " + (num1 - num2));
System.out.println (""); }
}
Manipulative
Input/Output Method
Operation
The next few slides show you how to write a class that has only 1 single-method called main. The main method servers as the public interface.
The slides only show how to use built data type (actually classes int, float, double, Scanner, System.out) in our methods.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
26
Assignment:
Writing a program in JAVA that inputs 2 numbers and use them for addition, subtraction, multiplication,
and print out the results.
How ?
/*This program is an example of using built-in data type with input. Assumes
Scanner class is defined */
import java.util.*
public Class IntDataTypeDemo
{
public static void main(String[] args)
{
// declare variable to hold input data
int Num1, Num2 ; // integer data type
byte Gender ='M';
// single character data type declaration and assignment.
Scanner InputFromKeyboard = new Scanner(System.in);
System.out.println("");
System.out.println (Please enter 2 numbers and a character:");
num1 =InputFromKeyboard.nextInt();
num2 =InputFromKeyboard.nextInt();
Gender = InputFromKeyboard.nextByte(); // get a character from the screen
Self-Test.
Can you explain what this class does, step-by-step?
Can you correctly identify the class different parts and
explain what each part represent?
System.out.println (""");
System.out.println(Num1 +"*" + Num2 "+ " = " + (Num1 * Num2));
System.out.println(Num1 +"+" + Num2 "+ " = " + (Num1 + Num2));
System.out.println(Num1 +"-" + Num2 "+ " = " + (Num1 - Num2));
System.out.println ("Gender is" + Gender);
System.out.println ("");
}
}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
27
/*This program is an example of using String data type (define in System
class)
and the input Scanner class defined in java.util package */
import java.util.*
public Class StringDataTypeDemo
{
public static void main(String[] args)
{
Scanner InputLine = new Scanner(System.in); // so we can do inputs
// declare variable string data type
String FriendNamed, YourName, CourseName;
System.out.println("");
CourseName = "Computer Programming");
System.out.println ("What is your name ?");
YourName =InputLine.nextLine();
System.out.println ("What is your friend's name ?");
FriendName =InputLine.nextLine();
System.out.println ("");
Self-Test.
What is the difference between this program and
the program from the preceding slide?
Find out how to use the other methods define in
the Scanner class and the String class.
System.out.println( "Your name is " + name_input );
}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
28
//This program is an example of using int built-in data type for input.
makes available classes defined in java.util.* package
import java.util.*;
/* java.util is a package that contains several predefine classes and methods. One of the classes is
Scanner.
Scanner is a predefine class that contains methods for getting input into our program */
IntDataTypeDemo is a class. It contains only 1 method called main, which
servers as a public interface, to the outside world.
public Class IntDataTypeDemo
{
public static void main(String[] args)
signature for main ( ) method definition,
{
Scanner Keyboard = new Scanner(System.in);
Declares Keyboard as a type of Scanner class. This an example of using
class
in our
own class
definition.
/*Keyboard is a variable of Scanner class i.e. a location in memory,another
that is
now
reserved
to hold
object of type Scanner. From this point, that location will now be referred to as Keyboard, */
// declare 2 variables to hold data
int num1, num2 ; // integer data type
System.out.println("");
num1 = Keyboard(nextInt(); // get first number from keyboard
num2 = Keyboard(nextInt(); // get second number from keyboard
System.out.println ("");
System.out.println(num1 +"*" + num2 "+ " is " + (num1 * num2));
System.out.println(num1 +"+" + num2 "+ " is " + (num1 + num2));
System.out.println(num1 +"-" + num2 "+ " is " + (num1 - num2));
System.out.println ("");
}
}
End of public interface method, main() definition.
End of IntDataTypeDemo class definition.
5/2/2017
nextInt( ) is one of the public interface methods defined in the Scanner class.
Since Keyboard is declared as a Scanner class, Keyboard now has access to the
Scanner class methods.
Side note:
To use any methods, it is only required that we know the method's signature.
A method's signature defines how to access and use it properly.
To define a method, 's signature, you specify :
1. the access control type –a.k.a permission (private,public, etc)
2. the type of data (return_type) to be returned by the method if any.
3. the name of the method
4. parameters-the set of data in needs from outside. The parameters
are specified by pair of data_type and data_name.
To use any methods, it is only required that we know the method's signature.
1. the type of data (return_type) by the method if any.
2. the name of the method
3. parameters and their data type
4. Of course, we must know the access type. Why?
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
29
BlueJ editor screen
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
30
program code
//import java.util.*;
/**
* This program is an example of using int built-in data type variables. It also shows
* how to use input Java class -Scanner for *
* @author: Tai Elemide
* @version: Java Tutorial Version 1.0 -Beta
*/
public class DataTypeDemo
{
public static void main(String[] args)
{
// declare variable to hold input data
int Num1, Num2, Sum, Diff, Product, Modul ; // variable declarations -integer data type
String operation ;
// Sring character data type declaration .
System.out.println("");
Num1 = 25; // variables assignment.
Num2 = 5;
operation =" * ";
System.out.println("---------------------------------------------------------------");
System.out.println("Using int variables to perform arithmetic (i.e. whole ) ");
System.out.println(" int data type is used for storing whole numbers with no decimal.");
System.out.println("---------------------------------------------------------------\n");
System.out.println(Num1 + operation + Num2 + " = " + (Num1 * Num2));
operation = " + ";
System.out.println(Num1 + operation + Num2 + " = " + (Num1 + Num2));
operation = " - ";
System.out.println(Num1 + operation + Num2 + " = " + (Num1 - Num2));
operation = " % ";
System.out.println(Num1 + operation + Num2 + " = " + (Num1 % Num2));
System.out.println("::::::::::::::::::::");
Sum = Num1 + Num2;
Diff = Num1 - Num2;
Product = Num1 * Num2; // assignments
Modul = Num1 % Num2;
System.out.print("Add = " + Sum );
System.out.println(", Diff= " + Diff );
System.out.print("Multiply = " + Product);
System.out.println(", Modulos = " + Modul );
System.out.println("----------------------------------------------");
Built-in data types: i.e. primitive data types.
int – integers i.e. whole numbers.
long – for long int
short –for short int
double–decimal numbers
float –decimal numbers (less range than double)
char –single characters.
Strings – chain or array of characters.
BlueJ output (terminal) screen.
}
}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
31
Writing a program in JAVA that inputs 2 numbers and 1 arithmetic sign. (*, +, -, /) Computes and prints out the result.
page 1
page 2
//This program is an example of using built-in data type with input. */
import java.util.*;
public class NumData
{
public static void main(String[] args)
{
int Num1 =0; double Num2 = 0.00 ; // integer data type
char Opr ='*';
// single character data type declaration and assignment.
String restOfLine;
Scanner InputFromKeyboard = new Scanner(System.in);
System.out.println("");
System.out.print("Please enter 2 numbers and a character: ");
while (!InputFromKeyboard.hasNextInt())
{System.out.print("Integer please: ");
InputFromKeyboard.nextLine();
}
Num1 =InputFromKeyboard.nextInt();
System.out.println("Opr = "+ Opr);
switch( Opr)
{
case '*':
System.out.println(Num1 +"*" + Num2 + " = " + (Num1 * Num2));
break;
case '+':
System.out.println(Num1 +"+" + Num2 + " = " + (Num1 + Num2));
case '-':
System.out.println(Num1 +"-" + Num2 + " = " + (Num1 - Num2));
break;
case '-':
System.out.println(Num1 +"-" + Num2 + " = " + (Num1 - Num2));
break;
}
System.out.println ("");
}
}
while (!InputFromKeyboard.hasNextDouble())
{System.out.print("Float please: ");
InputFromKeyboard.nextLine();
}
Num2 =InputFromKeyboard.nextDouble();
System.out.println("");
while ((restOfLine=InputFromKeyboard.nextLine()).length() == 0)
System.out.println("Now enter an operation: ");
Self-Test.
Why while? Explain the purpose the while in these
statements
Opr = restOfLine.trim().charAt(0); // get a character from the screen
continue on next page
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
32
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
33
Assignment: Writing a program in JAVA that inputs 2 numbers and 1 arithmetic sign. (*, +, -, /) Computes and prints
out the result.
page 1
page 2
//This program is an example of using built-in data type with input. Assumes
Scanner class is defined */
import java.util.*;
public class NumData
{
public static void main(String[] args)
{
// declare variable to hold input data
int Num1 =0; double Num2 = 0.00 ; // integer data type
char Opr ='*'; // single character data type declaration and assignment.
String restOfLine;
Scanner InputFromKeyboard = new Scanner(System.in);
System.out.println("");
do{
System.out.print("Please enter 2 numbers and a character: ");
while (!InputFromKeyboard.hasNextInt())
{System.out.print("Integer please: ");
InputFromKeyboard.nextLine();
}
Num1 =InputFromKeyboard.nextInt();
while (!InputFromKeyboard.hasNextDouble())
{System.out.print("Float please: ");
InputFromKeyboard.nextLine();
}
Num2 =InputFromKeyboard.nextDouble();
System.out.println("");
switch( Opr)
{
case '*':
System.out.println(Num1 +"*" + Num2 + " = " + (Num1 * Num2));
break;
case '+':
System.out.println(Num1 +"+" + Num2 + " = " + (Num1 + Num2));
break;
case '-':
System.out.println(Num1 +"-" + Num2 + " = " + (Num1 - Num2));
break;
case '/':
System.out.println(Num1 +"/" + Num2 + " = " + (Num1 / Num2));
break;
}
} while (Opr !='q');
System.out.println ("");
}
}
Using the switch and case constructs to replace multiple
if (…..) else
while ((restOfLine=InputFromKeyboard.nextLine()).length() == 0)
System.out.println("Now enter an operation: ");
// get a character from the screen
Opr = restOfLine.trim().charAt(0); // get a character from the screen
The alternate while (condition) { something } loop
the do {something } while (condition) loop
continue on next page
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
34
Introduction to OO Paradigm
Procedural languages (e.g. C, COBOL, FORTRAN) define programs around procedures or functions and data.
In the OO paradigm, solutions are designed around objects having characteristics and behaviors.
JAVA is an object-oriented programming language.
Object are things/concepts with :
•abilities (behaviors) and
•characteristics or states of being (attributes)
In JAVA objects are defined ( represented/implemented ) using the CLASS construct.
•Behaviors are implemented as member methods, functions.
•Characteristics or data (represent the state of being for an object )are implemented as instance fields .a.k.a data members.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
35
Representing state of being or how to define characteristics.
Basic state of being can
be represented:
1.
numbers
2.
characters.
whole numbers
45
54
3000
Primitive Data types.
Decimal
45.55
54.00
3000.89
Single characters
'a'
'b'
'k'
True or false
(yes or no)
Each primitive data type can hold different type of data.
Composite data types are built using these primitive data types.
e.g.
1. a name is made of individual single characters to form a string of characters.
2. a box can be represented by it's length, breadth & height (numbers).
3. a person can be represented by combination of first name, last name, social security number, address, gender, color,
height, weight, birth day, age, etc. i.e. string & numbers.
4. an employee can be represented by the composite of being a person, plus employee id, job title, rank, authority, salary,
office, type of work. (An object i.e. person + other strings + numbers)
5. a book can be represented by combination of title, edition, author, publisher, date of publication, number of pages, ISDN,
subject matter, price, level or audience, medium of publication, language, etc.
6. a car can be described by combination of type of vehicle, year model, manufacturer, number tires, color, body shape,
license plate, manufacturer assigned identification number, engine type, engine capacity, gas type, gas consumption,
electronic components, etc. Each of these is a composite object made up of basic primitive data type.
The overriding characteristic of composite or complex objects is that composite objects are represented
using other objects (perhaps built from combination of other lower level objects and primitive objects).
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
36
JAVA 4 basic built-in data types to define characteristics.
int
Whole Numbers
45
54
3000
Range -2G to +2G
Storage – 4 bytes
Variations
Byte
Range +128 > -127
Storage – 1 byte
short
Range ±2G
Storage – 4 bytes
Float
Decimal
45.55
54.00
3000.89
4.4
9.0
Variations /qualifiers
double
Range
± 1.7 x 10+308
to ± 1.7 x 10-324
Storage – 8 bytes
char
Single characters
'a'
'b'
'k'
Storage -2 bytes
True or false
(yes or no)
Variations /qualifiers
String - made of individual single
characters to form a sequence of
characters.
long
Range ± 9 x 1019
Storage – 8 bytes
JAVA Keywords for data type
Keyword
Data Type
Typical Size in Bytes
Byte
character
1
short
integer
2
int
integer
4
long
integer
4
float
floating-point number
4
double floating-point number
8
long double
floating-point number
8
Note: Bytes size varies from compiler to compiler. So check your compiler
implementation.
5/2/2017
boolean
•keywords –have specific meaning in the
programming language.
•Data types indicates the kind of data (type of
abstraction), so that the compiler know how to
reserve appropriate space for the object that will
"live" in the space and help guard against misuse of
the object space.
•To guard means to check and verify that objects are
involved in only predefined and known operations.
•e.g. myfirstname divide by mylastname is not a
typically allowable operation for String data type.
•i.e. Tai
÷ Elemide is an error!
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
37
JAVA Keywords for data type
•keywords -specific meaning to the complier.
•Data types indicates the kind of data (type of abstraction), so that the compiler can reserve appropriate
space for data.
•
Built-in data type.
Keyword
Data Type
Typical Size in Bytes
Byte
character
1
short
integer
2
int
integer
4
long
integer
4
float
floating-point number
4
double floating-point number
8
long double
floating-point number
8
Note: Bytes size varies from compiler to compiler. So check your compiler
implementation.
5/2/2017
Character and integers are
called Integral data types.
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
38
Other Java built-in data types
Literal Constant = data whose
•data type is implicit,
•automatically assume the JAVA language
predefined data type, based on the data syntax,
value and/or format
and hence is automatically type bounded.
Constant implies their values do not change.
LightOnOrOff =True;
True is True, type is Boolean
salary = 5423.00;
The value of 5423.00 is 5423.00 type is float
FirstNum = 9;
9 is 9, type is byte or short
AlphaChar = 'a';
'a' is a, the type is byte or char
AlphString = "b"
"b" is b followed by a null. It's data type is string.
VarName = "Good"
"Good" is a sequence of G o o d followed by a null. It's data type is string.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
39
Other built-in literal constants
Other Literal Constants
Constant
Default Type
Meaning
false
Boolean
NO
true
Boolean
FALSE
\n
esc char
newline
\t
esc char
vertical tab
\"
esc char
double quote
\b
esc char
backspace
Note:
For each data type there are basic operators that can operate on
the data type.
•Arithmetic operators on numeric data type.
•Concatenation on sting data type.
•Other operations are logical comparison, bit-wise
shifts etc.
For each data or object type, there are predefined operations and operators.
Operators are symbolic representation of operations. Operations specify what to do with objects.
Operators have specific, based on the context of their usage and placement
e.g. mathematic operations:
1. a plus sign (+), typically represent the addition of some objects on both side of the + sign,
2. the minus sign (-) implies the subtraction of object on the right side of the – symbol, from the object to the left of the –
symbol.
3. the division sign (/ or ÷ ) is an instruction to divide of object on the left side of the / or ÷ symbol, from the object to the
left of the / or ÷ symbol.
Java String class operations:
MyName = "Tai" + "Elemide" implies add, which translates to concatenate or join Strings "Tai" and "Elemide" to form TaiElemide
and store it in MyName
SonsLName = MyName – "Tai" which implies subtract the string "Tai" from " Tai Elemide " may not be valid if that operation has
not been defined for the minus sign for String object type.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
40
Using data type to store objects:Variables in JAVA
If you want to store data objects that will later be used in any of the following ways:
•
•
•
•
•
print or display out
use in some operations like arithmetic,
update, edit, copy to another data object,
manipulated in some ways to form new data object,
use as a temporary holder,
we must first
1. reserve some space in computer memory (RAM) for holding data objects whose value may or may change,(.i.e. a variable)
2. preferably associate a name or identifier to the reserved space,
3. tell the computer program what kind of object (i.e data type) use or "live" in the reserved memory space.
These process of performing these activities is known as Variables Declaration.
Variables (identifiers) are the names given to memory locations which will be used to store data.
4 characteristics of a typical variable.
name
variable identifier –how the location will be referred to.
object type
the type of data object that be stored in that location.
(Compiler can reserve right size of memory.)
Address
Location in memory (RAM) relative
To declare an variable, the programmer
must specify at least 2 things:
1.
the object data type and
2.
the variable name.
the actual value stored in that location.
Value
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
41
Variables in JAVA
Using Variables (for memory locations for storing data.)
reservation and naming of memory space, to be used for some data.
In general a variable must be declared before it can be used (referenced.)
Variable Declarations
int
NumberOfStudents ;
data type
float
Minimum declaration specifies type and name
1. Value is unknown;
2. Address may (not) be known until run-time.
name
String first_name ;
char
letter_grade;
double Height ;
salary ;
Using variables: once a variable has been declared it can be
used or referenced. e.g to store an initial value in the variable.
Declaration and value assignment can be combined.
Combined declaration/value assignment:
data type
name
Value
String CourseName = "Introduction to Programming";
int
Address
data type
NumberOfStudents = 45;
name
Scanner InputDevice = new Scanner(System.in);
Value
1. Address may (not) be known until run-time.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
42
Simple variables in JAVA
Reservation of memory to be used for some data.
A variable must be declared before it can be used (referenced.)
data type
name
a symbolic way of referencing a chunk of memory reserve for use.
object data type implications:
1. data type determines (suggests) amount of memory (size) to be reserved for the object.
2.
data object type, for built-in type, determines the data value range i.e. minimum and
maximum value that data object can represent. or hold (as a result of #1 above)
3.
data type determines the allowable type of operations and operators.
4.
may help (compiler) enforcement of correct usage of data object.
Variable Declarations:
int
NumberOfStudents ;
Q: Why must variables be declared be4 being used?
data type
int
byte
name
Maximum value -214783648 to+214783647
Mileage;
NumberOfPets; Maximum value -128 to + 127
short StreetNumber;
float Salary;
5/2/2017
Maximum value -32768 to +32767
Maximum ± 3.47 X10+38 to ± 1.4 X10-48
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
43
Summary JAVA declarative statements / variable declarations.
Declarative Statements are use to declare our intention to use some computer memory to hold some data of certain type.
•E.g.
•
int LotSize; keyword int tells the compiler that user-defined LotSize will be used to hold data type of
• int LotSize;
integer.
•char gender;
•
LotSize is called a variable or identifier and int is the data type.
•float salary;
•
Basic data type are language built-in.
•Sting name;
•
Other data types are defined in classes found in Library packages that come with your Software
•Employee Joe;
Development Toolkit and user-defined packages.
Made of keywords/reserved (specific meaning) and user-defined words.
Complex / Composite data type combines basic data types, keywords and user defined words together to create a new data type in
form of class.
A Class definition is a representation or abstraction of the real life object being represented.
•
•
•
We use data/object types (e.g char) for variable (user-defined) declaration and type casting.
Variable declaration tells the compiler to:
1.
Reserve an amount of memory of size defined for the data type.
2.
Associate that reserved location with the variable name.
3.
Check that the variable participates only in operations defined for that type of data (Type checking) and
type casting is the conversion of one data/object type to another type .e.g. interger (100) to float (100.00).
1.
int LotSize; can be converted to LotSizeDecimal like this: float LotSizeDecimal = (float) Lotsize;
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
44
Declaring basic data type in Java
One declaration per statement;
int height;
int breadth; int width ;
Multiple declaration per line, with multiple statements;
int box_square, box_volume;
Combined declarations : multiple variables of the same data type with one statement;
// other statements.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
45
Writing expressions using built-in integral data type
Variables declarations.
Note: JAVA is case sensitive.
int height,breadth, width, temp;
int box_square, box_volume;
Assignments operations.
The = is an arithmetic operator, with operands on both sides.
height = 34;
breadth = 20;
width = 25;
Using constants to assign values to variables.
box_square = height * width;
box_volume = box_square * height;
temp = box_volume;
temp= width;
5/2/2017
Using other variables to perform arithmetic
operations and to assign values to variables
Using other variables to assign values to variables.
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
46
JAVA String data type
JAVA string data type is provided as String class, with the appropriate access operations (methods).
"JAVA string data type is sequence of 0 or more characters (array of characters)
enclosed in a pair of quotes." It also has access and operational methods
associated with it.
Examples of String data type
To use/ manipulate strings you must apply the string
operations or methods provided with string Class.
"Hello"
"Convert this to lower case"
"This is an example of JAVA string "
"JAVA string data type operations or methods:"
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
47
JAVA String data type
JAVA string class internal storage representation (partial) as a special array of characters.
•
•
The position of each character in known by indexing, starting from 0.
i.e. the first character is in position 0,
•
In the example of TAI below, I is in position index 2,
•
in "JAM HAM", H is in 4th index location.
`T`
`A`
0
1
2
3
`J`
`A`
`M`
``
0
1
2
`I`
`\0`
Index
3
`H`
`A`
`M`
`\0`
4
5
6
7
JAVA String class (object type) declaration
i.e. declarations of variables of class String type.
String FullName, FirtName, LastName;
String city;
String zipCode;
String country;
String title;
String position;
String StreetAddress;
String salutation;
5/2/2017
With these declarations, of these variables belong to String
Class and there4 have all the abilities of String class type.
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
48
JAVA String class symbolic operations.
Assignment = a_string_data
YourAlias = MyName;
StreetName = "Clifton";
String LastName = "Ford";
Concantenation a_string_data + another_string
String FullName = "Joe" + LastName;
FullName = FirstName + LastName;
YourAlias = MyName + zipcode;
Address = StreetName + City + zipcode + country;
JAVA String class methods. (This is partial list – check your
Java SDK documentation for a complete list of Sting
class methods).
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
length( )
equals( a_string_data)
equalsIgnoreCase(a_string_data)
indexOf(a_string_data)
toLowerCase()
toUpperCase()
trim()
substring (Start)
substring (Start,End)
compareTo(a_string_data)
Declaration and Assignment
String FirstName = "Joe"
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
49
Break Time
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
50
OO Paradigm
To represent these real life objects, we must have pre-define data/object types, such the built-in data types. Of course each data
type have unique characteristics and behaviors.
Note: Object types are defined data types with ability for data-type hierarchies (inheritance) and operations or behavior.
In JAVA objects types are defined using the CLASS mechanism.
Before you define a class of objects you must first identify the objects you want to represent.
Object class identification involve determination of:
1. the object type attributes or characteristics that describe the type of objects states of being) (a.k.a data member, data
fields, instance fields)
2.
the object type allowable behaviors or operations or abilities (a.k.a methods, functions, routines)
3.
How the object of the type will interact with other objects (access)
In general, objects are things/concepts with abilities (behaviors) and characteristics or states of being (attributes)
In JAVA objects are defined ( represented/implemented ) using the CLASS construct in which:
•Behaviors are implemented as member methods, functions.
•Characteristics or data (represent the state of being for an object )are implemented as instance fields .a.k.a data members.
Creating our own User-defined data types
Beside the built-in data-type (native ) and classes defined in the java library PACKAGES, we need to create our own new object
representation known as object types (or data-types) i.e. new classes, using the above admonition.
Some of the reasons for creating our own (i.e. new object types or user-defined object types) are:
1) To expand capabilities of existing object behaviors and operators:
a.
to accurately represent the object we want to model (data abstraction).
b.
by defining more complex operations, (not available in built-it data type), for our user defined type.
c.
better hide information about our objects from illegal access and operations.
d.
allowing reuse of predefine objects, as building block for new, expanded, better, specialized objects via inheritance
of some or all the characteristics of the base objects.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
51
Identifying objects and object instances.
In OO we think of a program as the interactions of and among objects.
E.g. In the university setting, there are instructors, courses, buildings, departments, employees, colleges,
etc. that interact among themselves to run university programs and businesses.
1.
Each category has something in common among their characteristics
2.
These common characteristics enables us to identify the group and the group members.
1.. Course Object
2.. Car Object
•
•
•
•
•
•
•
C++, JAVA, Database Overview
Database Management System 1
Program Logic and Methods
Introduction to Programming
History of Civilization,
Physics 101
Calculus 1
These are all instances of Course
Object. They have similar features but
different feature values
1.. Network Object
•
•
•
•
•
•
•
• Daddy's Car
• Mommy's Car
• Company Car
• Rental Car
• Policed Car
• Used Car
• New Car
• My Car
These are all instances of Car Object.
Other kind of objects
1.. Building Object
•
•
•
•
•
•
•
•
Chemistry Building
Residential House
Office Building
Stadium
Pet House
Mega Mal
Mini Plaza
Religious Buildings
These are all instances of Building
Object.
• Person object
• Student object
• Vehicle object
• Employee object
• Computer object
• Modem object
• Thermostat object
• Tires object
• Furniture object
• Bank Account –(a concept)
• Telephone Conversation –(a concept)
• Wedding Party– (a concept)
• Crime – (a concept)
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
• Admission – (a concept)
Telecommunications Network.
Cable System Network
Satellite Network
Wired Network
Wireless Network
Optical Network
LAN, WAN
These are all instances of Network
Object.
5/2/2017
52
Object-Oriented (OO) Paradigm
In the OO paradigm, solutions are designed around objects types having self-contained characteristics and access methods.
e.g. books in general have:
1.
pages, title, author, publisher, date of publication,
2.
topics or subject matter, domain, etc. as common characteristics.
Depending on the problem we are solving, the books in our problem area will have certain operations. E.g. in the library domain
book operations may include
1.
check out a book, return a borrowed book, destroy a book,
2.
put book on a shelf, add a book to the catalog,
In the built-in data types, each object/data type have predefined size, allowable operators and operations:
1.
integer number operations -add, subtract, divide, multiply.
2.
character operations –sub-string, concatenation,
To represent these real life objects, we must have Object types.
Object types are data types with ability for data-type hierarchies (data type built from other data types which in turn are made of
other data types until we reach the most basic data types –this is a recursive sort of definition) and operations.
In JAVA objects types are defined using the CLASS mechanism.
Before you define a class of objects you must first identify the objects you want to represent.
Object class identification involve determination of
1.
the object type attributes (characteristics that describe the type of object)
2.
the object type allowable behavior (operations)
3.
How the object of the type will interact with other objects (access)
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
53
Self-improvement Exercises: Specifying Object Classes
1.
Identify the characteristics and possible behaviors of each of
the following objects i.e create model for each of this
objects.
a.
Professor object
b.
Student object
c.
Vehicle object
d.
Employee object
e.
Computer object
f.
Modem
g.
Thermostat
h.
Building
i.
Tires
j.
Furniture
k.
Bank Account –(a concept)
l.
Telephone Conversation –(a concept)
m. Wedding Party– (a concept)
n.
Crime – (a concept)
o.
Admission – (a concept)
2.
Convert each model to JAVA classes.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
54
Defining the CLASS for courses (minimal version)
Java CLASS: COURSES
OBJECT TYPE: COURSES
Data or Attributes or State
1.
CourseTitle
char(50)
2.
CourseNumber char(9)
3.
CourseCreditHrs numeric
4.
CoursePre
char(9)
5.
CourseDesc
char(500)
6.
CourseLeve
numeric;
Instance fields
methods
OPERATIONS.
1. Initialize( )- ; // with nothing.
2. Initialize( )- basic info (1,2,3,4,5 above);
3. Initialize( )- basic info (1,2, above);
4. set_course_num(2 above )
5. String get_course_num(return 2 )
6. set_title(1 above )
7. get_title( return 1 above)
8. set_pre_course( 4 above)
9. get_pre_course (return 4 above )
10. set_desc(5above )
11. get_desc( return 5 above)–
12. set_clevel(6 above )
13. get_cleve ( return 6 above)–
14. set_creditHrs(3)
15. get_creditHrs(return above)
5/2/2017
class Courses
{
private String CourseTitle;
private String CourseNumber;
private String CoursePre,
private String CourseDesc;
private int CourseCreditHrs;
private int CourseLevel;
// translate to interface methods
Courses( )- ; // constructor with nothing.
Courses( )- basic info (String ctitle, tnum,cpre,cdesc); //constructor
overloading
Courses( )- basic info (String ctitle,cnum); //constructor overloading
public void set_course_num(String cnum) // returns course number
public String get_course_num() // returns course number
public void set_title(String ctitle) // sets course title
public String get_title( ) // returns course title
public void set_pre_course( cpre) // set course pre-requisite
public String get_pre_course ( ) // returns course pre-requisite
public void set_desc(String cdesc ) // sets course description
public String get_desc( )–// returns course description
public void set_clevel(int cl ) // sets course level
public int get_clevel( )–// returns course level
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
55
Analysis of courses CLASS
class COURSES
class keyword starts the class specification
Courses is the name of the class.
public class Courses
{
private String CourseTitle;
private String CourseNumber[9];
private int
CourseCreditHrs;
private char
CoursePre[9] ;
private String CourseDesc[500];
private int
CourseLevel;
private keyword and colon(:) to denote the private data and function
section. Note the openning curly bracket
All the data are considered private
constructor method that is responsible for object instantiation.
Courses ( ) { // do nothing};
Courses ( String cT, String cN, int cC, String cP, String cD,String cL);
void setTitle( Sting paraTitle) {//CourseTitle = paraTitle};
String getTitle( ) { return CourseTitle; };
void PrintCourseInfo( ) ;
String setDesc(String description );
void setLevel (char level) { CourseLevel = level;};
char getLevel ( ) { return CourseLevel; };
another constructor method; being overloaded.
Can sets default values at object instantiation.
All the member methods a are considered
public to all the other classes defined
within the same package..
};
The closing curly bracket and semicolon closes the specification.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
56
CLASS specification
Class members:
Instance variables-all variables defined within a class specification.
Member Methods-all methods defined as part of the class specification.
Keyword private - only member methods can use the private data and methods (functions) defined in the private section.
Keyword public- public data and functions can be accessed and used by other methods and classes.
Keyword static- for data fields and/or methods defined within the class but do not belong to any object instance of the class and can be
accessed by any methods or objects that do not belong to the class.
The class specification can be considered as a TEMPLATE for object model, that tells the compiler how to allocate space for objects
declared as of that class.
A class is not an object. It is simply a type specification or type definition.
Every class has 2 default methods call constructor and destructor.
The constructor method(s) takes the name of the class, eg. courses ( ). The constructor is responsible for creating an new of object.
The destructor also uses the class name prefixed with the tilde symbol e.g. ~courses( ). The destructor is responsible for deleting
objects by releasing the memory used by the object as well as clean-up after the object.
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
57
Assignment:
Writing a JAVA class to represent Cars.
import java.util.*;
/** This class Cars models car ownership.
* @author: Tai Elemide
* @version: Java Tutorial Version 1.0 -Beta 4/17/2005
* There are at least 2 ways to use this class: 1. We can put a static main program here, in the class specification. This is usually done for test purposes.
* / or 2. Write a separate application (the preferred usage) that uses the class objects.
public class Cars Cars as a class definition or specification
{
// instance variables - defined without any access control i.e private,public,protected. Consequenly these variables can be accessed by any class in the
// package. -This is not the best way to go. Defeats the encapsulation and information protection or "hiding" sprit.
int highwayMilesPerGallon;
int cityMilesPerGallon;
String Owner;
int YearModel;
instance variables
String Make;
String Model;
note: the instance variables have default access controls,
String VIN;
since no explicit control access (private, public, protected)
String Color;
// Constructor for objects of class Cars
was specified.
public Cars() {
}
Consequently, any methods with which this class shares
// -------------------------------------------package will have access to the innards of this class.
/** showCarsInfoMethod displays a car instance information.
In the next exercise, we will fix this problem.
* @param: none
* @return : void
*/
public void showCarsInfoMethod( )
instance method
{
// Use the System.out.prinln method to show all the car info
System.out.println("\nCar Information Report");
System.out.println("----------------------");
System.out.println("Owner : " + Owner);
System.out.println("Model : " + Model);
System.out.println("Year : " + YearModel);
System.out.println("Make : " + Make);
System.out.println("Color : " + Color);
System.out.println("VIN : " + VIN);
System.out.println("Year : " + YearModel);
System.out.println("Rating : ");
System.out.println("\t Highway : " + highwayMilesPerGallon);
System.out.println("\t City : " + cityMilesPerGallon);
System.out.println("---------End of Report ----------\n");
}
}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
58
Assignment:
Writing a JAVA class to that uses Cars class.
import java.util.*;
/**DemoCars is the a program that uses the class Cars. here.
* * @author: Tai Elemide
* @version: Java Tutorial Version 1.0 -Beta 4/17/2005
*/
DemoCars as a class –dummy class
public class DemoCars
{
// instance variables - replace the example below with your own
/** Constructor for objects of class DemoCars
*/
program entry point - static
public static void main(String[ ] args)
{
// initialise instance variables
Cars DaddysCar = new Cars(); // create 1 instance of cars.
class method – that uses Cars class
Cars instance declaration –now using Cars.
DaddysCar as an object-an
instance of Cars.
// Can now set the instance fields of DaddysCar.
// The object DaddysCar has access to the instance fields defined in
// Cars becuase (1) they were defined without explicit access control
//
and (2) DemoCars and Cars are part of the same package.
DaddysCar.Owner = "Big Daddy";
note: because the instance variables have default access
DaddysCar.highwayMilesPerGallon = 14;
controls, since no explicit control access (private, public,
DaddysCar.cityMilesPerGallon = 12;
protected) was specified, we have direct access to the innards of
DaddysCar.YearModel = 1945;
this class. This defeats our security and violates our access
DaddysCar.Make = "Chevy";
control mechanism for data protection or hiding.
DaddysCar.Color = "Unknown";
DaddysCar.Model = "Impala";
DaddysCar.VIN = "ZI-RE8812345-9899TP09";
Cars instance method being used. showCarsInfoMethod() was
// call cars method to show DaddysCar
defined as a member (public interface) of Cars class. .
DaddysCar.showCarsInfoMethod( );
//----------------------------------------------------// now let's create MommysCar
Cars instance creation –now using Cars to create MommsCar object.
Cars MommysCar = new Cars();
MommysCar as an objectMommysCar.Owner = "Young Mommy";
an instance of Cars.
MommysCar.highwayMilesPerGallon = 25;
MommysCar.cityMilesPerGallon = 21;
note: Within the class of DemoCars, we have direct access to the innards of this
MommysCar.YearModel = 2005;
class, because those instance fields were not defined with explicit access control.
MommysCar.Make = "Lexus";
No security. The private data-instance variables, are not private!
MommysCar.Model = "3XGL";
MommysCar.Color = "Pristine Gold";
MommysCar.VIN = "LX-45JH-9HR-P05";
// show MommysCar
MommysCar.showCarsInfoMethod( );
}
5/2/2017
}
Cars instance method being used .
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
59
Output
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
60
Assignment:
Writing an improved JAVA class to represent Cars.- hides the information with keyword private.
page 1
page 2
import java.util.*;
public void setOwnerMethod( String message) { Owner = message; }
/** This class Cars models car ownership.
* @author: Tai Elemide
public String getOwnerMethod() { return Owner; }
* @version: Java Tutorial Version 1.0 -Beta 4/17/2005
**/
public void setModelMethod( String message) { Model = message; }
public class Cars
{
Cars as a class definition or specification
public String getModelMethod() { return Model; }
/* instance variables - defined with private access control i.e only the object
methods (those not defined as static) that a members of the class will
public void setMakeMethod( String message)
have direct access to these private fields.Hence we achieve high level
{ Make = message; }
of protection and data "hiding" for the fields*/
instance
private int highwayMilesPerGallon;
methods
public String getMakeMethod() { returnMake; }
private int cityMilesPerGallon;
instance variables
private String Owner;
public void setColorMethod( String message) { Color = message; }
private int YearModel;
note: the instance variables now
private String Make;
have private access controls.
public String getColorMethod() { return Color; }
private String Model;
showCarsInfoMethod has access
private String VIN;
to the fields.
public void setYearMethod( int message) { Year = message; }
private String Color;
// Constructor for objects of class Cars
public String getYearMethod() { returnYear; }
public Cars() { }
/** showCarsInfoMethod displays a car instance information.
public void setVINwnerMethod( String message) {VIN = message; }
* @param: none
instance method
* @return : void */
public String getVINMethod() { return VIN; }
public void showCarsInfoMethod( )
{
public void setYearModelMethod( String message) {Owner = message; }
// Use the System.out.prinln method to show all the car info
System.out.println("\nCar Information Report");
public String getYearModelMethod() { return YearModel; }
System.out.println("----------------------");
System.out.println("Owner : " + Owner);
public void setHighwayMilageMethod( int message)
System.out.println("Model : " + Model);
{highwayMilesPerGallon = message; }
System.out.println("Year : " + YearModel);
System.out.println("Make : " + Make);
public int getHighwayMilageMethod() { return highwayMilesPerGallon; }
System.out.println("Color : " + Color);
System.out.println("VIN : " + VIN);
public void setCityMilageMethod( int message)
System.out.println("Year : " + YearModel);
{cityMilesPerGallon = message; }
System.out.println("Rating : ");
System.out.println("\t Highway : " + highwayMilesPerGallon);
public int getCityMilageMethod() { return cityMilesPerGallon; }
System.out.println("\t City : " + cityMilesPerGallon);
}
System.out.println("---------End of Report ----------\n");
}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
61
Assignment:
DaddysCar is an
instance of Cars.
Writing an improved JAVA program (class) to that uses Cars class.
import java.util.*;
/**DemoCars is the a program that uses the class Cars. here.
* * @author: Tai Elemide
* @version: Java Tutorial Version 1.0 -Beta 4/17/2005
*/
public class DemoCars
{
public static void main(String[ ] args)
{
// create an instance variables
Cars DaddysCar = new Cars(); // create 1 instance of cars.
DemoCars as a class –dummy class
static class method – that uses Cars class
Cars instance declaration –now using Cars.
/*Can now set the instance fields of DaddysCar.
The object DaddysCar CANNOT directly access the instance fields, except through the
instance access methods provided.*/
// DaddysCar.Owner = "Big Daddy"; not valid-no direct access; instead use
DaddysCar.setOwnerMethod("Big Daddy");
DaddysCar. setHighwayMilageMethod( 14);
DaddysCar. setHighwayMilageMethod( 12);
DaddysCar. setYearMethod (1945);
DaddysCar. setMakeMethod ("Chevy");
DaddysCar. setColorMethod( "Unknown");
DaddysCar. setModelMethod( "Impala");
DaddysCar. setVINwnerMethod( "ZI-RE8812345-9899TP09");
DaddysCar.showCarsInfoMethod( );
//----------------------------------------------------Cars MommysCar = new Cars();
MommysCar,
MyUnclesCar,
MyFriendsCar
are instances of
Cars.
Cars instatiation –
using Cars to create
MyUnclesCar,
MyFriendsCar objects.
Cars MyUnclesCar = new Cars();
Cars MyFriendsCar = new Cars();
MommysCar.Owner = "Young Mommy";
MommysCar.highwayMilesPerGallon = 25;
MommysCar.cityMilesPerGallon = 21;
MommysCar.YearModel = 2005;
MommysCar.Make = "Lexus";
MommysCar.Model = "3XGL";
MommysCar.Color = "Pristine Gold";
MommysCar.VIN = "LX-45JH-9HR-P05";
// show MommysCar
MommysCar.showCarsInfoMethod( );
}
}
5/2/2017
Cars instance methods being used .
Cars instance method being used .
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
62
/*This program is an example of using built-in data type with input. Assumes Scanner class
is defined */
import java.util.*
public Class IntDataTypeDemo
{
public static void main(String[] args)
{
// declare variable to hold input data
int Num1, Num2 ; // integer data type
byte Gender ='M';
// single character data type declaration and assignment.
Scanner InputFromKeyboard = new Scanner(System.in);
System.out.println("");
System.out.println (Please enter 2 numbers and a character:");
num1 =InputFromKeyboard.nextInt();
num2 =InputFromKeyboard.nextInt();
Gender = InputFromKeyboard.nextByte(); // get a character from the screen
// be careful here, how you type your input. The above will read end of line as character in
// your Gender variable! – What is the solution to this problem?
System.out.println (""");
System.out.println(Num1 +"*" + Num2 "+ " = " + (Num1 * Num2));
System.out.println(Num1 +"+" + Num2 "+ " = " + (Num1 + Num2));
System.out.println(Num1 +"-" + Num2 "+ " = " + (Num1 - Num2));
System.out.println ("Gender is" + Gender);
System.out.println ("");
}}
5/2/2017
Java TM Programming.Tutorial - Lanrel Tech Training, Consulting & Staffing; Author/Instructor:Tai Elemide
63