Download public static void main(String[ ] args) - E

Document related concepts
no text concepts found
Transcript
Introduction to JAVA
PROGRAMMING STEPS

ANALISA MASALAHNYA




INPUT-NYA APA SAJA?
ALGORITMA PROSESNYA BAGAIMANA?
OUTPUT-NYA APA?
KETIK SOURCE CODE-NYA
HEADER FILES import < library >
 GLOBAL SECTIONS  VARIABEL GLOBAL, FUNGSI BANTU
 MAIN SECTIONS  VARIABEL LOKAL, INPUT, PROSES, OUTPUT

COMPILE & RUN PROGRAMNYA  ADA ERROR ?
 TES HASILNYA  SUDAH BENAR ?
 BUAT ARSIP/ DOKUMENTASINYA

Computers and Programming
A computer is a machine that can process data
by carrying out complex calculations quickly.
 A program is a set of instructions for the
computer to execute.
 A program can be high-level (easy for humans
to understand) or low-level (easy for the
computer to understand).
 In any case, programs have to be written
following a strict language syntax.

Running a Program

Typically, a program source code has to be
compiled into machine language before it can be
understood by a computer.
writes
void test()
{
println(“Hi”);
}
source code (high level)
programmer
compiler
machine
language
Hi
executed by
object code (low level)
computer
Portability

Different makes of computers


speak different “languages” (machine language)
use different compilers.
This means that object code produced by one
compiler may not work on another computer of
a different make.
 Thus the program is not portable.
 Java is portable because it works in a different
way.

History of Java
The Java programming language was
developed at Sun Microsystems
 It is meant to be a portable language that
allows the same program code to be run
on different computer makes.
 Java program code is translated into bytecode that is interpreted into machine
language that the computer can
understand.

Java Byte-Code





Java source code is compiled by the Java
compiler into byte-code.
Byte-code is the machine language for a ‘typical’
computer.
This ‘typical’ computer is known as the Java
Virtual Machine.
A byte-code interpreter will translate byte-code
into object code for the particular machine.
The byte-code is thus portable because an
interpreter is simpler to write than a compiler.
Running a Java Program
writes
programmer
public void test()
{
System.out.println(“Hi”);
}
Java source code (high level)
Java
compiler
Java byte-code
Extra step that
allows for
portability
Byte-code
interpreter
Machine
language
Hi
executed by
object code (low level)
computer
Types of Java Programs

Console Applications:
 Simple
text input / output
 This is what we will be doing for most of this
course as we are learning how to program.
public class ConsoleApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Types of Java Programs

import
GUI Applications:
 Using
the
Java
Swing
library
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 Programs

Applets
 To
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 Program
public class CalcCircle
{
public static void main(String[ ] args)
{
int radius;
// radius - variable
final double PI = 3.14159;
// PI - constants
radius = 10;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
System.out.println(”For a circle with radius ” + radius + ”,”);
System.out.print(”The circumference is ” + circumference);
System.out.println(” and the area is ” + area);
}
}
Elements of a Java Program

A Java Program is made up of:
 Identifiers:
 variables
 constants
 Literal
values
 Data types
 Operators
 Expressions
Identifiers

The identifiers in the previous program
identifier indicating name of the program
consist of:
(class name)
public class CalcCircle
{
public static void main(String[] args)
{
int radius;
// radius - variable
final double PI = 3.14159;
// PI - constants
…
identifier
to store the
} value of radius
}
(variable)
identifier to store the
fixed value of PI
(constant)
Data Types

Data types indicate the type of storage
required.
public class CalcCircle
{
public static void main(String[ ] args)
PI is a floating-point (double) value
{
int radius;
// radius - variable
final double PI = 3.14159;
// PI - constants
}
}
… is an integer (int) value
radius
Literal values

Literals are the actual values stored in
variables or used in calculations.
public class CalcCircle
{
public static void main(String[ ] args)
the variable radius stores the value 10
{
…
radius = 10;
…
}
}
Operators and Expressions

