Escape Sequences \n newline \t tab \b backspace \r carriage return

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

2.1 Program Construction In Java
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Basic Java Constructs and Data Types – Nuts and Bolts
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Java Math Class. What is the Math Class? The Math Class is another class that is prepared by Java for us to use We use this class for mathematical operations.
Building Java Programs
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Return values.
Pemrograman Dasar - Data Types1 OPERATOR. Pemrograman Dasar - Data Types2 Arithmetic operator  + - * /  / operator denotes integer division if both.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
Chapter 6: User-Defined Functions I
CMT Programming Software Applications
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 106 Introduction to Computer Science I 02 / 24 / 2010 Instructor: Michael Eckmann.
Chapter 6: User-Defined Functions I
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Introduction to Methods
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Input, Output, and Processing
CSC Programming I Lecture 5 August 30, 2002.
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CSC Programming I Lecture 6 September 4, 2002.
Methods We write methods in our programs for many reasons:
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Chapter 2 topics Concept # on Java Subset Required for AP Exam print and println10. Testing of output is restricted to System.out.print and System.out.println.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
The Math Class Methods Utilizing the Important Math Operations of Java!
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
Fundamental of Java Programming Basics of Java Programming
CHAPTER 3: String And Numeric Data In Python
Unit 3: Variables in Java
Just Enough Java 17-May-19.
Presentation transcript:

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? 3

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 60

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? 3.0

Math.pow  

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? 62

More Math methods  

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); } 12,628

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? First line. Second line.

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? First line. Second line.

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); }

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 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”); 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 { 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; }