SlideShare a Scribd company logo
Geoff Holmes
 Date
 Math
 Weighted Distr
 Strings
 String methods
 Tokenizers
 System
 Examples
Utility Classes (Chapter 17)
import java.util.*;
Department of Computer Science 2
Date
 Represents both times and dates
class Date {
public Date() // current time and date!
public Date(int y, int m, int d, int h, int m, int s)
public int getMonth(), .., getSeconds(),
public int getDay() // day of the week
public int getYear() // year – 1900
public long getTime() // milliseconds since epoch
public void setMonth(int m), .., setSeconds(int s)
Department of Computer Science 3
import java.util.*;
public class DateTest {
public static void main(String [] args) {
Date s = new Date();
System.out.println("s toString = " + s.toString());
int j = 0;
for (int i=0; i<100000; i++) j = j + i;
Date e = new Date();
System.out.println("That took " +
(e.getTime() - s.getTime())+ " msecs");
}
}
Department of Computer Science 4
Math
 Supplies static constants and methods
public static final double E // = 2.71828
public static final double PI // = 3.1415926
 Trigonometric ops (double  double):
sin, cos, tan, asin, acos, atan, atan2
 Rounding ops: ceil, floor, rint, round
 Exponentials: exp, pow, log, sqrt
 Other: abs, max, min, random
Department of Computer Science 5
Draw from weighted distribution
static public int weightedDistribution (int[ ] weights) {
int sum = 0; // sum of weights
for(int i = 0; i < weights.length; i++)
sum += weights[i];
int val = (int) Math.floor(Math.random()*sum+1);
for(int i = 0; i < weights.length; i++) {
val -= weights[i];
if (val < 0) return i; }
return 0; // should never happen
}
 weights (1,3,2) will yield p(0)=1/6, p(1)=1/2, p(2)=1/3
Department of Computer Science 6
String
 Immutable! i.e. cannot be changed
String name = “John Smith”;
char[] data = {‘q’,’e’,’d’};
String quod = new String(data);
 Concatenation: +, but be careful, groups from left:
System.out.println(“Catch-” + 2 + 2)  “Catch22”
System.out.println(2 + 2 + “warned”)  “4warned”
System.out.println(“” + 2 + 2 + “warned”)  “22warned”
// trick: empty leading string
Department of Computer Science 7
String methods
 Will return copies in case of modifications
 Constructors from Strings and StringsBuffer, char
and byte arrays
 concat, replace (characters), (retrieve) substring,
toLowerCase, toUpperCase, trim (whitespace),
valueOf, compareTo, equalsIgnoreCase,
endsWith, startsWith, indexOf, lastIndexOf
Department of Computer Science 8
valueOf safer than toString
public static String valueOf(Object o) {
return (o == null) ? “null” : o.toString();
}
 Purely polymorphic and safe:
Shape aShape = null;
…
String a = String.valueOf(aShape); // “null”
String b = aShape.toString();
// nullPointerException
Department of Computer Science 9
== on Strings
String one = “One”;
String two = new String(one); // copy of one
String three = String.valueOf(one); // ref to one
System.out.println((one == two)); // “false”
System.out.println((one == three)); // “true”
Department of Computer Science 10
StringBuffer
 More like strings in C (arrays of char), can be
modified:
StringBuffer strbuf = new StringBuffer(“hope”);
strbuf.setCharAt(0,’c’);
 Constructors: StringBuffer(String initial),
StringBuffer(int capacity)
 append, insert, and reverse modify buffer and
return this thus allowing for cascaded calls:
strbuf.append(“ with ”).append(“209”);
 setCharAt, charAt,
 length, setLength, ensureCapacity, toString
Department of Computer Science 11
StringTokenizer
 Breaks a string into a sequence of tokens,
 tokens are defined by delimiters (e.g. space)
 Implements the Enumeration protocol
public StringTokenizer(String s)
public StringTokenizer(String s, String delims)
public boolean hasMoreElements()
public Object nextElement()
public String nextToken()
public int countTokens() // remaining tokens
Department of Computer Science 12
StringTokenizer example
public void readLines (DataInputStream input) throws IOException {
String delims = “ tn.,!?;:”;
for(int line = 1; true; line++) {
String text = input.readLine();
if (text==null) return;
text = text.toLowerCase();
StringTokenizer e = new StringTokenizer(text,delim);
while( e.hasMoreElements())
}}
Department of Computer Science 13
Parsing String Values
 For primitive data types wrapper classes provide parsing
from strings and back:
String dstr = “23.7”;
Double dwrap = new Double(dstr);
double dval = dwrap.doubleValue();
 Instead of constructor:
double dval = Double.parseDouble(“23.7”);
enterWord(e.nextToken(), new Integer(line));
 Similar for ints, booleans, longs, and floats
Department of Computer Science 14
System
 Supplies system-wide resources:
 Streams: System.in, System.out, System.err
 System.exit(int) terminates a program
 SystemDemo.java
Department of Computer Science 15
Examples
 Write a program palindrome in two ways:
First, using StringBuffer (and reverse)
• public StringBuffer reverse( )
Second, using
• public char charAt(int index)
 Eliza psychiatric help
 Supply the name of a file as argument and
count the number of lines, words and
characters in the file (tips).

More Related Content

Similar to Utility.ppt

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
archana singh
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
anujsharmaanuj14
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
xcoda
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
RohitkumarYadav80
 
Huraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docxHuraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docx
hurairawarisarain23
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
Yael Zaritsky Perez
 
About java
About javaAbout java
About java
Jay Xu
 
Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----
Tak Lee
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
Charm Sasi
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
akkhan101
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdf
kokah57440
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
Aiman Hud
 

Similar to Utility.ppt (20)

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
Huraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docxHuraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docx
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
 
About java
About javaAbout java
About java
 
Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdf
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 

More from BruceLee275640

Git_new.pptx
Git_new.pptxGit_new.pptx
Git_new.pptx
BruceLee275640
 
introductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdfintroductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdf
BruceLee275640
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
BruceLee275640
 
fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.ppt
BruceLee275640
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
BruceLee275640
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
life science.pptx
life science.pptxlife science.pptx
life science.pptx
BruceLee275640
 

More from BruceLee275640 (7)

Git_new.pptx
Git_new.pptxGit_new.pptx
Git_new.pptx
 
introductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdfintroductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdf
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
 
fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.ppt
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
life science.pptx
life science.pptxlife science.pptx
life science.pptx
 

Recently uploaded

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
aisafed42
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 

Recently uploaded (20)

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabhQuarter 3 SLRP grade 9.. gshajsbhhaheabh
Quarter 3 SLRP grade 9.. gshajsbhhaheabh
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 

Utility.ppt

