Java/C# Syntax Continued Proper Object definition will be used

advertisement

Java/C# Syntax Continued Proper Object definition will be used

CSA 1012-Joseph Cordina (C) 1

Precedence

• If two or more operators occur together, the compiler uses precedence to determine order of execution • Java’s precedence rules are similar to other programming languages • For example, multiplication and division have higher precedence than addition and subtraction: – 2+3*5 /* evaluates to 17 */ – (2+3)*5 / evaluates to 25 */ – 2+(3*5) /* evaluates to 17 */ • Extra parentheses are harmless and make the expression more readable: – X = new Integer((5*7)+((8*3)/15)) 2 CSA 1012-Joseph Cordina (C)

Precedence (Con’t)

• Other noteworthy precedence rules – arithmetic operators take precedence over relational, so the following is correct: Boolean inBounds = new Boolean(5 < 7 – 1);

The above is bad programming practice

• Relational operators take precedence over the bitwise logical operators, so the parentheses are necessary in the following: – Boolean isZero= new Boolean( (5 & 0xff000 ) == 0); • Rule of thumb:when precedence is in doubt, use parentheses to specify order of execution 3 CSA 1012-Joseph Cordina (C)

Associativity

• Where two or more operators have equal precedence, associativity applies: – / and * have equal precedence and associate left to right: 6 / 2 * 3 has a value of (6/2) * 3, i.e. 9, not 6 / (2*3), i.e. 1 • “Right to left” associativity is more appropriate in other cases.

CSA 1012-Joseph Cordina (C) 4

Associativity (contd.)

• what would this do?

• Integer a,b; • a = b = new Integer(3); • assignment: • is a operator with right-to-left associativity • changes the left-hand argument’s value • produces a value for the next operation • this example creates an object with value 3 and makes b point to it • Produces the reference to the object, • The next assignment operator assigns the object reference into a, also produces the reference to the object (which is then thrown away) 5 CSA 1012-Joseph Cordina (C)

Function Calls

• A function call is another form of expression • Functions declared void do not return values • Functions declared other than void return values of the declared type • Examples: – Long t = currentTime(); where currentTime() returns Long – Double a = areaOfOval(8,7); where areaOfOval() returns Double • We will examine functions (methods) later on.

6 CSA 1012-Joseph Cordina (C)

Simple Statements

• Java/C# is an expression-based language: – expressions do the work but they must appear in the context of statements • A simple statement consists of an expression and a semi-colon: – the semi-colon is a required terminator • These are expressions: – a – i.intValue() * j.intValue() – z = new Integer(x.intValue() * 5) CSA 1012-Joseph Cordina (C) 7

Simple Statements (contd.)

• Assigned semi-colons turns expressions into statements: – a; – i.intValue() * j.intValue(); – z = new Integer( x.intValue() * 5); the first two are not legal and return errors with the JDK Java compiler In C# – a; – i*j; – z=x*5; - the third calculates a product, creates an object and stores it into z.

- You can distinguish a legal statement when you can answer in the positive the following question - does the statement have an after-effect when executed?

8 CSA 1012-Joseph Cordina (C)

Control Structures

• A control structure gives us the ability to make a decision and directs the flow of the program accordingly.

• Java uses several flow control structures.

• if statement (conditional) if (i.intValue() > 0) x = new Integer (y.intValue()*5); else //else part is optional x = NULL; • Indentation is important 9 CSA 1012-Joseph Cordina (C)

Loops

• A conditional loop is used when we wish to repeat a certain piece of code until a condition is met.

• The while loop is entered whenever a condition is met.

– while (i.intValue()<5) i=new Integer (i.intValue()+1); • The do-while loop is executed at least once and repeats whenever condition is true.

do a = new Integer ( a.intValue()+a.intValue()); while (a.intValue()<= 20/2); 10 CSA 1012-Joseph Cordina (C)

Complex Loops

• The for loop is a more complicated loop structure which is used as a short hand instead of the while loop. for (i=new Integer(0); i.intValue()<22; i=new Integer(i.intValue()+1)) a=new Integer( a.intValue() + 2); Pseudo-code initialise i to Integer with value0 continue only if i’s value < 22 do body of loop create new object with new value repeat test • in C# – for (i=0;i<22;i=i+1) a=a+2; • Note: – conditions must be of type Boolean • While goto exists in Java/C#, one should never use them and they have been proven to not be necessary apart from making unreadable code.

11 CSA 1012-Joseph Cordina (C)

Compound Statements

• • A compound statement lets us group multiple statements into a single statement: syntax: {

declarations or statements

} Compound statements are legal anywhere simple statements are legal, and vice versa CSA 1012-Joseph Cordina (C) 12

Compound Statements Contd.

