330 likes | 569 Views
Escape Sequences. <br> newline t tab b backspace carriage return ’ single quote ” double quote \ backslash. Typecasting. Typecasting allows you to take a value that belongs to one type and “cast” it into another type.
E N D
Escape Sequences • \n newline • \t tab • \b backspace • \r carriage return • \’ single quote • \” double quote • \\ backslash
Typecasting • Typecasting allows you to take a value that belongs to one type and “cast” it into another type. • The syntax for typecasting is to put the name of the type in parentheses and use it as an operator. • double pi = 3.14159; • int x = (int) pi; • System.out.println(x); • // What will the output be?
Precedence • Typecasting takes precedence over arithmetic operations. • double pi = 3.14159; • int x = (int) pi * 20.0; • System.out.println(x); • // What will the output be? • Converting to an integer always rounds down, even if the fraction part is 0.99999999
Math methods • Like objects, classes can have methods too. One of the most commonly used classes in Java is Math. • Methods of classes are invoked the same as they are for objects.
Math.sqrt • To find a square root of a number in Java, the Math.sqrt method can be called. • The Math.sqrt method takes a single argument which is the a double and returns a double which is its square root. • double x = Math.sqrt(9.0); • System.out.println(x); • // What will the output be?
Trig Functions • The common trigonometric functions can be called using methods of the Math class. • The trig function methods take a single double argument which is the angle in radians and returns a double which is the result of that trigonometric function. • double angle = 1.5; • double sine = Math.sin(angle); • double cosine = Math.cos(angle); • double tangent = Math.tan(angle);
math • Java also provides a few commonly used numbers such as pi. The double Math.PI can be used anywhere in place of π. • double halfPie = Math.PI/2; • Another useful method of Math is round. Math.round can be used to round off a floating point number to the nearest integer which is then returned as an int. • int x = Math.round(Math.PI * 20.0); • System.out.println(x); • // What is the output?
Exercise 2-1 Copy the code below and calculate the area of a circle with a radius of 63.4 and round it to the nearest whole number. • class Circle{ • public static void main(String[] args) { • double radius = 63.4; • // your code goes here • System.out.println(area); • } • }
Adding new methods • We can define new methods to do specific tasks and then call them in our main method like we have been doing with the previous few examples. • When a method is called from somewhere else in the program, it is “invoked”. • Methods have the following syntax: • public static void NAME( PARAMETERS) { • STATEMENTS • }
Methods • By convention, Java methods start with a lower case letter and use camelCase. • The list of parameters specifies what information, if any, you have to provide to invoke the new method. • When a method is called from somewhere else in the program, it is supplied arguments which match up with the parameters of the method.
Methods • Copy the following method in to your program. This method should go inside your Class but before the main method. • public static void newLine() { • System.out.println(“”); • } • This method is named newline and the empty parentheses means that it takes no arguments. It contains one statement which prints an empty String before skipping to the next line.
Calling a method • class NewLine { • public static void newLine() { • System.out.println(“”); • } • public static void main(String[] args){ • System.out.println(“First line.”); • newLine(); • System.out.println(“Second line.”); • } • } • // What will the output be?
Exercise 2-2 Add a new method after newLine named threeLine. threeLine should have no return type (void) and take no parameters. make threeLine invoke newLine three times. In your main method, copy the following: • System.out.println(“First line.”); • threeLine(); • System.out.println(“Second line.”); • // What is the output?
class • A class is a collection of related methods. In the last example, the class named NewLine contained three methods, named newLine, threeLine, and main. • Methods of other classes then the one we are writing in can be called by specifying the name of the class. • Math.abs(73); // abs is a method of the class Math • newLine(); // Java assumes newLine is a method of the class we are writing (NewLine).
parameters • A parameter is a variable that stores an argument. The parameter list of a method indicates what arguments are required. • For example, printTwice specifies a single parameter, s, that has type String. • public static void printTwice(String s) { • System.out.println(s); • System.out.println(s); • }
parameters • To invoke printTwice, a single argument with the type String must be provided. • printTwice(“Don’t make me say this twice!”); • When a method is invoked, the arguments that are provided to it are assigned to the parameters. This is known as parameter passing. The argument must have the same type as the parameter • Variables can be used as arguments as well. • String argument = “Never say never.”; • printTwice(argument);
Multiple parameters • Methods can have multiple parameters by declaring each one separately. • public static void printTime(int hour, int minute) { • System.out.print(hour); • System.out.print(“ : “); • System.out.println(minute); • } • When invoking functions, remember that you do not have to declare the types of arguments. • printTime(int hour, int minute); // INCORRECT • printTime(hour, minute); // CORRECT
Exercise 2-3 • Recreate the Midnight program which calculates and displays the number of seconds since midnight. Use the following code in your main method and create the new method calculateSeconds which does the calculations and prints out the result. • public static void main(String[] args){ • int hour = 10; • int minute = 02; • int second = 37; • calculateSeconds(hour, minute, second); • }
boolean • The boolean data type only has two possible values, true or false. True and false are Java keywords so they can’t be used as variable names. • boolean isMale = true; • boolean is21 = false;
Conditionals • To write useful programs, we need to check conditions and change the behavior of the program accordingly. This is done via conditional statements. • The if statement is the simplest form of a conditional statement. • if (x > 0) { • System.out.println(“x is positive”); • } • The expression in the parenthese is called a condition. If it is true, then the statements in brackets get executed. If not true, nothing happens.
Relational Operators • x == y • x != y • x > y • x < y • x >= y • x <= y • Remember that = is the assignment operator while == is a comparison operator. • The two sides of a condition operator have to be the same type.
Alternative Execution • Another form of conditional execution is alternative execution in which there are two possibilities and the condition determines which one gets executed. • if (x%2 == 0) { • System.out.println(“x is even”); • } else { • System.out.println(“x is odd”); • }
Exercise 2-4 Create a new Class called Parity with the following method: public static void printParity(int x) which prints out either “<x> is even” or “<x> is odd” whether x is even or odd. Put the following statements in your main method. • public static void main(String[] args){ • printParity(17); • printParity(-486); • printParity(10000); • }
Chained Conditionals • One way to check for a number of related conditionals and choose one of several actions is by chaining a series of ifs and elses. • if (x > 0) { • System.out.println(“x is positive”); • } else if (x < 0) { • System.out.println(“x is negative”); • } else { • System.out.println(“x is zero”); • }
Nested Conditionals • Conditionals can be nested within another. • if (x == 0) { • System.out.println(“x is zero”); • } else { • if (x > 0) { • System.out.println(“x is positive”); • } else { • System.out.println(“x is negative”); • } • }
The return statement • The return statement allows you to terminate the execution of a method before you reach the end. One reason to use it is if you detect an error condition. • public static void printLogarithm(double x) { • if (x <= 0.0) { • System.out.println(“Positive numbers only, please.”); • return; • } • double result = Math.log(x); • System.out.println(“The log of x is “ + result); • }
Recursion • A method can invoke itself. This is called recursion. • public static void square (int x) { • if (x > 100) { • System.out.println(x); • }else { • System.out.println(x); • square(x*x); • } • }
Exercise • public static void countdown(int n) { • if (n == 0) { • Sysem.out.println(“Blastoff!!!”); • } else { • System.out.println(n); • countdown(n – 1); • } • }
Return values • So far, all of our methods have been void: that is, methods that return no value. When a void method is invoked, it is typically on a line by itself with no assignment. • countdown(100); • newLine(); • Methods can also return things. These methods are called value methods. • For value methods, just replace void with the type the function is going to return. To return the value, write the return statement followed by the expression we are returning. • public static double area(double radius) { • return Math.PI * radius * radius; • }
Exercise 2-5 Write a method that takes in x1, x2, y1, and y2 and returns the distance between the two points. • public static double distance • (double x1, double y1, double x2, double y2) { • double dx = x2 - x1; • double dy = y2 - y1; • double dsquared = dx*dx + dy*dy; • double result = Math.sqrt(dsquared); • return result; • }