Upload
bryce-parrish
View
239
Download
2
Embed Size (px)
Citation preview
Introduction to JAVAIntroduction to JAVA
PROGRAMMING STEPSPROGRAMMING STEPS
ANALISA MASALAHNYAANALISA MASALAHNYA INPUT-NYA APA SAJA?INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA?ALGORITMA PROSESNYA BAGAIMANA? OUTPUT-NYA APA?OUTPUT-NYA APA?
KETIK SOURCE CODE-NYAKETIK SOURCE CODE-NYA HEADER FILES HEADER FILES import < library >import < library > GLOBAL SECTIONS GLOBAL SECTIONS VARIABEL GLOBAL, FUNGSI BANTU VARIABEL GLOBAL, FUNGSI BANTU MAIN SECTIONS MAIN SECTIONS VARIABEL LOKAL, INPUT, PROSES, VARIABEL LOKAL, INPUT, PROSES,
OUTPUTOUTPUT COMPILE & RUN PROGRAMNYA COMPILE & RUN PROGRAMNYA ADA ADA
ERROR ?ERROR ? TES HASILNYA TES HASILNYA SUDAH BENAR ? SUDAH BENAR ? BUAT ARSIP/ DOKUMENTASINYABUAT ARSIP/ DOKUMENTASINYA
Computers and ProgrammingComputers and Programming
A computer is a machine that can process A computer is a machine that can process data by carrying out complex calculations data by carrying out complex calculations quickly.quickly.
A A programprogram is a set of instructions for the is a set of instructions for the computer to execute.computer to execute.
A program can be A program can be high-levelhigh-level (easy for (easy for humans to understand) or humans to understand) or low-levellow-level (easy (easy for the computer to understand).for the computer to understand).
In any case, programs have to be written In any case, programs have to be written following a strict language syntax.following a strict language syntax.
Running a ProgramRunning a Program
Typically, a program source code has to be Typically, a program source code has to be compiledcompiled into machine language before it into machine language before it can be understood by a computer.can be understood by a computer.
programmer
void test(){ println(“Hi”);}
source code (high level)
compiler
machine language
object code (low level)
writes
executed by
computer
Hi
PortabilityPortability
Different makes of computersDifferent makes of computers speak different “languages” (machine speak different “languages” (machine
language)language) use different compilers. use different compilers.
This means that object code produced by This means that object code produced by one compiler may not work on another one compiler may not work on another computer of a different make.computer of a different make.
Thus the program is not Thus the program is not portableportable.. Java is Java is portableportable because it works in a because it works in a
different way.different way.
History of JavaHistory of Java
The Java programming language was The Java programming language was developed at Sun Microsystemsdeveloped at Sun Microsystems
It is meant to be a It is meant to be a portableportable language language that allows the same program code that allows the same program code to be run on different computer to be run on different computer makes.makes.
Java program code is translated into Java program code is translated into byte-codebyte-code that is interpreted into that is interpreted into machine language that the computer machine language that the computer can understand.can understand.
Java Byte-CodeJava Byte-Code
Java source code is compiled by the Java Java source code is compiled by the Java compiler into compiler into byte-codebyte-code..
Byte-code is the machine language for a Byte-code is the machine language for a ‘typical’ computer.‘typical’ computer.
This ‘typical’ computer is known as the This ‘typical’ computer is known as the Java Java Virtual MachineVirtual Machine..
A byte-code A byte-code interpreter interpreter will translate byte-will translate byte-code into object code for the particular code into object code for the particular machine.machine.
The byte-code is thus The byte-code is thus portableportable because an because an interpreter is simpler to write than a compiler.interpreter is simpler to write than a compiler.
Running a Java ProgramRunning a Java Program
programmer
public void test() { System.out.println(“Hi”);} Java source code (high level)
Javacompiler
Machine language
object code (low level)
writes
executed by
computer
HiByte-codeinterpreter
Java byte-code
Extra step thatallows forportability
Types of Java ProgramsTypes of Java Programs
Console Applications:Console Applications:Simple text input / outputSimple text input / outputThis is what we will be doing for most of This is what we will be doing for most of
this course as we are learning how to this course as we are learning how to program.program.public class ConsoleApp
{public static void main(String[] args){
System.out.println("Hello World!");}
}
Types of Java ProgramsTypes of Java Programs
GUI Applications:GUI Applications:Using the Java Swing libraryUsing the Java Swing library
import javax.swing.*; public class GuiApp{
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Hello World!","GUI Application", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);}
}
Types of Java ProgramsTypes of Java Programs
Applets Applets To be viewed using a internet browserTo be viewed using a internet browser
import java.applet.*;import java.awt.*; public class AppletEg extends Applet{
public void paint(Graphics g){
g.drawString("Hello World!", 20, 20);}
}___________________________________________________<applet code="AppletEg.class" width=200 height=40></applet>
Sample Java ProgramSample Java Programpublic classpublic class CalcCircle CalcCircle{{ public static void main(String[ ] args)public static void main(String[ ] args) {{
intint radius; radius; // radius - variable// radius - variablefinalfinal doubledouble PI = 3.14159; PI = 3.14159; // PI - constants// PI - constants
radius = 10;radius = 10;doubledouble area = PI * radius * radius; area = PI * radius * radius;doubledouble circumference = 2 * PI * radius; circumference = 2 * PI * radius;
System.out.println(”For a circle with radius ” + radius + System.out.println(”For a circle with radius ” + radius +
”,”);”,”);System.out.print(”The circumference is ” + circumference);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);System.out.println(” and the area is ” + area);
}}}}
Elements of a Java ProgramElements of a Java Program
A Java Program is made up of:A Java Program is made up of:Identifiers:Identifiers:
variablesvariablesconstantsconstants
Literal valuesLiteral valuesData typesData typesOperatorsOperatorsExpressionsExpressions
IdentifiersIdentifiers
The identifiers in the previous The identifiers in the previous program consist of:program consist of:
public class CalcCircle{ public static void main(String[] args) {
int radius; // radius - variablefinal double PI = 3.14159; // PI - constants
…
}}
identifier indicating name of the program(class name)
identifier to store the value of radius(variable)
identifier to store the fixed value of PI(constant)
Data TypesData Types
Data types indicate the type of Data types indicate the type of storage required.storage required.
public class CalcCircle{ public static void main(String[ ] args) {
int radius; // radius - variablefinal double PI = 3.14159; // PI - constants
…
}}
radius is an integer (int) value
PI is a floating-point (double) value
Literal valuesLiteral values
Literals are the actual values stored Literals are the actual values stored in variables or used in calculations.in variables or used in calculations.
public class CalcCircle{ public static void main(String[ ] args) {
…radius = 10;…
}}
the variable radius stores the value 10
Operators and ExpressionsOperators and Expressions
Operators allow us to perform some Operators allow us to perform some calculations on the data by forming calculations on the data by forming expressions.expressions.
public class CalcCircle{ public static void main(String[ ] args) {
…double area = PI * radius * radius;double circumference = 2 * PI * radius;…
}}
The multiplication operator (*) is used to calculate the area
An expression is formed usingoperators and operands
Java Program StructureJava Program Structure For the next few weeks, our Java For the next few weeks, our Java
programs will have the following programs will have the following structure:structure:
public class CalcCircle{ public static void main(String[ ] args) {
// This section consists of // program code consisting of // of Java statements //
}}
The program is a class definition – use the same name as the filename.ie. Save this file as CalcCircle.java
Your program must have a mainmethod – it will start execution from here.
Curly braces indicate where sections begin and end.You should indent your code for clarity.
Displaying OutputDisplaying OutputFor console applications, we use For console applications, we use
the System.out object to display the System.out object to display output.output.public class CalcCircle
{ public static void main(String[ ] args) {
… System.out.println(”For a circle with radius ” + radius + ”,”);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);
}}
The text and data within the parentheseswill be output to the screen.
Compiling and RunningCompiling and Running
The preceding source code must be saved as The preceding source code must be saved as CalcCircle.javaCalcCircle.java
You must then use the Java Development Kit You must then use the Java Development Kit (JDK) to compile the program using the (JDK) to compile the program using the commandcommandjavac CalcCircle.javajavac CalcCircle.java
The byte-code file The byte-code file CalcCircle.classCalcCircle.class will be will be created by the compiler if there are no errors.created by the compiler if there are no errors.
To run the program, use the commandTo run the program, use the commandjava CalcCirclejava CalcCircle
Compiling and RunnngCompiling and Runnng
Buttons to compile andrun the program
Anatomy of a Java ClassAnatomy of a Java Class
A Java console application must consist of A Java console application must consist of one class that has the following structure: one class that has the following structure:
/* This is a sample program only. Written by: Date: */public class SampleProgram{
public static void main(String [] args){
int num1 = 5; // num stores 5System.out.print("num1 has value ");
System.out.println(num1);}
}
class header
mainmethod
Anatomy of a Java ClassAnatomy of a Java Class
A Java console application must consist of A Java console application must consist of one class that has the following structure: one class that has the following structure:
/* This is a sample program only. Written by: Date: */public class SampleProgram{
public static void main(String [] args){
int num1 = 5; // num stores 5System.out.print("num1 has value ");
System.out.println(num1);}
}
multi-line comments
in-linecomments
name of the class
statementsto be executed
What is the result of execution?What is the result of execution?
public classpublic class CalcCircle CalcCircle{{ public static void main(String[ ] args)public static void main(String[ ] args) {{
intint radius; radius; // radius - variable// radius - variablefinalfinal doubledouble PI = 3.14159; PI = 3.14159; // PI - constants// PI - constants
radius = 10;radius = 10;doubledouble area = PI * radius * radius; area = PI * radius * radius;doubledouble circumference = 2 * PI * radius; circumference = 2 * PI * radius;
System.out.println(”For a circle with radius ” + radius + System.out.println(”For a circle with radius ” + radius +
”,”);”,”);System.out.print(”The circumference is ” + circumference);System.out.print(”The circumference is ” + circumference);System.out.println(” and the area is ” + area);System.out.println(” and the area is ” + area);
}}}}
Displaying outputDisplaying output
There are some predefined classes in Java There are some predefined classes in Java that we can use for basic tasks such as:that we can use for basic tasks such as: reading inputreading input displaying outputdisplaying output
We use the We use the SystemSystem classclass to display output to display output to the screen for console applications.to the screen for console applications.
System.out System.out is an is an objectobject that provides that provides methods for displaying strings of characters methods for displaying strings of characters to the console screen.to the console screen. The The methodsmethods we can use are we can use are printprint and and printlnprintln..
ExampleExample
Write a program that prints two lines: Write a program that prints two lines: I love Java ProgrammingI love Java Programming
It is fun!It is fun!
public class PrintTwoLines{ public static void main(String[] args) { System.out.println("I love Java Programming"); System.out.println("It is fun"); }}
Print vs PrintlnPrint vs Println
What if you use What if you use System.out.print()System.out.print() instead?instead?
System.out.println() advances the System.out.println() advances the cursor to the next line after cursor to the next line after displaying the required output. displaying the required output.
If you use System.out.print(), you If you use System.out.print(), you might need to add spaces to format might need to add spaces to format your output clearly.your output clearly.
ExamplesExamples
Code Fragment Output Displayed
System.out.println("First line");System.out.println("Second line");
First lineSecond line
System.out.print("First line");System.out.print("Second line");
First lineSecond line
ExerciseExercise
Write a Java program that displays Write a Java program that displays your name and your studentID.your name and your studentID.
// Sandy Lim// Lecture 1// Printing name and student IDpublic class Information{
public static void main (String[] args){
// your code here}
}
ExerciseExercise
Write a Java program that prints out Write a Java program that prints out to the screen the following tree:to the screen the following tree: ** ****** ************************
********
// Sandy Lim// Lecture 1// Printing a tree using *public class tree{
public static void main (String[] args){
// your code here}
}
RemindersReminders
Get your computer accounts before Get your computer accounts before next week's tutorial so that you can next week's tutorial so that you can start programming ASAP.start programming ASAP.
Download JCreatorLE and J2SDK1.5.0, Download JCreatorLE and J2SDK1.5.0, you can access both through the you can access both through the JCreator (3.50LE) website: JCreator (3.50LE) website: http://www.jcreator.com/download.hthttp://www.jcreator.com/download.htmm
Data Types, Data Types, Variables & Variables & OperatorsOperators
Memory and DataMemory and DataOne of the most important components One of the most important components
of a computer system is the of a computer system is the memorymemory..A computer’s memory holds:A computer’s memory holds:
data that is to be processeddata that is to be processeddata that is the result of some processingdata that is the result of some processing
We can imagine that a computer’s We can imagine that a computer’s memory consists of boxes to hold data.memory consists of boxes to hold data.
However, the However, the sizessizes of the boxes would of the boxes would depend on the type of data that is held.depend on the type of data that is held.
IdentifiersIdentifiers
We have to give We have to give namesnames to the boxes to the boxes we are using to store data.we are using to store data.
These names are called These names are called variable variable namesnames, or , or identifiersidentifiers..
The actual data is the The actual data is the literalliteral valuevalue of the identifier.of the identifier.
subject
BIT106 value of subject
identifier / variable name
The box is identified assubject and it stores the value “BIT106”
Java Spelling RulesJava Spelling Rules
An identifier can consist of:An identifier can consist of:letters (A – Z, a – z) letters (A – Z, a – z) digits (0 to 9) digits (0 to 9) the characters _ and $the characters _ and $
The first character cannot be a digit.The first character cannot be a digit.
Identifier RulesIdentifier Rules
A single identifier must be one word A single identifier must be one word only (no spaces) of any length.only (no spaces) of any length.
Java is Java is case-sensitivecase-sensitive. . Reserved WordsReserved Words cannot be cannot be
identifiers.identifiers.These are words which have a special These are words which have a special
meaning in Javameaning in Java
ExamplesExamplesExamples of identifiersExamples of identifiers
num1num1 num2num2 first_namefirst_name lastNamelastNamenumberOfStudentsnumberOfStudents accountNumberaccountNumbermyProgrammyProgram MYPROGRAMMYPROGRAM
Examples of reserved wordsExamples of reserved wordspublicpublic ifif intint doubledouble
see Appendix 1 in the text book for others.see Appendix 1 in the text book for others. Illegal identifiersIllegal identifiers
3rdValue3rdValue my programmy program this&that this&that
ExerciseExercise
Which of the following are valid identifier Which of the following are valid identifier names?names?my_granny’s_namemy_granny’s_namejoesCarjoesCarintegerinteger2ndNum2ndNumChild3Child3 doubledouble third valuethird value mid2charsmid2chars PUBLICPUBLIC
Types of DataTypes of Data
What kind of data can be collected for use What kind of data can be collected for use in a computer system?in a computer system?
Consider data on:Consider data on: College application formCollege application form Student transcriptStudent transcript Role Playing Game (RPG)Role Playing Game (RPG)
Types of DataTypes of Data
We typically want to collect data which We typically want to collect data which may bemay be numericnumeric characterscharacters StringsStrings choice (Y/N)choice (Y/N)
Java Data TypesJava Data Types In order to determine the sizes of storage (boxes) In order to determine the sizes of storage (boxes)
required to hold data, we have to required to hold data, we have to declaredeclare the the data data typestypes of the identifiers used. of the identifiers used.
Integer data types are used to hold whole numbers Integer data types are used to hold whole numbers 0, -10, 99, 10010, -10, 99, 1001
The Character data type is used to hold any single The Character data type is used to hold any single character from the computer keyboardcharacter from the computer keyboard '>', 'h', '8''>', 'h', '8'
Floating-point data types can hold numbers with a Floating-point data types can hold numbers with a decimal point and a fractional part.decimal point and a fractional part. -2.3, 6.99992, 5e6, 1.5f-2.3, 6.99992, 5e6, 1.5f
The Boolean data type can hold the values The Boolean data type can hold the values truetrue or or falsefalse..
Primitive vs Primitive vs Reference Data TypesReference Data Types
A data type can be a:A data type can be a:Primitive typePrimitive typeReference type (or Class type)Reference type (or Class type)
Primitive vs Reference Data Primitive vs Reference Data TypesTypes
A Primitive type is one that holds a A Primitive type is one that holds a simple, indecomposable value, such simple, indecomposable value, such as:as:a single numbera single numbera single charactera single character
A Reference type is a type for a A Reference type is a type for a classclass::it can hold objects that have data and it can hold objects that have data and
methods methods
Java Primitive Data TypesJava Primitive Data TypesThere are 8 primitive data types in JavaThere are 8 primitive data types in Java
Type nameType name Kind of valueKind of value Memory usedMemory used
bytebyte integerinteger 1 byte1 byte
shortshort integerinteger 2 bytes2 bytes
intint integerinteger 4 bytes4 bytes
longlong integerinteger 8 bytes8 bytes
floatfloat floating-point numberfloating-point number 4 bytes4 bytes
double double floating-point numberfloating-point number 8 bytes8 bytes
charchar single charactersingle character 2 bytes2 bytes
booleanboolean true or falsetrue or false 1 bit1 bit
Declaring variablesDeclaring variables
When we want to store some data in When we want to store some data in a variable,a variable,we must first we must first declaredeclare that variable. that variable.to prepare memory storage for that to prepare memory storage for that
data.data.Syntax:Syntax:
Type VariableName;Type VariableName;
Declaring variablesDeclaring variables
Examples:Examples:The following statements will declareThe following statements will declare
an integer variable called studentNumber to an integer variable called studentNumber to store a student number: store a student number:
a double variable to store the score for a studenta double variable to store the score for a studenta character variable to store the lettergradea character variable to store the lettergrade
public static void main(String[] args){
// declaring variablesint studentNumber;double score;char letterGrade;
Assignment StatementsAssignment Statements Once we have declared our variables, we Once we have declared our variables, we
can use the variables to hold data.can use the variables to hold data. This is done by This is done by assigningassigning literal values literal values
to the variables.to the variables. Syntax (for primitive types):Syntax (for primitive types):
VariableName = value;VariableName = value; This means that the value on the right hand This means that the value on the right hand
side is evaluated and the variable on the left side is evaluated and the variable on the left hand side is set to this value.hand side is set to this value.
Assignment StatementsAssignment Statements Examples:Examples:
Setting the student number, score and lettergrade Setting the student number, score and lettergrade for the variables declared earlier:for the variables declared earlier:
public static void main(String[] args){
// declaring variablesint studentNumber;double score;char letterGrade;
// assigning values to variablesstudentNumber = 100;score = 50.8;letterGrade = 'D';
}
Initializing VariablesInitializing Variables We may also We may also initialize initialize variables when variables when
declaring them.declaring them. Syntax:Syntax:
Type VariableName = value;Type VariableName = value; This will set the value of the variable the This will set the value of the variable the
moment it is declared. moment it is declared. This is to protect against using variables This is to protect against using variables
whose values are undetermined.whose values are undetermined.
Initializing VariablesInitializing Variables Example: the variables are initialized as Example: the variables are initialized as
they are declared:they are declared:
public static void main(String[] args){
// declaring variablesint studentNumber = 100;double score = 50.8;char letterGrade = 'D';
}
Arithmetic OperatorsArithmetic Operators
We can use arithmetic operators in We can use arithmetic operators in our assignment statements.our assignment statements.
The Java arithmetic operators are:The Java arithmetic operators are: addition, +addition, + (integer and floating-point)(integer and floating-point) subtraction, -subtraction, - (integer and floating-(integer and floating-
point)point) multiplication, * multiplication, * (integer and floating-point)(integer and floating-point) division, / division, / (integer and floating-point) (integer and floating-point) modulus, %modulus, % (integer division to find remainder)(integer division to find remainder)
Arithmetic OperatorsArithmetic Operators
Example: using the + operatorExample: using the + operatorpublic static void main(String[] args){
// declaring two integer variablesint num1 = 5, num2 = 8;
// declaring a variable to store the totalint total;
// performing addition:total = num1 + num2;
// display resultSystem.out.println(“total = “ + total);
}
Arithmetic ExpressionsArithmetic ExpressionsMore examples of expressions:More examples of expressions:public static void main(String[] args){
// declaring variablesint num1 = 5, num2 = 8; int quotient, remainder;double total, average;
// performing arithmetic:total = num1 + num2;average = total / 2; // floating-point division
quotient = num1 / num2; //integer divisionremainder = num1 % num2;
// how to display the results?}
Operator PrecedenceOperator Precedence
Operators follow Operators follow precedence rulesprecedence rules::Thus you should use parentheses ( ) Thus you should use parentheses ( )
where necessary.where necessary.Generally according to algebraic Generally according to algebraic
rules:rules:( ) , * , / , % , + , -( ) , * , / , % , + , -
Operator PrecedenceOperator Precedence
Example:Example:The expressionsThe expressions
3 + 5 * 5 will evaluate to 283 + 5 * 5 will evaluate to 28(3 + 5) * 5 will evaluate to 40(3 + 5) * 5 will evaluate to 40
Assignment CompatibilitiesAssignment CompatibilitiesIn an assignment statement, you In an assignment statement, you
can assign a value of one type can assign a value of one type into another type:into another type:int iVariable = 6;double dblVariable;dblVariable = iVariable; // assigning int to double
Assignment CompatibilitiesAssignment CompatibilitiesHowever, you can not directly However, you can not directly
assign a double into an intassign a double into an intdouble dblVariable = 6.75; int iVariable;iVariable = dblVariable;
// assigning double to intCompiler error! Possible loss of precision
Type CastingType CastingGenerally, you can only assign a Generally, you can only assign a
type to the type appearing further type to the type appearing further down the list:down the list:byte > short > int > long > float > doublebyte > short > int > long > float > double
However, if you wish to change a However, if you wish to change a doubledouble type to an type to an intint, you must use , you must use type castingtype casting
Type Casting: ExampleType Casting: Example
The value of iVariable is now 6The value of iVariable is now 6The value of The value of dblVariabledblVariable is truncated is truncated
and assigned to and assigned to iVariableiVariable..The value of The value of dblVariabledblVariable remains remains
6.756.75
double dblVariable = 6.75; int iVariable;iVariable = (int) dblVariable;
// assigning double to int by typecasting
Sample ProgramSample ProgramLet's have a look at the following Let's have a look at the following
program. What does it do?program. What does it do?public class SimpleMaths{
public static void main (String[] args){
int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;
sum = num1 + num2;diff = num1 - num2;product = num1 * num2;quotient = num1 / num2;remainder = num1 % num2;
}}
Displaying outputDisplaying output
We must use display the results We must use display the results obtainedobtained
public class SimpleMaths{
public static void main (String[] args){
int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;diff = num1 - num2;… System.out.println(sum);System.out.println(diff);// etc
}}
displays the value stored in the variable sum
Displaying outputDisplaying output However, we should always make our However, we should always make our
output meaningful and clear.output meaningful and clear.public class SimpleMaths{
public static void main (String[] args){
int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;…
System.out.println("The sum is");System.out.println(sum);// etc
}}
Displaying outputDisplaying outputWe can use the System.out.print() We can use the System.out.print()
method:method:public class SimpleMaths{
public static void main (String [] args){
int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;…
System.out.print("The sum is ");System.out.println(sum);// etc
}}
Displaying outputDisplaying output
We can combine Strings and data using We can combine Strings and data using the concatenation operator +the concatenation operator +
public class SimpleMaths{
public static void main (String [] args){
int num1 = 5, num2 = 6;int sum, diff, product, quotient, remainder;sum = num1 + num2;…
System.out.print("The sum is " + sum);
// etc}
}
Concatenation + Concatenation +
The symbol '+' has two meanings in The symbol '+' has two meanings in JavaJavaAddition plus, which adds two numbersAddition plus, which adds two numbersConcatenation plus, which joins Strings Concatenation plus, which joins Strings
or text together.or text together.
Concatenation + Concatenation +
'+' will be used for '+' will be used for additionaddition if: if:both operands are numericboth operands are numeric
System.out.println(8 + 6);System.out.println(17.5 + 4);
System.out.println("8" + 6);System.out.println(8 + "6”)System.out.println("8" + "6”)System.out.println("The answer is " + 14);System.out.println("The answer is " + 8 + 6);
'+' will be used to '+' will be used to concatenateconcatenate if: if:if either operand is a String or textif either operand is a String or text
ExerciseExercise
Write a Java program that sets the Write a Java program that sets the values of three integer-valued values of three integer-valued assignment scores and then assignment scores and then calculates and displays:calculates and displays:the total of the three scoresthe total of the three scoresthe average of the three scoresthe average of the three scores
ExerciseExercise What is wrong with the following program?What is wrong with the following program?
public class countAvg{
public static void main (String[] args){
int score1, score2;double average = 0.0;score1 = 56;score2 = 73;average = score1 + score2 / 2System.out.print("The average of ");System.out.print(score1);System.out.print("and");System.out.println(score2);System.out.println("is " + average);
}}
The The CharChar data type data typeAnother primitive data type is Another primitive data type is charcharThe The charchar data type can hold values of data type can hold values of
the following character literals:the following character literals:the letters of the alphabet, eg.: the letters of the alphabet, eg.: 'A', 'b''A', 'b'the digits, eg. : the digits, eg. : '0' , '3''0' , '3'other special symbols, eg.: other special symbols, eg.: '(', '&', '+' '(', '&', '+' the null (empty) character: the null (empty) character: ''''
The The CharChar data type data type Invalid character literals:Invalid character literals:
"a""a" – this is a string – this is a string'aB''aB' – these are two characters – these are two characters'''''' – three consecutive single quotes: – three consecutive single quotes:
what does it mean?what does it mean?
Escape SequenceEscape Sequence
Sometimes it is necessary to Sometimes it is necessary to represent symbols:represent symbols:which already have special meanings in which already have special meanings in
the Java language, such as ' or "the Java language, such as ' or "other characters such as a tab or return.other characters such as a tab or return.
Escape SequenceEscape Sequence
The escape sequence character \ is The escape sequence character \ is used in this case.used in this case.'\'' '\'' to represent the single quote to represent the single quote
charactercharacter'\"' '\"' to represent the double quote to represent the double quote
charactercharacter'\\' '\\' to represent a backslash to represent a backslash
character. character. '\t''\t' to represent a tab to represent a tab'\n''\n' to create a new line to create a new line
ExerciseExercise
Write a program that will display Write a program that will display the following:the following:She said "Hello!" to me!She said "Hello!" to me!
The The StringString Data Type Data Type
A A String String type is an example of a type is an example of a reference data type.reference data type.
A string is defined as a sequence of A string is defined as a sequence of characters.characters.
The The StringString Data Type Data Type
Examples of String literals:Examples of String literals:" " (space, not the character ' ')" " (space, not the character ' ')"" (empty String)"" (empty String)"a""a""HELLO" "HELLO" "This is a String""This is a String""\tThis is also a String\n""\tThis is also a String\n"
Declaring a StringDeclaring a String
Strings can be used to store names, Strings can be used to store names, titles, etc.titles, etc.
We can declare a String data type by We can declare a String data type by giving it a variable name:giving it a variable name: String name;String name;
We can also initialize the variable We can also initialize the variable upon declaration:upon declaration: String subjectCode = “BIT106”;String subjectCode = “BIT106”;
ExerciseExerciseWrite a program to print out the Write a program to print out the
following, using String variables:following, using String variables:Subject code: BIT106Subject code: BIT106Subject name: Java ProgrammingSubject name: Java ProgrammingStudent name: Lee Ah YewStudent name: Lee Ah YewAssignment 1 Score (out of 25): 24.0 Assignment 1 Score (out of 25): 24.0 Assignment 2 Score (out of 25): 23.5Assignment 2 Score (out of 25): 23.5Exam Raw Score (out of 50) : 48.90Exam Raw Score (out of 50) : 48.90
Lee Ah Yew's Total Score for BIT106 (Java Lee Ah Yew's Total Score for BIT106 (Java Programming): 96.40 Programming): 96.40
Keyboard InputKeyboard Input
Java 5.0 has reasonable facilities for Java 5.0 has reasonable facilities for handling keyboard input.handling keyboard input.
These facilities are provided by the These facilities are provided by the ScannerScanner class in the class in the java.utiljava.util package.package.A A packagepackage is a library of classes. is a library of classes.
Using the Scanner ClassUsing the Scanner Class
Near the beginning of your program, insertNear the beginning of your program, insert
import java.util.*import java.util.* Create an object of the Create an object of the ScannerScanner class class
Scanner sc = new Scanner Scanner sc = new Scanner (System.in)(System.in)
Read data (an Read data (an intint or a or a doubledouble, for , for example)example)
int n1 = sc.nextInt();int n1 = sc.nextInt();
double d1 = sc.nextDouble();double d1 = sc.nextDouble();
Keyboard Input DemonstrationKeyboard Input Demonstration
class ScannerDemoclass ScannerDemo
Some Some ScannerScanner Class Methods Class Methods
syntaxsyntax
Int_Variable = Object_NameInt_Variable = Object_Name.nextInt();.nextInt();
Double_Variable = Double_Variable = Object_NameObject_Name.nextDouble();.nextDouble();
String_Variable = Object_NameString_Variable = Object_Name.next();.next();
String_Variable = Object_NameString_Variable = Object_Name.nextLine();.nextLine();
Remember to prompt the user for Remember to prompt the user for input, e.g.input, e.g.System.out.print(“Enter an integer: “);System.out.print(“Enter an integer: “);
Interactive InputInteractive InputYou should always You should always promptprompt the user the user
when obtaining data:when obtaining data:
Please enter your name: Sandy Lim
Please enter your age: 25
Please enter your score: 87.9Please enter your grade: A
ExerciseExercise
Write a program that asks the user to Write a program that asks the user to enter the name of an item, the price enter the name of an item, the price and the quantity purchased. The and the quantity purchased. The program must calculate the total price program must calculate the total price and display the following:and display the following:
ItemItem UnitUnit QtyQty Total Total
widget widget RM5.30RM5.30 1010 RM53.00 RM53.00
PseudocodePseudocode When we want to write a computer When we want to write a computer
program, we should always:program, we should always: ThinkThink PlanPlan CodeCode
We can write out our planning using We can write out our planning using pseudocodepseudocode – writing out the steps in – writing out the steps in simple English and not strict programming simple English and not strict programming language syntax.language syntax.
DocumentationDocumentation
A computer programmer generally spends A computer programmer generally spends more time more time readingreading and modifying and modifying programs than writing new ones.programs than writing new ones.
It is therefore important that your It is therefore important that your programs are documented:programs are documented: clearlyclearly neatlyneatly meaningfullymeaningfully
DocumentationDocumentation
You should always precede your program You should always precede your program with:with: Your nameYour name The dateThe date The purpose of the programThe purpose of the program
CommentsComments
Comments are used to:Comments are used to:Insert documentationInsert documentationClarify parts of code which may be Clarify parts of code which may be
complex.complex.Comments are ignored by the Comments are ignored by the
compiler but are useful to humans.compiler but are useful to humans.
CommentsComments
The symbols // are used to indicate that The symbols // are used to indicate that the rest of a line are comments.the rest of a line are comments.
If comments span more than one line, the If comments span more than one line, the symbols /* and */ can be used, eg.:symbols /* and */ can be used, eg.:/* this is the beginning of the documented /* this is the beginning of the documented comments and it only ends here */comments and it only ends here */
Variable namesVariable names
Variable names shoud:Variable names shoud:follow the Java rulesfollow the Java rulesbe be meaningfulmeaningful
For example, For example, namename, , score, totalBeforeTaxesscore, totalBeforeTaxesYou should almost never use names likeYou should almost never use names likea, b, ca, b, c
Variable namesVariable names
By convention:By convention:variable names start with a lowercase variable names start with a lowercase
letterletterclass names start with an uppercase class names start with an uppercase
letter, eg. letter, eg. String, ScannerString, Scanner
IndentationIndentation
Programs are also Programs are also indentedindented for for clarityclarity
Indentation shows the levels of Indentation shows the levels of nesting for the program.nesting for the program.public class CalcCircle
{public static void main(String[] args){
int radius; // radius - variablefinal double PI = 3.14159; // PI - constants
radius = 10;double area = PI * radius * radius;double circumference = 2 * PI * radius;
}}
ExerciseExercise
Write a program that asks the user Write a program that asks the user for their name and the year they for their name and the year they were born. Then display their age were born. Then display their age this year.this year.What is your name? KellyWhat is your year of birth? 1982Wow, Kelly, this year you will be 21 years old!
ExerciseExercise
Write a program that asks the user to Write a program that asks the user to enter the length and width of a enter the length and width of a rectangle and then display:rectangle and then display:the area of the rectanglethe area of the rectanglethe perimeter of the rectanglethe perimeter of the rectangle
The Math class: We can use pre-defined methods from The Math class: We can use pre-defined methods from the Math class to perform calculations.the Math class to perform calculations.
ExerciseExercise Write a Java program that asks the user to enter Write a Java program that asks the user to enter
two numbers, then:two numbers, then: find the absolute value of each of the numbers;find the absolute value of each of the numbers; determine which absolute value is largerdetermine which absolute value is larger find the square root of the larger of the two absolute find the square root of the larger of the two absolute
valuesvaluesSample run:Sample run:Enter first number: Enter first number: -36-36Enter second number: Enter second number: 55The absolute values of the two numbers are 36 and 5The absolute values of the two numbers are 36 and 5The larger absolute value is 36The larger absolute value is 36The square root of 36 is 6.0The square root of 36 is 6.0
Catch-up ExerciseCatch-up Exercise
Write a Java program that asks the Write a Java program that asks the user to enter a double number. Then user to enter a double number. Then display:display:the square root of the number.the square root of the number.
Now test the program with the values:Now test the program with the values:39.439.4-30-30
We want to be able to make sure that We want to be able to make sure that the user cannot enter negative values!the user cannot enter negative values!