Operators allow us to perform some calculations
on the data by forming expressions.
public class CalcCircle
An expression is formed
{
public static void main(String[ ] args) using
{
operators and operands
…
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
…
}
The multiplication operator (*) is
}
used to calculate the area
Java Program Structure

For the next few weeks, our Java programs
will have the following structure:
The program is a class definition
– use the same name as the filename.
ie. Save this file as CalcCircle.java
public class CalcCircle
{
public static void main(String[ ] args)
{
Your program must have a main
// This section consists of
method – it will start execution
// program code consisting of
from here.
// of Java statements
//
}
Curly braces indicate where sections begin and end.
}
You should indent your code for clarity.
Displaying Output

For console applications, we use the
System.out object to display 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 parentheses
will be output to the screen.
Compiling and Running
The preceding source code must be saved as
CalcCircle.java
 You must then use the Java Development Kit
(JDK) to compile the program using the
command
javac CalcCircle.java
 The byte-code file CalcCircle.class will be
created by the compiler if there are no errors.
 To run the program, use the command
java CalcCircle

Compiling and Runnng
Buttons to
compile and
run the
program
Anatomy of a Java Class

A Java console application must consist of one class
that has the following structure:
/* This is a sample program only.
Written by:
Date:
*/
class header
public class SampleProgram
{
public static void main(String [] args)
{
int num1 = 5;
// num stores 5
System.out.print("num1 has value ");
System.out.println(num1);
}
}
main
method
Anatomy of a Java Class

A Java console application must consist of one class
that has the following structure:
/* This is a sample program only.
Written by:
multi-line comments
Date:
*/
name of the class
public class SampleProgram
{
public static void main(String [] args)
{
in-line
statements
int num1 = 5;
// num stores 5
comments
System.out.print("num1 has value ");
to be
System.out.println(num1);
executed
}
}
What is the result of execution?
public class CalcCircle
{
public static void main(String[ ] args)
{
int radius;
// radius - variable
final double PI = 3.14159;
// PI - constants
radius = 10;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
System.out.println(”For a circle with radius ” + radius + ”,”);
System.out.print(”The circumference is ” + circumference);
System.out.println(” and the area is ” + area);
}
}
Displaying output

There are some predefined classes in Java that
we can use for basic tasks such as:


reading input
displaying output
We use the System class to display output to
the screen for console applications.
 System.out is an object that provides methods
for displaying strings of characters to the
console screen.


The methods we can use are print and println.
Example

Write a program that prints two lines:
I love Java Programming
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 Println
What if you use System.out.print()
instead?
 System.out.println() advances the cursor
to the next line after displaying the
required output.
 If you use System.out.print(), you might
need to add spaces to format your output
clearly.

Examples
Code Fragment
Output Displayed
System.out.println("First line");
System.out.println("Second line");
First line
Second line
System.out.print("First line");
System.out.print("Second line");
First lineSecond line
Exercise

Write a Java program that displays your
name and your studentID.
// Sandy Lim
// Lecture 1
// Printing name and student ID
public class Information
{
public static void main (String[] args)
{
// your code here
}
}
Exercise

Write a Java program that prints out to
the screen the following tree:
// Sandy Lim
*
// Lecture 1
// Printing a tree using *
***
public class tree
{
*****
public static void main (String[]
*******
{
// your code here
**
}
}
**
args)
Reminders
Get your computer accounts before next
week's tutorial so that you can start
programming ASAP.
 Download JCreatorLE and J2SDK1.5.0, you
can access both through the JCreator
(3.50LE) website:
http://www.jcreator.com/download.htm

Data Types, Variables &
Operators
Memory and Data
One of the most important components of a
computer system is the memory.
 A computer’s memory holds:

 data
that is to be processed
 data that is the result of some processing
We can imagine that a computer’s memory
consists of boxes to hold data.
 However, the sizes of the boxes would
depend on the type of data that is held.

Identifiers
We have to give names to the boxes we
are using to store data.
 These names are called variable names,