• Allows us to use several statements where syntax would normally expect just one: if (a.intValue()

The switch Statement

• A switch statement is another control structure.

– A switch provides multiple entry points into a block – Follow the switch statement with the variable to be checked.

– Follow case statements with possible alternatives.

– End every case block with a break statement.

– default is optional and its block is always executed switch (i.intValue()) { case 1: case 2: [do something] break; //jump to [do more work] case 3:…[do something else, keep going] default: … [do yet more work] } … [do more work] 14 CSA 1012-Joseph Cordina (C)

The switch contd.

• execution jumps to the • case label that matches the control expression • to the default label if no match is found • beyond the switch if there is no match and no default • Execution continues to the end unless a branching statement is encountered: – break in a switch causes a jump to the end – break statements turn a switch into multiple choice • Omitting break ends up making every case statement to be true.

• Case expressions may be of type Character,Byte,Short, Integer or literal i.e., with value determinable at compile time CSA 1012-Joseph Cordina (C) 15

Local Variable Scope

• A local variable is a variable declared within a block of executable code • A local variable may be declared anywhere within a function or compound statement • A local variable is in scope: – from the point of its declaration – until the close of its block (compound statement) • There may be only one local variable of a given name within scope at one time 16 CSA 1012-Joseph Cordina (C)

Local Variable Scope (contd.)

{ } Integer x; Integer i; for (i = new Integer(0); i.intValue() < 60; i=new Integer(i.intValue()+1)) { Integer x; // error – two x’s!

Integer j; } for (i = new Integer(0); i.intValue() < 60; i=new Integer(i.intValue()+1)) { Integer j; // ok – prior j is out of scope } 17 CSA 1012-Joseph Cordina (C)

Simple Output

• Simple output can be programmed by making use of the built in System.out.println(variable) method/ System.Console.WriteLine(variable) – System.out.println(i.intvalue()) – System.Console.WriteLine(i) • This will print things to screen and skip a line • Various class-types can be inserted in the parameter list.

• System.out.print/ System.Console.Write also exists which does not skip a line.

• Example of formatted output: – Integer dx = new Integer(3); System.out.println(“Value is “+ dx.intValue()); – int dx = 3; System.Console.WriteLine(“Value is “+ dx.intValue()); This example uses the string concatenation operator (+) to print a string literal followed by the contents of an integer variable .

18 CSA 1012-Joseph Cordina (C)

Simple Input in Java

• While output is very easy in Java, input is not so easy due to complex file operations.

• One ‘easy’ way of doing it is as follows: – import javax.swing.*; at the beginning of your file.

Input a string by something like: – String num = JOptionPane.showInputDialog

(“Type your number ?”); which will bring up a pop up window with the request for a number.

– At the end of main add the statement System.exit(0); for a clean termination.

19 CSA 1012-Joseph Cordina (C)

Input in Java (contd.)

• Now we need to change the string into something we can use • Use one of the following functions to do the conversion Integer.parseInt(string) Float.parseFloat(string) Double.parseDouble(string) Byte.parseByte(string) Short.parseShort(string) Long.parseLong(string) string.charAt(index) Returns String as Integer literal Returns String as Float literal Returns String as Double literal Returns String as Byte literal Returns String as Short literal Returns String as Long literal Returns Character at specified index in string 20 CSA 1012-Joseph Cordina (C)

Input in Java(contd)

• Example of input: import javax.swing.*; import java.io.*; public class Input { public static void main(String args[]) { Integer num; Character c; String str = JOptionPane.showInputDialog

("What is your age"); num= new Integer(Integer.parseInt(str)); c = new Character(str.charAt(0)); System.out.println(num.intValue()); System.out.println( “First Character =“+c.charValue()); System.exit(0); } } CSA 1012-Joseph Cordina (C) 21

Simple Input in C#

• To input integers from keyboard use: Console.Read(); which returns an integer; • To read a whole line use Console.ReadLine(); which returns a string.

CSA 1012-Joseph Cordina (C) 22

Input in C# (contd.)

• Now we need to change the string into something we can use • Use one of the following functions to do the conversion int.Parse(string) float.Parse(string) double.Parse(string) byte.Parse(string) short.Parse(string) long.Parse(string) Returns String as Integer literal Returns String as Float literal Returns String as Double literal Returns String as Byte literal Returns String as Short literal Returns String as Long literal 23 CSA 1012-Joseph Cordina (C)

Input in C#(contd)

• Example of input: using System; class Input { static void Main(String args[]) { int num; String str; Console.Writeln(“What is your age “); str = Console.ReadLine(); num= int.Parse(str); Console.WriteLine(num); System.exit(0); } } CSA 1012-Joseph Cordina (C) 24

Quiz

1. What is the difference between: a) the boolean operators & and &&?

b) the integer right shift operators >> and >>>?

2. Find the compiler error in the following code: Integer x = new Integer(1); do { Integer half = new Integer(x.intValue(); x = new Integer( x.IntValue()*2); } while (half.intValue()<1024) ; 25 CSA 1012-Joseph Cordina (C)

Exercises

1. Create a program that prints one of the following two messages: - x is evenly divisible by y - x is not evenly divisible by y depending on whether the value of an object y evenly divides the value of object x in the DivTest class. 2. Modify your program to print the values of x and y instead of “x” and “y”. Test your program by setting various values for x and y, recompiling and running your program. What happens if you set the value of y to zero and run?

26 CSA 1012-Joseph Cordina (C)

Exercises

2. Create a file Adder.java/Adder.cs

and make it add the even numbers from 1 to 100 and then print each newly added value to screen.

3. Create a program which calculates the power of any number and prints it out on screen.

4. Create a file Triangle.java/Triangle.cs to create a triangle made up of asterisks on screen. Make use of loops to print the triangle.

5. Write a program which inputs 5 numbers from the user and then outputs their sum on screen.

6. Modify the above so that the program asks the user how many numbers will be input and then the program proceeds in inputting these numbers 27 CSA 1012-Joseph Cordina (C)

Download