Java Programming Static Methods.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Introduction to Methods
Unit 2: Java Introduction to Programming 2.1 Initial Example.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
CSI 3125, Preliminaries, page 1 Compiling the Program.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Creating and Using Class Methods. Definition Class Object.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Topics Instance variables, set and get methods Encapsulation
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Methods. Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
User-Written Functions
Chapter 7 User-Defined Methods.
Lecture 14 Throwing Custom Exceptions
3 Introduction to Classes and Objects.
Java Course Review.
Predefined Functions Revisited
Yanal Alahmad Java Workshop Yanal Alahmad
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
JavaScript: Functions.
Lecture 4 Using Classes Richard Gesick.
CMSC 202 Static Methods.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Object Based Programming
Defining Classes and Methods
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Java Programming Function Introduction
CSE 1341 Topic 5 Methods © 2013 Ken Howard,
Chapter 5 Methods.
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Classes and Objects Static Methods
Object Oriented Programming in java
Java Programming Language
Chapter 9 Objects and Classes
Predefined Functions Revisited
Java Methods: A Deeper Look Academic 2019 Class: BIT23/BCS10 Chapter 06 Abdulaziz Yasin Nageye Faculty of Computing Java How to Program, 10/e 1 © Co py.
Java Programming Function Introduction
Methods/Functions.
Corresponds with Chapter 5
Chapter 7 Objects and Classes
Introduction to Methods and Interfaces
Presentation transcript:

Java Programming Static Methods

Radians/Degrees

Calculate radians/degrees From degree to radian Math. toRadians(180.0); From radian to degree Math. toDegrees(Math.PI);

RadianAndDegree.java package edu.hit.java.intro; public class RadianAndDegree { public static void main(String[] args) { double d = Math. toRadians(180.0); System.out.println(d); double r = Math.toDegrees(Math.PI); System.out.println(r); }

Adding new Method So far we’ve only written short programs that have a single class and a single method (main). Can we calculate the radians or degrees by calling the methods that are defined by ourselves without using the Math methods?

RadianAndDegree.java (modified) package edu.hit.java.intro; public class RadianAndDegree { public static double toRadians(double degree) { double radian = degree*Math.PI/180.0; return radian; } public static double toDegrees(double radian) { double degree= radian*180.0/Math.PI; return degree; public static void main(String[] args) {…}

RadianAndDegree.java (modified) public static void main(String[] args) { double d = toRadians(180.0); System.out.println(d); double r = toDegrees(Math.PI); System.out.println(r); }

Static method definition public static TYPE NAME (TYPE NAME,…) { STATEMENTS return EXPRESSION; }

Parameters & Return Value The variables defined in the parentheses after the method name in the method definition are called parameters (or formal parameters). The number of the parameters may be more than one. Return Value A method that returns a value is called value method, also called function. A value that a method returns is called return value. The function return a value of a specified type, called the return type of the function.

Void method A method without return value is called void method. The return type of a void method in the definition must be void. For example, the main method is a void method.

Arguments & parameter passing The values that are passed to a method when it is invoked are called arguments (or actual parameters). Parameter passing The process that the argument gets passed from outside the method to the inside is called parameter passing.

Return statement The value methods must have a return statement at least. The return statement terminates execution of the function and return a value to the caller. The return value must match the return type that is specified for the function. The return statement also allows you to terminate a method before you reach the end of it. I will show you in the next lecture (Conditionals).

Local variable A variable declared inside a method is called local variable. The parameters are also local variables. Note : Local variables cannot be accessed from outside their method. A local variable declared inside a block cannot be accessed from outside the block.

Parameters & Return values Return type Parameter Return type Parameter Return value Return value

Method invoking & Arguments Method invoking can be part of a expression Argument Argument

Celsius and Fahrenheit Define two methods: Converting Celsius to Fahrenheit Converting Fahrenheit to Celsius We have known: C=(5/9)*(F-32) F=(9/5)*C+32

Celsius and Fahrenheit package edu.hit.java.intro; public class CelsiusAndFahrenheit { public static double toFahrenheit(double celsius) { double fahrenheit = celsius*(9/5)+32; return fahrenheit ; } public static double toCelsius(double fahrenheit) { double celsius= (5/9)*(fahrenheit -32); return celsius; public static void main(String[] args) {…}

Celsius and Fahrenheit public static void main(String[] args) { double d = toFahrenheit(-26); System.out.println(d); double r = toCelsius(60); System.out.println(r); }

Non-static methods A method can be defined without the static keyword. If we want to access the non-static methods, we must use the keyword new followed by a call to the class's constructor to instantiate an object, and then use the dot notation to invoke them. Note: constructor is a special method whose name is same with the name of the class. If you didn’t define the constructor method, the compiler will help you define it.

Celsius and Fahrenheit package edu.hit.java.intro; public class CelsiusAndFahrenheit { public double toFahrenheit(double celsius) { double fahrenheit = celsius*(9/5)+32; return fahrenheit ; } public double toCelsius(double fahrenheit) { double celsius= (5/9)*(fahrenheit -32); return celsius; public static void main(String[] args) {…}

Celsius and Fahrenheit public static void main(String[] args) { CelsiusAndFahrenheit cf = new CelsiusAndFahrenheit(); double d = cf.toFahrenheit(-26); System.out.println(d); double r = cf.toCelsius(60); System.out.println(r); }

Advantages of methods Method is also called subroutine, or function. A method should do one thing and only one thing. Big programs are built out of small methods. Methods can be individually developed, tested and reused. User of method does not need to know how it works (a method seems to be a black box).

Some useful functions Getting the running time of your program Getting the current time with specified format Generating random numbers

Getting the running time long start=System.currentTimeMillis(); //write your code here … end=System.currentTimeMillis(); System.out.println(“your program spent "+(end-start)+"ms");

Getting current time package edu.hit.java.method; import java.util.Date; import java.text.SimpleDateFormat; public class CurrentDate { public static void main(String[] args) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(new Date())); }

Date and time pattern

New Date and time API of Java 8 There are some disadvantages in the old version of date-time related classes, so Java 8 introduces some new classes (in the package java.time) to process date and time. Reading materials: http://www.oracle.com/technetwork/articles/java/jf14- date-time-2125367.html http://tutorials.jenkov.com/java-date-time/index.html http://www.codeceo.com/article/java-8-date-time- api.html

Getting current time Package edu.hit.java.method; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class NewCurrentDate { public static void main(String[] args) { //getting current Date and Time LocalDateTime dateTime = LocalDateTime.now(); //specific format System.out.println(dateTime.format( DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss "))); }

Generating random numbers There are two principal means of generating random (really pseudo-random) numbers: the static method Math.random() generates doubles between 0 (inclusive) and 1 (exclusive). the java.util.Random class generates random integers, doubles, longs and so on, in various ranges. By invoke its nextXXX() methods, such as, nextFloat(), nextInt(), nextInt(int n), etc.

Math.random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random();

java.util.Random An instance of this class is used to generate a stream of pseudorandom numbers. 

Java API reference http://docs.oracle.com/javase/7/docs/api/index.h tml

Quiz 3 Refactor the CalcArea.java Add a static value method calcCircleArea to calculate the area of a circle. Add a non-static value method calcRectangleArea to calculate the area of a rectangle. Modify the main method, invoke calcCircleArea to find the area of a circle with radius 10, invoke calcRectangleArea to find the area of a rectangle with length10 and width 20, and print the results.

Can a method call itself?