or identifiers.
 The actual data is the literal value of the
identifier.

BIT106
The box is identified as
subject and it stores the
value “BIT106”
subject
value of subject
identifier / variable name
Java Spelling Rules

An identifier can consist of:
 letters
(A – Z, a – z)
 digits (0 to 9)
 the characters _ and $

The first character cannot be a digit.
Identifier Rules
A single identifier must be one word only
(no spaces) of any length.
 Java is case-sensitive.
 Reserved Words cannot be identifiers.

 These
are words which have a special
meaning in Java
Examples

Examples of identifiers
num1 num2
first_name lastName
numberOfStudents accountNumber
myProgram MYPROGRAM

Examples of reserved words
public
if
int double
 see Appendix 1 in the text book for others.

Illegal identifiers
3rdValuemy program
this&that
Exercise

Which of the following are valid identifier names?
 my_granny’s_name
 joesCar
 integer
 2ndNum
 Child3




double
third value
mid2chars
PUBLIC
Types of Data
What kind of data can be collected for use in a
computer system?
 Consider data on:

College application form
 Student transcript
 Role Playing Game (RPG)

Types of Data

We typically want to collect data which may be
numeric
 characters
 Strings
 choice (Y/N)

Java Data Types





In order to determine the sizes of storage (boxes) required to
hold data, we have to declare the data types of the
identifiers used.
Integer data types are used to hold whole numbers
 0, -10, 99, 1001
The Character data type is used to hold any single character
from the computer keyboard
 '>', 'h', '8'
Floating-point data types can hold numbers with a decimal
point and a fractional part.
 -2.3, 6.99992, 5e6, 1.5f
The Boolean data type can hold the values true or false.
Primitive vs
Reference Data Types

A data type can be a:
 Primitive
type
 Reference type (or Class type)
Primitive vs Reference Data Types

A Primitive type is one that holds a simple,
indecomposable value, such as:
a
single number
 a single character

A Reference type is a type for a class:
 it
can hold objects that have data and
methods
Java Primitive Data Types

There are 8 primitive data types in Java
Type name
Kind of value
Memory used
byte
integer
1 byte
short
integer
2 bytes
int
integer
4 bytes
long
integer
8 bytes
float
floating-point number
4 bytes
double
floating-point number
8 bytes
char
single character
2 bytes
boolean
true or false
1 bit
Declaring variables

When we want to store some data in a
variable,
 we
must first declare that variable.
 to prepare memory storage for that data.

Syntax:
Type VariableName;
Declaring variables

Examples:
 The
following statements will declare
 an
integer variable called studentNumber to store
a student number:
 a double variable to store the score for a student
 a character variable to store the lettergrade
