Download Java Syntax

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Some basic I/O
Example of Output Stream
• Our first program involved the output
stream
• // First Program HelloWorld
• public class HelloWorld {
•
public static void main(String args []){
•
}
}
System.out.println(“Hello world...”):
System.out.println(“Hello
world...”):
•
•
•
•
•
System.out is called the standard output
object
This will display a line of text in the command
window
In Java , any source and destination for I/O
is considered a stream of bytes or
characters.
To perform output we insert bytes or
characters into a stream. To perform input
we extract bytes or characters from a
stream.
java.lang.System class contains three
predefined streams
•
•
•
System.out
System.err for errors
System.in
Consider
• System.in
System.in
• Standard input is this stream
• Some books refer to the input
method
• System.in.readln();
Problem
• System.in.readln() doesn’t seem to
work with system here
• Solution import the scanner class
Consider the following program
• // Second Program HelloWorld
• import java.util.Scanner;
• public class HelloWorld3 {
•
public static void main(String args []){
•
Scanner input = new Scanner( System.in );
•
String theName = input.nextLine();
•
System.out.println(“input was“ + theNAme);}}
It contains the lines
• // Second Program HelloWorld
• import java.util.Scanner;
• This imports an input Utility class called Scanner
•
Scanner input = new Scanner( System.in );
• This creates an instance called input of the
scanner utility
String theName = input.nextLine();
• This calls a method of the class called
nextLine()
• This gets input from the screen
• It binds this to a variable called
theName which is declared to be a
string type by the String Keyword
So now we have a basic input
method which seems to work
• Next we need to consider the basic
components of programs in order to
start building more complex
examples.
• We will start with basic syntax and
operators
Java Syntax
Primitive data types
Operators
Control statements
Primitive data types
• Identical across all computer platforms
 portable
Primitive data types
• char (16 bits) a Unicode character
• byte (8 bits)
• int (32 bits) a signed integer
• short (16 bits) a short integer
• long (64 bits) a long integer
Primitive data types
• float (32 bits) a real number
• double (64 bits) a large real number
• boolean (8 bits)
– values are true or false (keywords)
– cannot be converted to and from other data
types
e.g. while (i!=0) not while(i)
Primitive Data Types
Type
boolean
Size in bits
char
16
byte
8
short
16
int
32
long
64
float
32
double
64
Values
true or false
Standard
[Note: The representation of a boolean is
specific to the Java Virtual Machine on each
computer platform.]
'\u0000' to '\uFFFF'
(ISO Unicode character set)
(0 to 65535)
–128 to +127
(–27 to 27 – 1)
–32,768 to +32,767
(–215 to 215 – 1)
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
Negative range:
(IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
Negative range:
(IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
Operators
• Addition Subtraction
•
+ -
• Increment operators (postfix and prefix)
++ -• Multiplication Division Modulus
* / %
• Equality
== !=
• Assignment operators
= += -= *= /= %=
Arithmetic Operators
Operator(s)
*
/
%
+
-
Operation(s)
Multiplication
Division
Remainder
Addition
Subtraction
Order of evaluation (precedence)
Evaluated first. If there are several of this type
of operator, they are evaluated from left to
right.
Evaluated next. If there are several of this type
of operator, they are evaluated from left to
right.
Precedence of arithmetic operators.
Back to our simple input program
• Remember the last night we had a
program to input an integer,
manipulate it and output it.
We used
• input.nextLine(); Returns a String
• It would need to be converted if we
are to use this string as an integer
using the following parseInt method
•
Parsing Strings for integers
• Integer.parseInt(String s);
• The parseInt() function parses a
string and returns an integer.
Using our Scanner input method
• // Second Program HelloWorld
• import java.util.Scanner;
• public class HelloWorld4 {
•
public static void main(String args []){
•
Scanner input = new Scanner( System.in );
•
String theName = input.nextLine();
•
•
•
int num1 = Integer.parseInt(theName);
num1 = num1 + 1;
System.out.println("result" + num1);}}
Some anomalies
• Note the String declaration starts
with an Uppercase Letter
• And the int declaration starts with a
lowercase letter
String Contatenation anomaly
• Note we use the arithmetic operator
+ to increment num1 by 1
• We use the same notation + to
concatenate the result num1 to the
string result an example of operator
overloading which in turn is part of
polymorphism
Use of parseInt
• int num1 =
Integer.parseInt(theName);
• We use the method parseInt on the
string theName to produce our
integer num1
Exercise
• Write code to input 2 integers , add
them together and output the result.
Towards more complicated
programming
• Next Conditionals and Loops
• Now all Conditionals and Loops are
characterised by Conditions (called
guards in the case of Loops)
• Conditions are boolean expressions
largely based on relational operators
• Next we look at these operators
Operators
• Relational operators
< <= > >=
• Conditional operator
?:
Logical Operators
• Not
!
• Logical AND
&&
• Logical OR
||
• Boolean logical AND
&
• Boolean logical inclusive OR
|
• Boolean logical exclusive OR
^
(true if only one operand is true)
Relational Operators
Standard algebraic Java equality
Example
equality or
or relational
of Java
relational operator operator
condition
Equality operators
==
x == y
=
!=
x != y

Relational operators
>
x > y
>
<
x < y
<
>=
x >= y

<=
x <= y

Equality and relational operators.
Meaning of
Java condition
x is equal to y
x is not equal to y
x is greater than y
x is less than y
x is greater than or equal to y
x is less than or equal to y
If Statements
• Similar to C/C++ syntax:
• if statement
if (x != n){
…
}
else if {
…
}
else {
…
}
Example of Classic Conditional Program
• Consider our Leap Year program
• // Second Program HelloWorld
• import java.util.Scanner;
• public class Leapyear {
•
public static void main(String args []){
•
Scanner input = new Scanner( System.in );
•
String theName = input.nextLine();
•
int num1 = Integer.parseInt(theName);
•
if(num1 % 4 ==0 && (num1 % 100 != 0 ||num1 % 400 == 0))
•
System.out.println("leap");
•
else
•
System.out.println("not leap");
•
}}
Exercises
• Write javaclasses which will
• 1: Input two Integers and output the
largest
• 2 :Input 3 sides of a triangle and
determine whether the triangle is
scalene, isoceles or equilateral.
• 3 Input a month and a year and
calculate how many days are in that
month
Exercises continued
• Remember
• 30 days hath September , April ,
June and November,
• All the Rest have 31,
• Except February which has 28,
• save for one year in four
• When it has one day more
More Exercises
• An insurance company offers different
classes of insurance based on age
• Over 20 and less than 40 is Category A
• Between 40 and 60 is Category B
• Over 60 is Category C
• Write a program to accept in someones age
and tell them the class of insurance they
are entitled to.
Control Statements
• switch statement
switch (n){
case 1:
…
break;
case 2: case 3:
…
break;
default:
break;
};
Loop Statements
• for statement
for (int i=0; i<max; i++){
…
};
• while statement
while (x==n ){
…
};
• do statement
do {
…
} while( x<=y && x!=0);
General Points to Note
• Case sensitive
• Use lower case
– objects have capitalised first letter
Reserved Words
Java Keywords
abstract
assert
boolean
break
case
catch
char
class
default
do
double
else
final
finally float
for
implements import
instanceof int
long
native
new
package
protected public
return
short
strictfp
super
switch
synchronized
throw
throws
transient try
volatile
while
Keywords that are reserved, but not currently used
const
goto
byte
continue
extends
if
interface
private
static
this
void