This document provides an overview of several Java standard classes including Date, SimpleDateFormat, Scanner, Math, and DecimalFormat. It discusses how to create objects from these classes, commonly used methods, and examples of how to incorporate them into programs. For Date, it demonstrates getting the current date, comparing dates, and formatting dates. For Scanner, it shows reading user input. For Math, it lists common mathematical methods. For DecimalFormat, it demonstrates formatting numbers to a specified number of decimal places.
The document discusses constructors in Java. It defines constructors as special methods that initialize objects. Constructors are invoked during object creation and provide initial values for object fields. The document covers default constructors that provide default values if no constructor is defined, parameterized constructors that initialize fields with passed in values, and constructor overloading which allows multiple constructors with different parameters. It provides examples of each type of constructor.
The document discusses defining classes and objects in Java. It covers defining simple classes, class elements like fields and methods, constructors, properties, static members, and using classes by creating instances and calling methods. Key points include classes define the structure of objects, constructors initialize object state, properties encapsulate fields, and static members are associated with a class not individual objects.
This document provides an overview of object-oriented programming concepts in Java, including classes, objects, variables, methods, constructors, abstraction, encapsulation, inheritance, and polymorphism. It defines classes and objects, and describes how classes act as blueprints for objects. It explains the syntax for defining classes and class members like variables and methods. It also covers method overloading, different types of methods, and how constructors are used to initialize objects. The document concludes with brief explanations of abstraction, encapsulation, inheritance, and polymorphism as fundamental principles of object-oriented design.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
The document provides an overview of various Objective-C concepts including classes, objects, methods, properties, protocols, categories, dictionaries, property lists, user defaults, errors, delegates, callbacks, and table views. It discusses core classes like NSString, NSArray, NSDictionary, and NSMutableDictionary. It covers concepts like inheritance, polymorphism, and memory management using retain, release, and autorelease. The document also provides examples of declaring and defining classes, creating class instances, and implementing table views with custom cells.
This document provides an overview of object-oriented programming concepts in Java including classes, objects, attributes, and methods. It discusses how classes define templates for objects and how objects are instances of classes. Examples are given of declaring a class for a car with attributes like make and speed, and methods like accelerate and turn. The document also covers creating objects from classes in code, and accessing object attributes and methods. Finally, it briefly introduces some standard Java classes like Math that are commonly used.
Classes allow the creation of user-defined data types through the grouping of related properties and behaviors. They contain members like variables and methods that can be declared as private, protected, public or static. Constructors initialize new class objects, while finalizers run before objects are destroyed. The toString method returns a string representation of an object. Abstract data types specify logical properties without implementation details. An example program designs classes for a candy machine application that displays products, accepts selections and payments, and dispenses items.
The document discusses constructors in Java. It defines constructors as special methods that initialize objects. Constructors are invoked during object creation and provide initial values for object fields. The document covers default constructors that provide default values if no constructor is defined, parameterized constructors that initialize fields with passed in values, and constructor overloading which allows multiple constructors with different parameters. It provides examples of each type of constructor.
The document discusses defining classes and objects in Java. It covers defining simple classes, class elements like fields and methods, constructors, properties, static members, and using classes by creating instances and calling methods. Key points include classes define the structure of objects, constructors initialize object state, properties encapsulate fields, and static members are associated with a class not individual objects.
This document provides an overview of object-oriented programming concepts in Java, including classes, objects, variables, methods, constructors, abstraction, encapsulation, inheritance, and polymorphism. It defines classes and objects, and describes how classes act as blueprints for objects. It explains the syntax for defining classes and class members like variables and methods. It also covers method overloading, different types of methods, and how constructors are used to initialize objects. The document concludes with brief explanations of abstraction, encapsulation, inheritance, and polymorphism as fundamental principles of object-oriented design.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
The document provides an overview of various Objective-C concepts including classes, objects, methods, properties, protocols, categories, dictionaries, property lists, user defaults, errors, delegates, callbacks, and table views. It discusses core classes like NSString, NSArray, NSDictionary, and NSMutableDictionary. It covers concepts like inheritance, polymorphism, and memory management using retain, release, and autorelease. The document also provides examples of declaring and defining classes, creating class instances, and implementing table views with custom cells.
This document provides an overview of object-oriented programming concepts in Java including classes, objects, attributes, and methods. It discusses how classes define templates for objects and how objects are instances of classes. Examples are given of declaring a class for a car with attributes like make and speed, and methods like accelerate and turn. The document also covers creating objects from classes in code, and accessing object attributes and methods. Finally, it briefly introduces some standard Java classes like Math that are commonly used.
Classes allow the creation of user-defined data types through the grouping of related properties and behaviors. They contain members like variables and methods that can be declared as private, protected, public or static. Constructors initialize new class objects, while finalizers run before objects are destroyed. The toString method returns a string representation of an object. Abstract data types specify logical properties without implementation details. An example program designs classes for a candy machine application that displays products, accepts selections and payments, and dispenses items.
The document describes the order of presentation for a group project. Etukudo Andy will introduce the project and order of presentation. Adewumi Ezekiel will present on the numerical data project and contribution. Fajuko Micheal will run the program and discuss contribution. Finally, Afia Kennedy will provide the conclusion and link the project to previous lectures, discussing contribution.
This document provides a review of object-oriented programming concepts in Java, including:
- The difference between primitives and objects, and value vs reference semantics.
- How classes act as blueprints for objects, defining their data and behavior.
- Key object-oriented principles like encapsulation, fields, methods, and constructors.
- How objects pass by reference when used as parameters or assigned.
- Comparing objects requires special methods rather than using ==.
The document discusses classes and objects in C++. It defines what a class is - a blueprint for an object that contains data members and member functions. An object is an instance of a class that allocates memory. The document explains how to define a class with public and private members, create objects of a class, and access class members through objects using dot operators. It also covers constructors and how they initialize objects automatically upon creation.
The document discusses various topics in Objective-C including variables, data types, categories, protocols, and composite objects. It provides code examples to illustrate initializing objects, variable scope, enumerated data types, typedefs, data type conversion, categories, class extensions, protocols, delegates, and composite objects in Objective-C and compares some of these concepts to Java.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document discusses Scala concepts including higher-order functions, anonymous functions, currying, tail recursion, classes and objects, properties with getters and setters, object-private fields, auxiliary constructors, primary constructors, nested classes, and singleton objects. It provides code examples to illustrate these Scala features and explains how they work and how they compare to similar concepts in other languages like Java. The document is intended as a lesson on these Scala programming concepts.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
This document provides an introduction to object-oriented programming concepts in Java. It discusses similarities and differences between Java and C++, object-oriented nomenclature, instance variables, methods, and constructors. Instance variables are fields that belong to objects of a class. Methods are functions defined within classes that can access and modify instance variables. Constructors initialize new objects and are called when objects are created using the new operator. The document provides examples to illustrate these concepts and highlights key differences between Java and C++ regarding object-oriented programming.
This chapter discusses user-defined classes and abstract data types (ADTs) in Java. It covers defining classes with private, protected, public, and static members. Constructors and finalizers are examined. The toString method is explored. Abstract data types are introduced as data types that specify logical properties without implementation details. An example candy machine problem is presented to demonstrate defining classes for a non-GUI and GUI application to model a candy machine with items for sale, a cash register, dispenser, and other components.
C# programs use namespaces and classes. A class defines methods and variables. C# supports inheritance, interfaces, structs, and enums. The main method runs code. Common data types include primitive types like int and reference types like string. C# can read input, perform math operations, and conditionally execute code using if/else statements. Methods can pass parameters by value or reference.
The document provides information on Java OOP concepts including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It defines objects as entities with state and behavior, and classes as collections of objects. Inheritance allows objects to acquire properties of parent objects. Polymorphism allows one task to be performed in different ways. Abstraction hides internal details and shows functionality, while encapsulation binds code and data together into a single unit.
Wrapper classes allow primitive data types like int and double to be used as objects. Each primitive type has a corresponding wrapper class like Integer and Double. Wrapper classes allow primitive values to be passed by reference rather than by value. GUIs can be created using Swing components like JFrame for windows and JOptionPane for simple input/output dialogs. Components are added to the content pane of the JFrame to build the GUI interface.
Objective-C for iOS Application DevelopmentDhaval Kaneria
The document provides an introduction to Objective-C and iPhone development. It discusses key aspects of Objective-C including its syntax which extends C with object-oriented capabilities. Objective-C uses class definitions with interfaces and implementations. Programs create class instances that can receive messages to call methods. Classes can inherit from superclasses and support polymorphism. The document also outlines core concepts like memory management, frameworks for iOS development and examples of Hello World programs.
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
Ring allows defining classes with attributes and methods. When a new object is created:
1. The class region code is executed to initialize the object's attributes.
2. Methods are collected from the class and parent classes to be called on the object.
3. Attributes can be accessed directly or via getter/setter methods, which are called automatically.
Global names are searched when defining attributes to allow dynamic attribute definition based on global state. However, this could cause conflicts that the programmer must avoid, such as by prepending names with $ or self..
This document discusses object placement and layout managers in GUI programming. It describes how to add objects like buttons and labels to a content pane and use different layout managers, including FlowLayout, BorderLayout, and GridLayout, to determine object positioning. It also introduces the concept of panels, which allow sectioning of a frame and the use of nested layouts.
The document discusses object-oriented programming concepts like passing objects to methods, returning objects from methods, using objects as attributes, and overloading methods. Specifically, it provides an example of creating an Equipment class with attributes like name and value, and methods to get those attributes, loan the equipment to a student, and check which student it is loaned to. It also shows adding a borrowed equipment attribute to the Student class to track equipment loans.
The document describes the order of presentation for a group project. Etukudo Andy will introduce the project and order of presentation. Adewumi Ezekiel will present on the numerical data project and contribution. Fajuko Micheal will run the program and discuss contribution. Finally, Afia Kennedy will provide the conclusion and link the project to previous lectures, discussing contribution.
This document provides a review of object-oriented programming concepts in Java, including:
- The difference between primitives and objects, and value vs reference semantics.
- How classes act as blueprints for objects, defining their data and behavior.
- Key object-oriented principles like encapsulation, fields, methods, and constructors.
- How objects pass by reference when used as parameters or assigned.
- Comparing objects requires special methods rather than using ==.
The document discusses classes and objects in C++. It defines what a class is - a blueprint for an object that contains data members and member functions. An object is an instance of a class that allocates memory. The document explains how to define a class with public and private members, create objects of a class, and access class members through objects using dot operators. It also covers constructors and how they initialize objects automatically upon creation.
The document discusses various topics in Objective-C including variables, data types, categories, protocols, and composite objects. It provides code examples to illustrate initializing objects, variable scope, enumerated data types, typedefs, data type conversion, categories, class extensions, protocols, delegates, and composite objects in Objective-C and compares some of these concepts to Java.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document discusses Scala concepts including higher-order functions, anonymous functions, currying, tail recursion, classes and objects, properties with getters and setters, object-private fields, auxiliary constructors, primary constructors, nested classes, and singleton objects. It provides code examples to illustrate these Scala features and explains how they work and how they compare to similar concepts in other languages like Java. The document is intended as a lesson on these Scala programming concepts.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
This document provides an introduction to object-oriented programming concepts in Java. It discusses similarities and differences between Java and C++, object-oriented nomenclature, instance variables, methods, and constructors. Instance variables are fields that belong to objects of a class. Methods are functions defined within classes that can access and modify instance variables. Constructors initialize new objects and are called when objects are created using the new operator. The document provides examples to illustrate these concepts and highlights key differences between Java and C++ regarding object-oriented programming.
This chapter discusses user-defined classes and abstract data types (ADTs) in Java. It covers defining classes with private, protected, public, and static members. Constructors and finalizers are examined. The toString method is explored. Abstract data types are introduced as data types that specify logical properties without implementation details. An example candy machine problem is presented to demonstrate defining classes for a non-GUI and GUI application to model a candy machine with items for sale, a cash register, dispenser, and other components.
C# programs use namespaces and classes. A class defines methods and variables. C# supports inheritance, interfaces, structs, and enums. The main method runs code. Common data types include primitive types like int and reference types like string. C# can read input, perform math operations, and conditionally execute code using if/else statements. Methods can pass parameters by value or reference.
The document provides information on Java OOP concepts including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It defines objects as entities with state and behavior, and classes as collections of objects. Inheritance allows objects to acquire properties of parent objects. Polymorphism allows one task to be performed in different ways. Abstraction hides internal details and shows functionality, while encapsulation binds code and data together into a single unit.
Wrapper classes allow primitive data types like int and double to be used as objects. Each primitive type has a corresponding wrapper class like Integer and Double. Wrapper classes allow primitive values to be passed by reference rather than by value. GUIs can be created using Swing components like JFrame for windows and JOptionPane for simple input/output dialogs. Components are added to the content pane of the JFrame to build the GUI interface.
Objective-C for iOS Application DevelopmentDhaval Kaneria
The document provides an introduction to Objective-C and iPhone development. It discusses key aspects of Objective-C including its syntax which extends C with object-oriented capabilities. Objective-C uses class definitions with interfaces and implementations. Programs create class instances that can receive messages to call methods. Classes can inherit from superclasses and support polymorphism. The document also outlines core concepts like memory management, frameworks for iOS development and examples of Hello World programs.
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
Ring allows defining classes with attributes and methods. When a new object is created:
1. The class region code is executed to initialize the object's attributes.
2. Methods are collected from the class and parent classes to be called on the object.
3. Attributes can be accessed directly or via getter/setter methods, which are called automatically.
Global names are searched when defining attributes to allow dynamic attribute definition based on global state. However, this could cause conflicts that the programmer must avoid, such as by prepending names with $ or self..
This document discusses object placement and layout managers in GUI programming. It describes how to add objects like buttons and labels to a content pane and use different layout managers, including FlowLayout, BorderLayout, and GridLayout, to determine object positioning. It also introduces the concept of panels, which allow sectioning of a frame and the use of nested layouts.
The document discusses object-oriented programming concepts like passing objects to methods, returning objects from methods, using objects as attributes, and overloading methods. Specifically, it provides an example of creating an Equipment class with attributes like name and value, and methods to get those attributes, loan the equipment to a student, and check which student it is loaned to. It also shows adding a borrowed equipment attribute to the Student class to track equipment loans.
This document discusses file handling in Java. It covers creating File objects to represent files and directories, and using streams for low-level and high-level file input and output of primitive data types, text, and objects. Methods like exists(), list(), isFile() are used to check files. The FileChooser class provides a GUI to select files. Streams like FileOutputStream, FileInputStream, PrintWriter, Scanner facilitate reading and writing files. Object streams allow writing and reading objects to files.
This document discusses inheritance and GUI components in Java. It begins by reviewing how to create basic GUI frames and components using classes like JFrame and JOptionPane. It then explains the concepts of inheritance, where a subclass inherits attributes and methods from its superclass. Regarding GUIs, the document shows how custom GUI frames can be created by extending the JFrame class and overriding its methods. This allows creating specialized frame classes with customized functionality and properties.
This document discusses event handling in Java GUI programming. It explains that GUI components like buttons and text boxes generate events like clicks and key presses. Event listeners need to be created to handle these events. The ActionListener interface is used to create classes that listen for action events. There are four ways to implement an action listener: 1) create a separate listener class, 2) make the GUI class itself the listener, 3) create a nested listener class, 4) use an anonymous inner class. The event source and event object can be used to determine which component generated the event. Multiple listeners can be used to handle different event sources.
This document discusses error handling in programs. It explains that exceptions are runtime errors that occur during program execution. When an exception occurs, it is thrown. Code can be written to catch exceptions using try-catch blocks. Different types of exceptions that may occur are discussed, along with how to define and throw custom exceptions. Finally, the document touches on exception propagation through method calls and the use of assertions to check conditions.
The document discusses creating classes in Java. It covers:
1. Creating a class with attributes and methods, including get/set methods and constructors.
2. Using private and public access modifiers to control which parts of a class can be accessed from outside the class.
3. The principle of encapsulation, which separates the external interface of a class from its internal implementation through information hiding.
The document summarizes key concepts about strings and regular expressions in Java. It discusses that strings are immutable sequences of characters represented by the String class, and how to manipulate strings. It also covers that regular expressions provide a concise way to match patterns in strings using special characters. Finally, it notes that the StringBuffer and StringBuilder classes allow mutable string operations by modifying objects instead of creating new String objects.
This lecture covered the steps involved in solving a programming problem: problem identification, analysis, program design, implementation, testing, and documentation. It then discussed some key concepts for moving from C to Java, including variables, operators, control structures like if/else statements and loops, and arrays. The document provided examples and explanations of these concepts.
Design and optimization of ion propulsion dronebjmsejournal
Electric propulsion technology is widely used in many kinds of vehicles in recent years, and aircrafts are no exception. Technically, UAVs are electrically propelled but tend to produce a significant amount of noise and vibrations. Ion propulsion technology for drones is a potential solution to this problem. Ion propulsion technology is proven to be feasible in the earth’s atmosphere. The study presented in this article shows the design of EHD thrusters and power supply for ion propulsion drones along with performance optimization of high-voltage power supply for endurance in earth’s atmosphere.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Applications of artificial Intelligence in Mechanical Engineering.pdfAtif Razi
Historically, mechanical engineering has relied heavily on human expertise and empirical methods to solve complex problems. With the introduction of computer-aided design (CAD) and finite element analysis (FEA), the field took its first steps towards digitization. These tools allowed engineers to simulate and analyze mechanical systems with greater accuracy and efficiency. However, the sheer volume of data generated by modern engineering systems and the increasing complexity of these systems have necessitated more advanced analytical tools, paving the way for AI.
AI offers the capability to process vast amounts of data, identify patterns, and make predictions with a level of speed and accuracy unattainable by traditional methods. This has profound implications for mechanical engineering, enabling more efficient design processes, predictive maintenance strategies, and optimized manufacturing operations. AI-driven tools can learn from historical data, adapt to new information, and continuously improve their performance, making them invaluable in tackling the multifaceted challenges of modern mechanical engineering.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
2. Plan
▪ Discuss some Java standard classes
▪ Write some programs using these classes
▪ Learn about these classes BUT ALSO about OOP
generally
3. Recall…
▪ We looked at classes and objects.
▪ We saw how we can define our own classes and create
objects from those classes.
▪ Instead of writing our own classes, we can get used to
OOP using Java standard classes.
– Date, SimpleDateFormat
– Scanner
– DecimalFormat
– Math
4. Date class
▪ Date objects have methods and attributes that can be
used to represent dates
– millisecond precision
▪ When Date objects are created, it set to the current
time.
▪ The date is internally stored as a count of the number
of milliseconds since midnight 1 January, 1970.
– Does it matter how it is stored internally?
5. Date class
▪ Start by importing java.util:
import java.util.*
▪ Then, in main, declare and create an object:
Date now = new Date();
▪ Date objects have a method called toString() which converts
the stored time into a string that can be printed
System.out.print(now.toString());
6. Date class
▪ Date also has some methods
– boolean after(Date d)
– boolean before(Date d)
▪ Example: Write a method (in main()) that
– Creates a Date object
– Does some stuff – This is so that when you run it, the two Date
objects will be different.
– Creates another Date object
– Confirms that the first Date object is older the second Date
object.
7. public class L3 {
public static void main(String[] args) {
Date d1 = new Date();
for (int i = 0; i < 1e6;i++) {
int j = i * i;
}
Date d2 = new Date();
if (d1.before(d2))
System.out.println("d1 is older than d2");
else
System.out.println("d1 is newer than d2");
}
}
}
Creates a Date object
Does some stuff
Creates another
Date object
Confirms that the
first Date object is
older the second
Date object.
8. SimpleDateFormat class
▪ Date class has a method toString() which converts the
internal stored data format into a string.
▪ But what if we want more options?
▪ SimpleDataFormat objects have methods that can convert
Date objects.
9. SimpleDateFormat class
▪ Start by importing java.text:
import java.text.*;
▪ Create a SimpleDateFormat object and pass the format:
SimpleDateFormat SDF = new SimpleDateFormat(“dd/MMM/yyyy”);
▪ SimpleDateFormat objects have a method called format() – it
takes a Date object and returns a string of that date in the
correct format.
System.out.println(SDF.format(d1));
10. SimpleDateFormat class
▪ These are some of the formatting options1.
1Taken from "An Introduction to Object Orientated Programming with Java (5th ed.)" by C.ThomasWu
11. SimpleDateFormat class
▪ Exercise: Write a program
that:
– creates a Date object
– Displays it with one format
– Displays it with another
format
– Displays what day of the year
it is
12. Scanner class
▪ Scanner class is used to create objects that read data from a
source.
▪ This source might be from a…
– Keyboard – reading what a user is typing
– File – reading text or data from a file.
13. Scanner class
▪ Start by importing java.util:
import java.util.*;
▪ Then, in main(), declare and create a Scanner object. On creation,
we pass it where reads from:
Scanner scan = new Scanner(System.in);
OR
Scanner scan = new Scanner(s); //s is a String
OR
Scanner scan = new Scanner(f); // f is a file
14. Scanner class
▪ Scanner objects have a method next() which returns the next
input value as a String.
▪ Instead of the next() method, which returns a String:
– int nextInt() – returns the next input value as an int.
– byte nextByte() – returns the next input value as a byte
– float nextFloat() – returns the next input value as a float
– …
▪ Also several functions which check if there is anything in the
scanner:
– bool hasNextInt() – returns true if the scanner object has an integer input
– bool hasNextFloat() – returns true if the scanner object has a float input
– …
15. Scanner class
▪ Exercise: Reading in a user’s name from the console:
– Create a String and a scanner.
– Prompt for a name
– Use scanner to read in what comes next from its source
– Print the name to the screen.
16. public class L3 {
public static void main(String[] args) {
String firstName;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter your name: ");
firstName = scan.next();
System.out.println("Welcome, " + firstName);
}
}
Create a String and
a scanner
Prompt for a name
Use scanner to read
in what comes next
from its source
Print the name to
the screen
17. Scanner class
▪ Exercise: Write a program that reads in a person’s first name,
surname and age, greets them by name and tells them what year
they were born in.
18. String firstName, secondName;
int age;
Scanner scan = new Scanner(System.in);
System.out.print("Enter first name: ");
firstName = scan.next();
System.out.print("Enter surname name: ");
secondName = scan.next();
System.out.print("Enter age: ");
age = scan.nextInt();
System.out.println("Hello, " + firstName + " " + secondName +
". You were born in " + (2019‐age) + ".");
19. Constants
▪ Similar to a variable, precede with the keyword final
▪ Does not take up memory space
▪ Wherever it appears in your code is replaced the constant
value when you program compiles.
▪ e.g.
▪ Similar to #define in C
final double PI = 3.14159
…
area = 2* 3.14159 * radius;
final double PI = 3.14159;
…
area = 2* PI * radius;
20. Class methods vs Object methods
▪ Also called static methods vs instance methods
▪ Object methods (instance methods):
– Belong to object, not the class
– Need to create the object first
– Each object created from the class has its own copy of the method
▪ Class method:
– Belong to the class
– They can be called without creating an object first
– To be shared among all objects from the same class
▪ Revisit in more detail when we write our own classes.
21. Math class
▪ Math class: contains class constants and methods to
perform mathematical operations.
22. Math class
▪ Part of the java.lang package, automatically included so
don’t need to import specifically.
▪ NB: These are class methods and class constants
▪ Because they are class methods, call them without
declaring an object:
y = Math.abs(x);
y = 2 * Math.PI * r;
y = Math.random();
▪ Math.random() - Returns a random number between 0.0
and 1.0
23. Math class
▪ Taken from Table 3.7 from “An
Introduction to Object Orientated
Programming with Java (5th ed.)”
by C. Thomas Wu
24. Math class
▪ Write a program that sets the height and radius of a cylinder
randomly. Height is between 1.0 and 3.0, radius is between 5.0
and 8.0. Calculate the surface area and volume of this cylinder.
25. public class L3 {
public static void main(String[] args) {
double h, r, a, v;
h = Math.random() * 2.0 + 1.0;
r = Math.random() * 3.0 + 5.0;
a = 2*Math.PI * r * (h+r);
v = Math.PI * Math.pow(r, 2) * h;
}
}
h = Math.random();
h = Math.random() * 2.0;
h = Math.random() * 2.0 + 1.0;
h ranges from 0 to 1
h ranges from 0 to 2
h ranges from 1 to 3
26. DecimalFormat class
▪ DecimalFormat class is used to provide a standard format for
displaying float point numbers.
▪ We can use format specifiers like %0.1f
▪ But what if we wanted to let someone else specify how many
decimal points we should use?
▪ DecimalFormat objects are created with a specified format and
then any value passed to them is converted into this format.
27. DecimalFormat class
▪ Start by importing java.text:
import java.text.*;
▪ In main, declare and create an object. On creation, we pass a
pattern (string) that illustrates the number of decimal places:
DecimalFormat df = new DecimalFormat("0.00"); //2 dec places
DecimalFormat df = new DecimalFormat("0.000"); //3 dec places
28. DecimalFormat class
▪ DecimalFormat objects have a methods format() which returns a
String version of the number to the correct number of decimal
places
float f = 1.2345f;
DecimalFormat df = new DecimalFormat("0.0");
System.out.println(f); //1.2345
System.out.println(df.format(f)); //1.2
29. DecimalFormat class
▪ Amend the math class program from earlier to display the surface
area and volume correct to 1 decimal place.
30. public class L3 {
public static void main(String[] args) {
double h, r, a, v;
h = Math.random() * 2.0 + 1.0;
r = Math.random() * 3.0 + 5.0;
a = 2*Math.PI * r * (h+r);
v = Math.PI * Math.pow(r, 2) * h;
DecimalFormat df = new DecimalFormat("0.0");
System.out.println(df.format(a));
System.out.println(df.format(v));
}
}