public static void main(String[] args)
{
// declaring variables
int studentNumber;
double score;
char letterGrade;
Assignment Statements
Once we have declared our variables, we can
use the variables to hold data.
 This is done by assigning literal values to the
variables.
 Syntax (for primitive types):

VariableName = value;

This means that the value on the right hand side is
evaluated and the variable on the left hand side is
set to this value.
Assignment Statements

Examples:

Setting the student number, score and lettergrade for the
variables declared earlier:
public static void main(String[] args)
{
// declaring variables
int studentNumber;
double score;
char letterGrade;
// assigning values to variables
studentNumber = 100;
score = 50.8;
letterGrade = 'D';
}
Initializing Variables
We may also initialize variables when declaring
them.
 Syntax:

Type VariableName = value;
This will set the value of the variable the
moment it is declared.
 This is to protect against using variables whose
values are undetermined.

Initializing Variables

Example: the variables are initialized as they are
declared:
public static void main(String[] args)
{
// declaring variables
int studentNumber = 100;
double score = 50.8;
char letterGrade = 'D';
}
Arithmetic Operators
We can use arithmetic operators in our
assignment statements.
 The Java arithmetic operators are:

addition, +
(integer and floating-point)
 subtraction, (integer and floating-point)
 multiplication, *
(integer and floating-point)
 division, /
(integer and floating-point)
 modulus, %
(integer division to find remainder)

Arithmetic Operators

Example: using the + operator
public static void main(String[] args)
{
// declaring two integer variables
int num1 = 5, num2 = 8;
// declaring a variable to store the total
int total;
// performing addition:
total = num1 + num2;
// display result
System.out.println(“total = “ + total);
}
Arithmetic Expressions

More examples of expressions:
public static void main(String[] args)
{
// declaring variables
int 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 division
remainder = num1 % num2;
// how to display the results?
}
Operator Precedence
Operators follow precedence rules:
 Thus you should use parentheses ( )
where necessary.
 Generally according to algebraic rules:

(
),*,/,%,+,-
Operator Precedence
Example:
 The expressions

3
+ 5 * 5 will evaluate to 28
 (3 + 5) * 5 will evaluate to 40
Assignment Compatibilities
 In
an assignment statement, you can
assign a value of one type into
another type:
int iVariable = 6;
double dblVariable;
dblVariable = iVariable; // assigning int to double
Assignment Compatibilities
 However,
you can not directly assign
a double into an int
double dblVariable = 6.75;
int iVariable;
iVariable = dblVariable;
// assigning double to int
Compiler error! Possible loss of precision
Type Casting
 Generally,
you can only assign a type
to the type appearing further down the
list:
byte > short > int > long > float > double

However, if you wish to change a double
type to an int, you must use type casting
Type Casting: Example
double dblVariable = 6.75;
int iVariable;
iVariable = (int) dblVariable;
// assigning double to int by typecasting

The value of iVariable is now 6
 The
value of dblVariable is truncated and
assigned to iVariable.

The value of dblVariable remains 6.75
Sample Program

Let's have a look at the following
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 output

We must use display the results obtained
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);
displays the
System.out.println(diff);
value stored in
// etc
the variable
}
sum
}
Displaying output

However, we should always make our 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 output

We can use the System.out.print()
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 output

We can combine Strings and data using 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 +

The symbol '+' has two meanings in Java
 Addition
plus, which adds two numbers
 Concatenation plus, which joins Strings or text
together.
Concatenation +

'+' will be used for addition if:
 both
operands are numeric
System.out.println(8 + 6);
System.out.println(17.5 + 4);

'+' will be used to concatenate if:
 if
either operand is a String or text
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);
Exercise

Write a Java program that sets the values
of three integer-valued assignment scores
and then calculates and displays:
 the
total of the three scores
 the average of the three scores
Exercise

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 / 2
System.out.print("The average of ");
System.out.print(score1);
System.out.print("and");
System.out.println(score2);
System.out.println("is " + average);
}
}
The Char data type
Another primitive data type is char
 The char data type can hold values of the
following character literals:

 the
letters of the alphabet, eg.: 'A', 'b'
 the digits, eg. : '0' , '3'
 other special symbols, eg.: '(', '&', '+'
 the null (empty) character: ''
The Char data type

