some basic i/o
DESCRIPTION
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...”):. - PowerPoint PPT PresentationTRANSCRIPT
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
typese.g. while (i!=0) not while(i)
Primitive Data TypesType Size in bits Values Standard boolean true or false
[Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.]
char 16 '\u0000' to '\uFFFF' (0 to 65535)
(ISO Unicode character set)
byte 8 –128 to +127 (–27 to 27 – 1)
short 16 –32,768 to +32,767 (–215 to 215 – 1)
int 32 –2,147,483,648 to +2,147,483,647 (–231 to 231 – 1)
long 64 –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (–263 to 263 – 1)
float 32 Negative range: –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38
(IEEE 754 floating point)
double 64 Negative range: –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308
(IEEE 754 floating point)
Operators• Addition Subtraction• + - • Increment operators (postfix and prefix)
++ --
• Multiplication Division Modulus* / %
• Equality== !=
• Assignment operators= += -= *= /= %=
Arithmetic Operators
Operator(s) Operation(s) Order of evaluation (precedence) * /
%
Multiplication Division Remainder
Evaluated first. If there are several of this type of operator, they are evaluated from left to right.
+ -
Addition Subtraction
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 equality or relational operator
J ava equality or relational operator
Example of J ava condition
Meaning of J ava condition
Equality operators = == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y Equality and relational operators.
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
J ava Keywords abstract assert boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Keywords that are reserved, but not currently used const goto
Reserved Words