  • 1. Geoff Holmes  Date  Math  Weighted Distr  Strings  String methods  Tokenizers  System  Examples Utility Classes (Chapter 17) import java.util.*;
  • 2. Department of Computer Science 2 Date  Represents both times and dates class Date { public Date() // current time and date! public Date(int y, int m, int d, int h, int m, int s) public int getMonth(), .., getSeconds(), public int getDay() // day of the week public int getYear() // year – 1900 public long getTime() // milliseconds since epoch public void setMonth(int m), .., setSeconds(int s)
  • 3. Department of Computer Science 3 import java.util.*; public class DateTest { public static void main(String [] args) { Date s = new Date(); System.out.println("s toString = " + s.toString()); int j = 0; for (int i=0; i<100000; i++) j = j + i; Date e = new Date(); System.out.println("That took " + (e.getTime() - s.getTime())+ " msecs"); } }
  • 4. Department of Computer Science 4 Math  Supplies static constants and methods public static final double E // = 2.71828 public static final double PI // = 3.1415926  Trigonometric ops (double  double): sin, cos, tan, asin, acos, atan, atan2  Rounding ops: ceil, floor, rint, round  Exponentials: exp, pow, log, sqrt  Other: abs, max, min, random
  • 5. Department of Computer Science 5 Draw from weighted distribution static public int weightedDistribution (int[ ] weights) { int sum = 0; // sum of weights for(int i = 0; i < weights.length; i++) sum += weights[i]; int val = (int) Math.floor(Math.random()*sum+1); for(int i = 0; i < weights.length; i++) { val -= weights[i]; if (val < 0) return i; } return 0; // should never happen }  weights (1,3,2) will yield p(0)=1/6, p(1)=1/2, p(2)=1/3
  • 6. Department of Computer Science 6 String  Immutable! i.e. cannot be changed String name = “John Smith”; char[] data = {‘q’,’e’,’d’}; String quod = new String(data);  Concatenation: +, but be careful, groups from left: System.out.println(“Catch-” + 2 + 2)  “Catch22” System.out.println(2 + 2 + “warned”)  “4warned” System.out.println(“” + 2 + 2 + “warned”)  “22warned” // trick: empty leading string
  • 7. Department of Computer Science 7 String methods  Will return copies in case of modifications  Constructors from Strings and StringsBuffer, char and byte arrays  concat, replace (characters), (retrieve) substring, toLowerCase, toUpperCase, trim (whitespace), valueOf, compareTo, equalsIgnoreCase, endsWith, startsWith, indexOf, lastIndexOf
  • 8. Department of Computer Science 8 valueOf safer than toString public static String valueOf(Object o) { return (o == null) ? “null” : o.toString(); }  Purely polymorphic and safe: Shape aShape = null; … String a = String.valueOf(aShape); // “null” String b = aShape.toString(); // nullPointerException
  • 9. Department of Computer Science 9 == on Strings String one = “One”; String two = new String(one); // copy of one String three = String.valueOf(one); // ref to one System.out.println((one == two)); // “false” System.out.println((one == three)); // “true”
  • 10. Department of Computer Science 10 StringBuffer  More like strings in C (arrays of char), can be modified: StringBuffer strbuf = new StringBuffer(“hope”); strbuf.setCharAt(0,’c’);  Constructors: StringBuffer(String initial), StringBuffer(int capacity)  append, insert, and reverse modify buffer and return this thus allowing for cascaded calls: strbuf.append(“ with ”).append(“209”);  setCharAt, charAt,  length, setLength, ensureCapacity, toString
  • 11. Department of Computer Science 11 StringTokenizer  Breaks a string into a sequence of tokens,  tokens are defined by delimiters (e.g. space)  Implements the Enumeration protocol public StringTokenizer(String s) public StringTokenizer(String s, String delims) public boolean hasMoreElements() public Object nextElement() public String nextToken() public int countTokens() // remaining tokens
  • 12. Department of Computer Science 12 StringTokenizer example public void readLines (DataInputStream input) throws IOException { String delims = “ tn.,!?;:”; for(int line = 1; true; line++) { String text = input.readLine(); if (text==null) return; text = text.toLowerCase(); StringTokenizer e = new StringTokenizer(text,delim); while( e.hasMoreElements()) }}
  • 13. Department of Computer Science 13 Parsing String Values  For primitive data types wrapper classes provide parsing from strings and back: String dstr = “23.7”; Double dwrap = new Double(dstr); double dval = dwrap.doubleValue();  Instead of constructor: double dval = Double.parseDouble(“23.7”); enterWord(e.nextToken(), new Integer(line));  Similar for ints, booleans, longs, and floats
  • 14. Department of Computer Science 14 System  Supplies system-wide resources:  Streams: System.in, System.out, System.err  System.exit(int) terminates a program  SystemDemo.java
  • 15. Department of Computer Science 15 Examples  Write a program palindrome in two ways: First, using StringBuffer (and reverse) • public StringBuffer reverse( ) Second, using • public char charAt(int index)  Eliza psychiatric help  Supply the name of a file as argument and count the number of lines, words and characters in the file (tips).