Invalid character literals:
– this is a string
 'aB' – these are two characters
 ''' – three consecutive single quotes:
 "a"
 what
does it mean?
Escape Sequence

Sometimes it is necessary to represent
symbols:
 which
already have special meanings in the
Java language, such as ' or "
 other characters such as a tab or return.
Escape Sequence

The escape sequence character \ is used
in this case.
to represent the single quote character
 '\"' to represent the double quote
character
 '\\' to represent a backslash character.
 '\t' to represent a tab
 '\n' to create a new line
 '\''
Exercise
 Write
a program that will display the
following:
 She
said "Hello!" to me!
The String Data Type
A String type is an example of a
reference data type.
 A string is defined as a sequence of
characters.

The String Data Type

Examples of String literals:
"
" (space, not the character ' ')
 "" (empty String)
 "a"
 "HELLO"
 "This is a String"
 "\tThis is also a String\n"
Declaring a String
Strings can be used to store names, titles,
etc.
 We can declare a String data type by
giving it a variable name:
String name;
 We can also initialize the variable upon
declaration:

String subjectCode = “BIT106”;
Exercise

Write a program to print out the following,
using String variables:
Subject code: BIT106
Subject name: Java Programming
Student name: Lee Ah Yew
Assignment 1 Score (out of 25): 24.0
Assignment 2 Score (out of 25): 23.5
Exam Raw Score (out of 50) : 48.90
Lee Ah Yew's Total Score for BIT106 (Java
Programming): 96.40
Keyboard Input
Java 5.0 has reasonable facilities for
handling keyboard input.
 These facilities are provided by the
Scanner class in the java.util
package.
 A package is a library of classes.

Using the Scanner Class

Near the beginning of your program, insert
import java.util.*
Create an object of the Scanner class
Scanner sc = new Scanner (System.in)
 Read data (an int or a double, for example)
int n1 = sc.nextInt();
double d1 = sc.nextDouble();

Keyboard Input Demonstration

class ScannerDemo
Some Scanner Class Methods

syntax
Int_Variable = Object_Name.nextInt();
Double_Variable =
Object_Name.nextDouble();
String_Variable = Object_Name.next();
String_Variable = Object_Name.nextLine();

Remember to prompt the user for input,
e.g.
System.out.print(“Enter an integer: “);
Interactive Input

You should always prompt the user when
obtaining data:
Please enter your name: Sandy Lim
Please enter your age: 25
Please enter your score: 87.9
Please enter your grade: A
Exercise

Write a program that asks the user to enter
the name of an item, the price and the
quantity purchased. The program must
calculate the total price and display the
following:
Item
widget
Unit
RM5.30
Qty
10
Total
RM53.00
Pseudocode

When we want to write a computer program, we
should always:




Think
Plan
Code
We can write out our planning using pseudocode
– writing out the steps in simple English and not
strict programming language syntax.
Documentation
A computer programmer generally spends more
time reading and modifying programs than
writing new ones.
 It is therefore important that your programs are
documented:




clearly
neatly
meaningfully
Documentation

You should always precede your program with:



Your name
The date
The purpose of the program
Comments

Comments are used to:
 Insert
documentation
 Clarify parts of code which may be complex.

Comments are ignored by the compiler
but are useful to humans.
Comments
The symbols // are used to indicate that the rest
of a line are comments.
 If comments span more than one line, the
symbols /* and */ can be used, eg.:

/* this is the beginning of the documented
comments and it only ends here */
Variable names

Variable names shoud:
 follow
the Java rules
 be meaningful

For example,
name, score, totalBeforeTaxes
 You
should almost never use names like
a, b, c
Variable names

By convention:
 variable
names start with a lowercase letter
 class names start with an uppercase letter, eg.
String, Scanner
Indentation
Programs are also indented for clarity
 Indentation shows the levels of nesting for
the program.

public class CalcCircle
{
public static void main(String[] args)
{
int radius;
// radius - variable
final double PI = 3.14159;
// PI - constants
radius = 10;
double area = PI * radius * radius;
double circumference = 2 * PI * radius;
}
}
Exercise

Write a program that asks the user for
their name and the year they were born.
Then display their age this year.
What is your name? Kelly
What is your year of birth? 1982
Wow, Kelly, this year you will be 21 years old!
Exercise

Write a program that asks the user to
enter the length and width of a rectangle
and then display:
 the
area of the rectangle
 the perimeter of the rectangle
The Math class: We can use pre-defined methods from
the Math class to perform calculations.
Exercise

Write a Java program that asks the user to enter two
numbers, then:
find the absolute value of each of the numbers;
 determine which absolute value is larger
 find the square root of the larger of the two absolute values
Sample run:
Enter first number: -36
Enter second number: 5
The absolute values of the two numbers are 36 and 5
The larger absolute value is 36
The square root of 36 is 6.0

Catch-up Exercise

Write a Java program that asks the user to
enter a double number. Then display:
 the

square root of the number.
Now test the program with the values:
 39.4
 -30

We want to be able to make sure that the
user cannot enter negative values!