1. The document discusses library classes and methods in the String class in Java.
2. It explains that Strings are immutable class objects, not primitive types, and the Java Virtual Machine can optimize memory usage by sharing String objects between variables when the literal is the same.
3. When comparing Strings for equality, the equals method should be used instead of the == operator, as == checks for reference equality rather than value equality of Strings.
This document discusses strings and string buffers in Java. It defines strings as sequences of characters that are class objects implemented using the String and StringBuffer classes. It provides examples of declaring, initializing, concatenating and using various methods like length(), charAt() etc. on strings. The document also introduces the StringBuffer class for mutable strings and lists some common StringBuffer functions.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
This document discusses Java strings and provides information about:
1. What strings are in Java and how they are treated as objects of the String class. Strings are immutable.
2. Two ways to create String objects: using string literals or the new keyword.
3. Important string methods like concatenation, comparison, substring, and length; and string classes like StringBuffer and StringBuilder that allow mutability.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
This document discusses strings and string buffers in Java. It defines strings as sequences of characters that are class objects implemented using the String and StringBuffer classes. It provides examples of declaring, initializing, concatenating and using various methods like length(), charAt() etc. on strings. The document also introduces the StringBuffer class for mutable strings and lists some common StringBuffer functions.
This document discusses arrays in Java programming. It covers defining and creating single and multi-dimensional arrays, accessing array elements using indexes and loops, and performing operations like sorting and finding maximum/minimum values. Examples are provided for different array types like integer, string and character arrays, and operations like input/output, break/continue statements, and star patterns. Homework involves writing a program to produce a given output pattern.
This document discusses Java strings and provides information about:
1. What strings are in Java and how they are treated as objects of the String class. Strings are immutable.
2. Two ways to create String objects: using string literals or the new keyword.
3. Important string methods like concatenation, comparison, substring, and length; and string classes like StringBuffer and StringBuilder that allow mutability.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
This document provides an overview of threads in Java, including:
- Threads allow for multitasking by executing multiple processes simultaneously. They are lightweight processes that exist within a process and share system resources.
- Threads can be created by extending the Thread class or implementing the Runnable interface. The run() method defines the code executed by the thread.
- Threads transition between states like new, runnable, running, blocked, and dead during their lifecycle. Methods like start(), sleep(), join(), etc. impact the thread states.
- Synchronization is used to control access to shared resources when multiple threads access methods and data outside their run() methods. This prevents issues like inconsistent data.
This document discusses implementation of inheritance in Java and C#. It covers key inheritance concepts like simple, multilevel, and hierarchical inheritance. It provides examples of inheritance in Java using keywords like extends, super, this. Interfaces are discussed as a way to achieve multiple inheritance in Java. The document also discusses implementation of inheritance in C# using concepts like calling base class constructors and defining virtual methods.
The document discusses key aspects of the Java class library including documentation, interfaces, implementations, access modifiers, and common classes. It provides examples of using library classes like Random and maps. It emphasizes the importance of understanding library documentation and being able to use classes from documentation without seeing implementations.
The document discusses arrays in C programming. It defines arrays as fixed-size collections of elements of the same data type that allow storing and processing large amounts of data. Arrays can be one-dimensional, two-dimensional or multi-dimensional. One-dimensional arrays use a single subscript to identify elements, while two-dimensional arrays use two subscripts to represent rows and columns. The document provides examples of declaring, initializing, and using one-dimensional and two-dimensional arrays in C code.
This document discusses abstract classes in C++. It defines an abstract class as a class designed to be used as a base class that cannot be instantiated and must contain at least one pure virtual function. It provides an example of how to declare an abstract class with a pure virtual function and how to derive a class from an abstract class, overriding the pure virtual functions. The importance of abstract classes is that they allow common functionality to be defined for derived classes while leaving implementation details to the derived classes.
The document discusses method overloading and overriding in Java. It defines method overloading as having multiple methods with the same name but different parameters, while overriding involves subclasses providing specific implementations of methods in the parent class. It provides examples of overloading methods by changing parameters and data types, and explains why overriding is not possible by only changing the return type due to ambiguity. The use of the super keyword to refer to parent class members is also explained.
A list in Python is a mutable ordered sequence of elements of any data type. Lists can be created using square brackets [] and elements are accessed via indexes that start at 0. Some key characteristics of lists are:
- They can contain elements of different types
- Elements can be modified, added, or removed
- Common list methods include append(), insert(), remove(), pop(), and sort()
Classes allow users to bundle data and functions together. A class defines data members and member functions. Data members store data within each object, while member functions implement behaviors. Classes support access specifiers like public and private to control access to members. Objects are instances of classes that allocate memory for data members. Member functions can access object data members and are called on objects using dot notation. Friend functions allow non-member functions to access private members of classes.
The document discusses the static keyword in Java and its uses for variables, methods, blocks and nested classes. It explains that static members belong to the class rather than instances, and provides examples of static variables, methods, blocks and how they work. Key points include static variables having only one copy in memory and being shared across instances, static methods that can be called without an instance, and static blocks that initialize static fields when the class loads.
This document discusses interfaces in Java. It defines an interface as a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. They represent an "is-a" relationship. There are three main reasons to use interfaces - for abstraction, to support multiple inheritance functionality, and to achieve loose coupling. The document provides examples of interfaces, such as a Printable interface and implementations in different classes. It also demonstrates multiple inheritance using interfaces and interface inheritance.
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
This document introduces method overloading and method overriding in Java. Method overloading allows a class to have multiple methods with the same name but different parameters. It increases readability. Method overriding allows a subclass to provide a specific implementation of a method declared in the parent class. It is used for runtime polymorphism where the method being called is determined by the object type. The document provides examples of method overloading by changing number/type of arguments and of method overriding where the subclass overrides the parent's display method.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
Wrapper classes allow primitive data types to be used as objects. Wrapper classes include Integer, Double, Boolean etc. Strings in Java are immutable - their values cannot be changed once created. StringBuffer and StringBuilder can be used to create mutable strings that can be modified. StringTokenizer can split a string into tokens based on a specified delimiter.
The document discusses constructors and destructors in C++. It describes constructor functions as special member functions that initialize object values when an object is created. It covers default constructors, parameterized constructors, copy constructors, and constructor overloading. Destructors are described as special functions that destroy objects and perform cleanup when objects go out of scope. The key characteristics and uses of constructors and destructors are summarized with examples.
Constructors, Destructors, call in parameterized Constructor, Multiple constructor in a class, Explicit/implicit call, Copy constructor, Dynamic Constructors and call in parameterized Constructor
This document provides information about applets including:
- Applets are small programs that can be embedded in web pages and run within web browsers. They allow for dynamic and interactive content.
- There are two types of applets: local applets stored on the local system and remote applets stored on remote servers.
- The lifecycle of a Java applet involves init(), start(), stop(), destroy(), and paint() methods being called in a specific order when the applet loads and runs in the browser.
The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. It describes different types of exceptions like checked exceptions and unchecked exceptions. It explains how to use try, catch, throw, throws and finally keywords to handle exceptions. The try block contains code that might throw exceptions. The catch block catches and handles specific exceptions. The finally block contains cleanup code that always executes regardless of exceptions. The document provides examples of exception handling code in Java.
The document provides an overview of key concepts in C++, including:
1) C++ adds object-oriented programming capabilities to C while maintaining C's power and flexibility. It was created in 1979 to provide object-oriented programming features to C.
2) Object-oriented programming encourages breaking problems into constituent parts called objects that contain related instructions and data. The three main traits of OOP are encapsulation, polymorphism, and inheritance.
3) C++ supports both traditional and modern styles, with newer headers placed in the std namespace. Keywords like class, public, and virtual allow defining classes and controlling access to members. Functions can be overloaded if their signatures differ.
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
CONSTRUCTOR AND DESTRUCTOR PPT BASED ON OOP SUBJECT ......FULLY CONCEPT EXPLAINED WITH SAMPLE PROGRAM IN IT .....FOR MORE SLIDES PLEASE FOLLOW ME ..... THANK YOU
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
ObjectivesMore practice with recursion.Practice writing some tem.docxvannagoforth
Objectives
More practice with recursion.
Practice writing some template functions.
Use stack ADT to implement given algorithms.
Look at some common applications of stacks.Description
In this assignment, you will be using the Stack abstract data type we developed this week and discussed in our weeks lectures, to implement 4 functions that use a stack data type to accomplish their algorithms. The functions range from relatively simple, straight forward use of a stack, to a bit more complex. But in all 4 cases, you should only need to use the abstract stack interface functions push(), pop(), top(), and isEmpty() in order to successfully use our Stack type for this assignment and the function you are asked to write.
For this assignment you need to perform the following tasks.
1. In the rst task, we will write a function that will check if a string of parenthesis is matching. Strings will be given to the function of the format "(()((())))", using only opening "(" and closing ")". Your function should be named doParenthesisMatch(). It takes a single string as input, and it returns a boolean result of true if the parenthesis match, and false otherwise.
The algorithm to check for matching parenthesis using a stack is fairly simple. A pseudo-code description migth be
for each charcter c in expression do
if c is an open paren ’(’ push it on stack
if c is a close paren ’)’:
do
if stack is empty
answer is false, because we can’t match the current ’)’
else pop stack, because we just matched an open ’(’ with a close ’)’
done
done
Your function will be given a C++ string class as input. It is relatively simple to parse each character of a C++ string. Here is an example for loop to do this:
s = "(())";
for (size_t index = 0; index < s.length(); index++)
{ char c = s[index];
// handle char c of the string expression s here }
2. In the next task, we will also write a function that decodes a string expression. Given a sequence consisting of ’I’ and ’D’ characters, where ’I’ denotes increasing and ’D’ denotes decreasing, decode the given sequence to construct a "minimum number" without repeated digits.
An example of some inputs and outputs will make it clear what is meant by a "minimal number".
sequence
output
IIII
->
12345
DDDD
->
54321
ID
->
132
IDIDII
->
1325467
IIDDIDID
->
125437698
If you are given 4 characters in the input sequence, the result will be a number with 5 characters, and further only the digits ’12345’ would be in the "minimal number" output. Each ’I’ and ’D’ in the input denotes that the next digit in the output should go up (increase) or go down (decrease) respectively. As you can see for the input sequence "IDI" you have to accommodate the sequence, thus the output goes from 1 to 3 for the initial increase, becase in order to then decrease, and also only have the digits ’123’, we need 3 for the second digit so the third can decrease to 2.
Take a moment to think how you might write an algorithm to solve this problem? It may be di cult to thi ...
This document provides an overview of key concepts in Java including Eclipse IDE, creating classes, the main method, printing output, variables, data types, user input, arithmetic operators, and typecasting. It explains how to create a Java class in Eclipse, use print statements, declare and initialize variables, take user input, and perform basic math operations and conversions between data types in Java.
The document discusses key aspects of the Java class library including documentation, interfaces, implementations, access modifiers, and common classes. It provides examples of using library classes like Random and maps. It emphasizes the importance of understanding library documentation and being able to use classes from documentation without seeing implementations.
The document discusses arrays in C programming. It defines arrays as fixed-size collections of elements of the same data type that allow storing and processing large amounts of data. Arrays can be one-dimensional, two-dimensional or multi-dimensional. One-dimensional arrays use a single subscript to identify elements, while two-dimensional arrays use two subscripts to represent rows and columns. The document provides examples of declaring, initializing, and using one-dimensional and two-dimensional arrays in C code.
This document discusses abstract classes in C++. It defines an abstract class as a class designed to be used as a base class that cannot be instantiated and must contain at least one pure virtual function. It provides an example of how to declare an abstract class with a pure virtual function and how to derive a class from an abstract class, overriding the pure virtual functions. The importance of abstract classes is that they allow common functionality to be defined for derived classes while leaving implementation details to the derived classes.
The document discusses method overloading and overriding in Java. It defines method overloading as having multiple methods with the same name but different parameters, while overriding involves subclasses providing specific implementations of methods in the parent class. It provides examples of overloading methods by changing parameters and data types, and explains why overriding is not possible by only changing the return type due to ambiguity. The use of the super keyword to refer to parent class members is also explained.
A list in Python is a mutable ordered sequence of elements of any data type. Lists can be created using square brackets [] and elements are accessed via indexes that start at 0. Some key characteristics of lists are:
- They can contain elements of different types
- Elements can be modified, added, or removed
- Common list methods include append(), insert(), remove(), pop(), and sort()
Classes allow users to bundle data and functions together. A class defines data members and member functions. Data members store data within each object, while member functions implement behaviors. Classes support access specifiers like public and private to control access to members. Objects are instances of classes that allocate memory for data members. Member functions can access object data members and are called on objects using dot notation. Friend functions allow non-member functions to access private members of classes.
The document discusses the static keyword in Java and its uses for variables, methods, blocks and nested classes. It explains that static members belong to the class rather than instances, and provides examples of static variables, methods, blocks and how they work. Key points include static variables having only one copy in memory and being shared across instances, static methods that can be called without an instance, and static blocks that initialize static fields when the class loads.
This document discusses interfaces in Java. It defines an interface as a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. They represent an "is-a" relationship. There are three main reasons to use interfaces - for abstraction, to support multiple inheritance functionality, and to achieve loose coupling. The document provides examples of interfaces, such as a Printable interface and implementations in different classes. It also demonstrates multiple inheritance using interfaces and interface inheritance.
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
This document introduces method overloading and method overriding in Java. Method overloading allows a class to have multiple methods with the same name but different parameters. It increases readability. Method overriding allows a subclass to provide a specific implementation of a method declared in the parent class. It is used for runtime polymorphism where the method being called is determined by the object type. The document provides examples of method overloading by changing number/type of arguments and of method overriding where the subclass overrides the parent's display method.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
Wrapper classes allow primitive data types to be used as objects. Wrapper classes include Integer, Double, Boolean etc. Strings in Java are immutable - their values cannot be changed once created. StringBuffer and StringBuilder can be used to create mutable strings that can be modified. StringTokenizer can split a string into tokens based on a specified delimiter.
The document discusses constructors and destructors in C++. It describes constructor functions as special member functions that initialize object values when an object is created. It covers default constructors, parameterized constructors, copy constructors, and constructor overloading. Destructors are described as special functions that destroy objects and perform cleanup when objects go out of scope. The key characteristics and uses of constructors and destructors are summarized with examples.
Constructors, Destructors, call in parameterized Constructor, Multiple constructor in a class, Explicit/implicit call, Copy constructor, Dynamic Constructors and call in parameterized Constructor
This document provides information about applets including:
- Applets are small programs that can be embedded in web pages and run within web browsers. They allow for dynamic and interactive content.
- There are two types of applets: local applets stored on the local system and remote applets stored on remote servers.
- The lifecycle of a Java applet involves init(), start(), stop(), destroy(), and paint() methods being called in a specific order when the applet loads and runs in the browser.
The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. It describes different types of exceptions like checked exceptions and unchecked exceptions. It explains how to use try, catch, throw, throws and finally keywords to handle exceptions. The try block contains code that might throw exceptions. The catch block catches and handles specific exceptions. The finally block contains cleanup code that always executes regardless of exceptions. The document provides examples of exception handling code in Java.
The document provides an overview of key concepts in C++, including:
1) C++ adds object-oriented programming capabilities to C while maintaining C's power and flexibility. It was created in 1979 to provide object-oriented programming features to C.
2) Object-oriented programming encourages breaking problems into constituent parts called objects that contain related instructions and data. The three main traits of OOP are encapsulation, polymorphism, and inheritance.
3) C++ supports both traditional and modern styles, with newer headers placed in the std namespace. Keywords like class, public, and virtual allow defining classes and controlling access to members. Functions can be overloaded if their signatures differ.
The document provides information about strings in Java including:
1) Strings are objects in Java that are used to hold text data. The String class represents strings and provides various methods to work with strings.
2) There are two ways to create String objects: using string literals or the new keyword. String literals reuse existing objects in the string constant pool.
3) Important String class methods include charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), and trim(). These methods allow manipulating and accessing string values.
CONSTRUCTOR AND DESTRUCTOR PPT BASED ON OOP SUBJECT ......FULLY CONCEPT EXPLAINED WITH SAMPLE PROGRAM IN IT .....FOR MORE SLIDES PLEASE FOLLOW ME ..... THANK YOU
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
ObjectivesMore practice with recursion.Practice writing some tem.docxvannagoforth
Objectives
More practice with recursion.
Practice writing some template functions.
Use stack ADT to implement given algorithms.
Look at some common applications of stacks.Description
In this assignment, you will be using the Stack abstract data type we developed this week and discussed in our weeks lectures, to implement 4 functions that use a stack data type to accomplish their algorithms. The functions range from relatively simple, straight forward use of a stack, to a bit more complex. But in all 4 cases, you should only need to use the abstract stack interface functions push(), pop(), top(), and isEmpty() in order to successfully use our Stack type for this assignment and the function you are asked to write.
For this assignment you need to perform the following tasks.
1. In the rst task, we will write a function that will check if a string of parenthesis is matching. Strings will be given to the function of the format "(()((())))", using only opening "(" and closing ")". Your function should be named doParenthesisMatch(). It takes a single string as input, and it returns a boolean result of true if the parenthesis match, and false otherwise.
The algorithm to check for matching parenthesis using a stack is fairly simple. A pseudo-code description migth be
for each charcter c in expression do
if c is an open paren ’(’ push it on stack
if c is a close paren ’)’:
do
if stack is empty
answer is false, because we can’t match the current ’)’
else pop stack, because we just matched an open ’(’ with a close ’)’
done
done
Your function will be given a C++ string class as input. It is relatively simple to parse each character of a C++ string. Here is an example for loop to do this:
s = "(())";
for (size_t index = 0; index < s.length(); index++)
{ char c = s[index];
// handle char c of the string expression s here }
2. In the next task, we will also write a function that decodes a string expression. Given a sequence consisting of ’I’ and ’D’ characters, where ’I’ denotes increasing and ’D’ denotes decreasing, decode the given sequence to construct a "minimum number" without repeated digits.
An example of some inputs and outputs will make it clear what is meant by a "minimal number".
sequence
output
IIII
->
12345
DDDD
->
54321
ID
->
132
IDIDII
->
1325467
IIDDIDID
->
125437698
If you are given 4 characters in the input sequence, the result will be a number with 5 characters, and further only the digits ’12345’ would be in the "minimal number" output. Each ’I’ and ’D’ in the input denotes that the next digit in the output should go up (increase) or go down (decrease) respectively. As you can see for the input sequence "IDI" you have to accommodate the sequence, thus the output goes from 1 to 3 for the initial increase, becase in order to then decrease, and also only have the digits ’123’, we need 3 for the second digit so the third can decrease to 2.
Take a moment to think how you might write an algorithm to solve this problem? It may be di cult to thi ...
This document provides an overview of key concepts in Java including Eclipse IDE, creating classes, the main method, printing output, variables, data types, user input, arithmetic operators, and typecasting. It explains how to create a Java class in Eclipse, use print statements, declare and initialize variables, take user input, and perform basic math operations and conversions between data types in Java.
The document discusses various String methods in Java:
- The charAt() method returns the character at a given index in the String.
- The compareTo() method compares two Strings lexicographically and returns an integer indicating their relative ordering.
- The indexOf() method returns the index of the first occurrence of a character or substring in the given String. It has overloads to specify a starting index for the search.
This document is a Python cheat sheet created by Mosh Hamedani to summarize the core concepts covered in his Python tutorial. It includes sections on variables, data types, operators, control flow, functions, classes, modules and the standard library. The author encourages readers to enroll in his Complete Python Programming Course if they want to become a Python expert.
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
The document provides instructions for Assignment 09, which involves implementing four functions that use a stack data structure:
1. doParenthesisMatch() checks if a string of parentheses is properly matched and returns a boolean.
2. decodeIDSequence() decodes a string of 'I's and 'D's into a minimum number string without repeated digits.
3. insertItemOnSortedStack() inserts an item into a sorted stack.
4. sortStack() sorts an unsorted stack recursively.
Students are provided header and implementation files for a Stack ADT and tests, and must implement the functions in the given files while following style guidelines. The assignment evaluates correct implementation of the functions and stack usage,
Programming in Java: Arrays. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Are you Looking for the Best Institute for Java Online or Offline Training Course? PSK Technologies PVT.LTD. Nagpur offers Java training classes with live projects by expert trainers. Our Java training program is specially designed for Under-Graduates (UG), Graduates, working professionals, and also for Freelancers. We provide end to end learning on Java Domain with deeper dives for creating a winning career for every profile.
Programming in Java: Organising Your Code. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
This document discusses how to take input from users in Java using the Scanner class. It provides examples of taking integer, double, character and string input. The Scanner class methods like nextInt(), nextDouble(), next() etc are used to read input. The document also contains sample code and explanations for taking input to calculate sum of two numbers, simple interest and reading a character.
This document discusses Java data types, variables, and methods. It covers primitive data types like int, float, and boolean. It describes rules for identifiers and conventions for naming variables and classes. The document defines parameter types, implicit and explicit parameters, and how to call methods. It explains constructing objects with the new operator and accessor and mutator methods. The summary concludes with a discussion of static methods and how to call them without an object.
This document provides an overview of strings and string processing in C#. It discusses the String class and how strings are implemented as objects in C#. Key methods of the String class like Length, IndexOf, Substring, Split, and Join are described. Algorithms for splitting a string into words and joining an array into a string are presented. Methods for comparing strings like Equals and CompareTo are also covered.
Arrays in C allow storing multiple values of the same data type in contiguous memory locations. An array is declared with a data type, array name, and size. Individual elements are accessed using the array name and index. Arrays are useful for storing lists of values, performing matrix operations, implementing algorithms like search and sort, and more. Strings in C are implemented as arrays of characters that are null-terminated. Functions like strcpy(), strcat(), strcmp() allow manipulating strings.
Programming in Java: Storing Data. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Question 1 1 pts Skip to question text.As part of a bank account.docxamrit47
Question 1 1 pts Skip to question text.
As part of a bank account implementation, there is an account class and a checking account class. These two classes should be related by:
polymorphism
abstract classes
both composition and inheritance
inheritance
composition
Flag this Question
Question 2 1 pts
When using OOP, which of the following terms refers to a mechanism for a behavior, basically how it’s implemented?
composition
inheritance
polymorphism
dynamic binding
Flag this Question
Question 3 1 pts
To access an element in an Array object,
Use the ArrayList's get() method.
Use the ArrayList's element() method.
Individual elements in an ArrayList can’t be accessed without doing a sequential query getSequential(), returning every element up to and including the element requested.
Use square brackets around an index value.
Flag this Question
Question 4 1 pts
To access an element in an ArrayList object,
Use square brackets around an index value.
Use the ArrayList element() method.
Use the ArrayList get() method.
Individual elements in an ArrayList can’t be accessed without doing a sequential query getSequential(), returning every element up to and including the element requested.
Flag this Question
Question 5 1 pts
What term below is defined as a message that tells the program that something has happened?
an interaction
a listener
an action
an event
Flag this Question
Question 6 1 pts
Which item below is defined as an object?
A String
An Array
All of the above
An ArrayList
Flag this Question
Question 7 1 pts
When a text-box-enter event occurs, which method and parameter are required to handle this type of action? (1 point)
actionEvent with an actionperformed parameter
actionListener with an interfaceID parameter
windowListener with an eventID parameter
actionPerformed with an actionEvent parameter
Flag this Question
Question 8 1 pts
Which class includes the setTitle and setSize methods?
JFrame
JWindow
JBox
JOptionpane
Flag this Question
Question 9 1 pts
Before utilizing the binary search method, __________ must be done to the array?
indexing
splitting
sorting
importing
Flag this Question
Question 10 1 pts
Which layout manager implements a one-compartment layout scheme?
GridlessLayout
GridBagLayout
GridLayout
FlowLayout
BorderLayout
Flag this Question
Question 11 1 pts
What is the default layout manager for a JFrame window?
GridBagLayout
GridLayout
FlowLayout
GridlessLayout
BorderLayout
Flag this Question
Question 12 1 pts
To call the superclass constructor, super() must be the first line in a constructor.
True
False
Flag this Question
Question 13 1 pts
Method overriding is when a method has the same name, same sequence of parameter types, and the same return type as a method in a superclass.
True
False
Flag this Question
Question 14 1 pts
Type casting, also known as promotion is ...
Swift is Apple's new programming language that is intended to replace Objective-C. It was created to address weaknesses in Objective-C like its unusual syntax, lack of modern features, and "C baggage". Swift keeps the best parts of Objective-C but brings modern features like type inference, closures, generics, and optionals. It also has a cleaner syntax that is more familiar to developers from other languages.
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
This document describes stacks and queues data structures and their application programming interfaces (APIs). It defines the common operations for stacks and queues, including push, pop, enqueue, and dequeue. It provides examples of using stacks and queues to evaluate postfix expressions and read input from a queue. Stacks and queues are widely used in applications like browsers, interpreters, and printing. The document also covers generics, autoboxing/unboxing, and real-world examples of stacks in programming languages and PostScript.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects have initial values before an object is used. The document provides examples of how to write constructors, how to overload constructors, and how to use the this keyword in constructors. It also discusses static initialization and the use of toString() methods.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects are properly initialized before use. The document provides examples of how to write classes with constructors and use constructor overloading. It also discusses static initialization, the this keyword, and recursion.
Similar to Programming in Java: Library Classes (20)
Principles of Health Informatics: Artificial intelligence and machine learningMartin Chapman
Principles of Health Informatics: Artificial intelligence and machine learning. Last delivered in 2024. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Clinical decision support systemsMartin Chapman
Principles of Health Informatics: Clinical decision support systems. Last delivered in 2024. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Martin Chapman
This document describes using search game models to explore complex public health issues like winter health service pressures. It discusses integrating real demographic and behavioral data into search game simulations to more accurately model these issues. An example application looks at modeling family resource acquisition challenges during winter and evaluating government intervention strategies to reduce pressures and inequalities. Integrating multiple real datasets allows configuring the search game model to replicate observed winter trends and assess intervention performance. The results suggest advising families is most effective at reducing health service utilization and disparities.
Technical Validation through Automated TestingMartin Chapman
The document discusses applying automated testing tools to the development of phenotypes to help ensure they operate correctly. It outlines how testing can be used at different stages of phenotype development: (1) during authoring by testing computable phenotype definitions, (2) during implementation by integrating testing frameworks, and (3) during validation as an additional validation technique through test cases. The document argues there is potential for more widespread use of automated testing in phenotype development similar to software development.
Scalable architectures for phenotype librariesMartin Chapman
The document discusses different architectural considerations for building phenotype libraries that are accessible at a large scale. It covers software architecture, definition structure, and distribution mechanisms. For software architecture, it advocates for a microservices approach to allow components to be built with different technologies and scaled independently. For definition structure, it presents Phenoflow's model that standardizes definitions and generates computable forms. For distribution, it notes the benefits of hosting definitions in version control systems like GitHub to improve discoverability. The overall goal is to make definitions easily located, downloaded, and interpreted by many users through careful library design.
Using AI to autonomously identify diseases within groups of patientsMartin Chapman
This FYP presentation discusses using AI to autonomously identify diseases within patient groups. The main functions are using a workflow to identify diseases, validating results with gold/silver standards, and using machine learning algorithms to generate silver standards from electronic health record data. The standard workflow requires installing tools like Cwltool and docker and providing test cases and gold references, while unsupervised learning algorithms generate silver standards from provided EHR data without supervision. Supervised learning additionally needs test cases, gold references, and unclassified data.
Using AI to understand how preventative interventions can improve the health ...Martin Chapman
Using AI and large UK datasets, the author digitally mimicked household environments of children and young people from different backgrounds to simulate preventative policy interventions and predict their effectiveness at improving health and reducing winter pressures on the NHS. The simulations found that issuing continued government advice during winter months could potentially reduce health utilization and disparities between socio-economic groups.
Principles of Health Informatics: Evaluating medical softwareMartin Chapman
Principles of Health Informatics: Evaluating medical software. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Usability of medical softwareMartin Chapman
Principles of Health Informatics: Usability of medical software. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Social networks, telehealth, and mobile healthMartin Chapman
Principles of Health Informatics: Social networks, telehealth, and mobile health. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Communication systems in healthcareMartin Chapman
Principles of Health Informatics: Communication systems in healthcare. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Terminologies and classification systemsMartin Chapman
Principles of Health Informatics: Terminologies and classification systems. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Informatics skills - searching and making d...Martin Chapman
This document discusses principles for searching for data and making decisions based on data from an informatics perspective. It covers search strategies for finding specific data within large datasets, using logical inference like deduction, abduction and induction to determine implications of new data, and using Bayes' theorem to update probabilities of outcomes when receiving new data while accounting for prior probabilities and sample sizes. Decision trees are presented as a way to combine multiple probabilities and include preferences through utilities to determine the highest utility decision.
Principles of Health Informatics: Informatics skills - communicating, structu...Martin Chapman
Principles of Health Informatics: Informatics skills - communicating, structuring, and questioning. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Models, information, and information systemsMartin Chapman
Principles of Health Informatics: Models, information, and information systems. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Using AI to understand how preventative interventions can improve the health ...Martin Chapman
Living in cold, damp homes can lead to poor health in children such as chest conditions and mental health problems in adolescents. With energy costs rising and wages not keeping pace with inflation, health issues for children and young people may worsen due to families' inability to afford home heating. An AI model was used to simulate how government advice and interventions could potentially reduce health care utilization and disparities between socioeconomic groups, though further validation is needed before implementing related policies.
Using Microservices to Design Patient-facing Research SoftwareMartin Chapman
Using microservices allows patient-facing research software to address challenges in software development, modularity, and processing time. The microservices architecture separates a system into individual communicating services, each providing a single functionality. This allows different languages to be used, logic to be replaced with minimal impact, and long execution times to be isolated. The CONSULT system demonstrates these benefits through its use of microservices to integrate data from various sources and provide decision support for stroke patients.
Using CWL to support EHR-based phenotypingMartin Chapman
This document describes a new Common Workflow Language (CWL)-based model for structuring electronic health record (EHR)-based phenotype definitions. Phenotype definitions are complex and lack standardization. The proposed model addresses this by representing definitions as workflows with abstract, functional, and computational layers. Non-standard definitions can be parsed and automatically generated as CWL workflows using the Phenoflow architecture. This standardizes definitions and makes them portable and reproducible.
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...EduSkills OECD
Andreas Schleicher, Director of Education and Skills at the OECD presents at the launch of PISA 2022 Volume III - Creative Minds, Creative Schools on 18 June 2024.
How to Download & Install Module From the Odoo App Store in Odoo 17Celine George
Custom modules offer the flexibility to extend Odoo's capabilities, address unique requirements, and optimize workflows to align seamlessly with your organization's processes. By leveraging custom modules, businesses can unlock greater efficiency, productivity, and innovation, empowering them to stay competitive in today's dynamic market landscape. In this tutorial, we'll guide you step by step on how to easily download and install modules from the Odoo App Store.
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.pptHenry Hollis
The History of NZ 1870-1900.
Making of a Nation.
From the NZ Wars to Liberals,
Richard Seddon, George Grey,
Social Laboratory, New Zealand,
Confiscations, Kotahitanga, Kingitanga, Parliament, Suffrage, Repudiation, Economic Change, Agriculture, Gold Mining, Timber, Flax, Sheep, Dairying,
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapitolTechU
Slides from a Capitol Technology University webinar held June 20, 2024. The webinar featured Dr. Donovan Wright, presenting on the Department of Defense Digital Transformation.
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...TechSoup
Whether you're new to SEO or looking to refine your existing strategies, this webinar will provide you with actionable insights and practical tips to elevate your nonprofit's online presence.
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxOH TEIK BIN
(A Free eBook comprising 3 Sets of Presentation of a selection of Puzzles, Brain Teasers and Thinking Problems to exercise both the mind and the Right and Left Brain. To help keep the mind and brain fit and healthy. Good for both the young and old alike.
Answers are given for all the puzzles and problems.)
With Metta,
Bro. Oh Teik Bin 🙏🤓🤔🥰
🔥🔥🔥🔥🔥🔥🔥🔥🔥
إضغ بين إيديكم من أقوى الملازم التي صممتها
ملزمة تشريح الجهاز الهيكلي (نظري 3)
💀💀💀💀💀💀💀💀💀💀
تتميز هذهِ الملزمة بعِدة مُميزات :
1- مُترجمة ترجمة تُناسب جميع المستويات
2- تحتوي على 78 رسم توضيحي لكل كلمة موجودة بالملزمة (لكل كلمة !!!!)
#فهم_ماكو_درخ
3- دقة الكتابة والصور عالية جداً جداً جداً
4- هُنالك بعض المعلومات تم توضيحها بشكل تفصيلي جداً (تُعتبر لدى الطالب أو الطالبة بإنها معلومات مُبهمة ومع ذلك تم توضيح هذهِ المعلومات المُبهمة بشكل تفصيلي جداً
5- الملزمة تشرح نفسها ب نفسها بس تكلك تعال اقراني
6- تحتوي الملزمة في اول سلايد على خارطة تتضمن جميع تفرُعات معلومات الجهاز الهيكلي المذكورة في هذهِ الملزمة
واخيراً هذهِ الملزمة حلالٌ عليكم وإتمنى منكم إن تدعولي بالخير والصحة والعافية فقط
كل التوفيق زملائي وزميلاتي ، زميلكم محمد الذهبي 💊💊
🔥🔥🔥🔥🔥🔥🔥🔥🔥
2. To understand how existing classes can be used to to
introduce additional functionality into our programs.
• To understand the meaning of the static keyword.
LIBRARY CLASSES: OBJECTIVES
2
4. REMEMBER: METHOD INPUT (1)
4
System.out.println("+------+");
System.out.println("| |");
System.out.println("+------+");
?
When considering method input (as opposed to just method
output; what a method returns), we asked the following
question:
What if I didn’t just want to print `Martin’ in a box to the
screen, but any number, an arbitrary number of times?
5. This lead to the introduction of the method, with
a single integer parameter.
REMEMBER: METHOD INPUT (2)
5
public class NumberPrinter {
public void printNumber(int num) {
System.out.println("+------+");
System.out.println("|" + num + "|");
System.out.println("+------+");
}
}
printNumber
6. What if we wanted to go through a similar process for a name
printer class (i.e. a generalised version of MartinPrinter)?
REMEMBER: METHOD INPUT (3)
6
public class NamePrinter {
public void printName( name) {
System.out.println("+------+");
System.out.println("|" + name + "|");
System.out.println("+------+");
}
}
?
Which datatype
should we
employ here?
7. It’s clear that we need some form of text datatype.
The formal name for this datatype is a String.
STRINGS (1)
7
public class NamePrinter {
public void printName(String name) {
System.out.println("+------+");
System.out.println("|" + name + "|");
System.out.println("+------+");
}
}
8. We have seen lots of String literals so far, but we haven’t yet
seen the String datatype.
STRINGS (2)
8
String martin = "Martin";
A variable of the String datatype is declared and assigned
in a familiar way (type followed by name with the optional
assignment of a literal), so why didn’t I discuss String with
the other primitive types?
We can answer this question by first considering a
problem…
9. In the previous topic (Exercise Topic5-2), I asked you to consider
how to ensure that each account requires a different pin.
STORING PINS (1)
9
public class BankAccount {
private double balance;
private int pin;
public BankAccount(int pin) {
this.pin = pin;
}
You probably
implemented something
along these lines.
public void withdraw(double amount, int pin) {
if ( pin == this.pin ) {
balance = balance - amount;
} else {
System.out.println("Ah ah ah, you didn't say the magic word.");
}
}
11. Rather than storing a user’s pin in plaintext it makes sense that we
should add some simple encryption to that pin.
STORING PINS (2): SIMPLE ENCRYPTION
11
public class BankAccount {
private double balance;
private int pin;
public BankAccount(int pin) {
this.pin = pin + 1000;
}
For example we might add 1000 to it when storing it, then
subtract 1000 from it when testing the pin.
public void withdraw(double amount, int pin) {
if ( pin == this.pin - 1000 ) {
balance = balance - amount;
} else {
System.out.println("Ah ah ah, you didn't say the magic word.");
}
}
12. Now that we know about strings, we could evolve our
____________class into an OnlineBankAccoun, which requires
a user to supply a password for entry, rather than a pin.
The first modification to the standard BankAccount class
should be clear:
STORING PASSWORDS (1)
12
public class OnlineBankAccount {
private String password;
public OnlineBankAccount(String password) {
this.password = password;
}
BankAccount OnlineBankAccount
13. 🤔
The use of passwords, which are often required to contain
special characters, prompts the question: which characters
can Java strings hold?
Java string support UTF-16, which is an encoding type that
captures a large range of characters.
• Still, be careful when adding special characters into your
program.
• If the Java compiler complains, it may be worth replacing
these characters with escaped unicode hex values.
ASIDE: WHICH CHARACTERS CAN I PLACE IN A STRING?
13
System.out.println("u00E9");
14. What about encrypting String passwords, in the same way
that we did with the numeric pin?
It might be a nice idea to reverse the password, to avoid
storing it in plaintext.
How would we go about doing this?
STORING PASSWORDS (2): SIMPLE ENCRYPTION (1)
14
15. public String encrypt(String password) {
}
In (slightly more descriptive) pseudocode, we want to do
something similar to the following:
STORING PASSWORDS (2): SIMPLE ENCRYPTION (2)
15
Declare an empty string
Starting at the end of the supplied password,
go backwards through each character in that
password:
Take the appropriate character and add it
to the empty string.
We should first capture
this functionality in a
method.
16. Declaring the empty String is straight forward.
• If we want an empty String, we must give our String an empty
literal as, like primitive types, Strings do not have default values.
STORING PASSWORDS (2): SIMPLE ENCRYPTION (3)
16
public String encrypt(String password) {
}
String reversedString = "";
Take the appropriate character and add it
to the empty string.
Starting at the end of the supplied password,
go backwards through each character in that
password:
17. Strings are actually abstractions over collections of characters.
• This will be a familiar notion to those with a C/C++
background.
As such, we can imagine Strings in the following way:
ASIDE: STRINGS AND CHARACTERS
17
"Martin"
‘M’,‘a’,‘r’,‘t’,‘i’,‘n’
Character 0 Character 1 Character 2 Character 3
Character 4
Character 5
In Topic 2 (Topic2-2) you
should have found that
character literals are
enclosed in single quotes.
18. Because of this breakdown, we can imagine each character
in a string as having an index.
• This means that there is a distinct difference between
the length of a string and the last index.
ASIDE: INDEX VS. LENGTH
18
‘M’,‘a’,‘r’,‘t’,‘i’,‘n’ Character 5
Length = 6.
We can leverage this idea in order to approach our current
problem.
19. We define a loop with the first index value equal to the
length of the string minus 1 (remember index vs. length) and
then go backwards through that loop.
STORING PASSWORDS (2): SIMPLE ENCRYPTION (4)
19
public String encrypt(String password) {
}
String reversedString = "";
Take the appropriate character and add it
to the empty string.
String length - 1for ( int i = ; i >= 0; i-- ) {
}
How do we do these two things?
20. We use the value of the index within the loop to perform a
repeated operation: reading an individual character from the
password string and adding it to our string variable.
STORING PASSWORDS (2): SIMPLE ENCRYPTION (5)
20
public String encrypt(String password) {
String reversedString = "";
for ( int i = password.length() - 1; i >= 0; i-- ) {
reversedString += password.charAt(i);
}
return reversedString;
}
Gives us the length of the string.
Gives us the character at a
given index in the string.
22. Remember we’ve seen two uses of the plus symbol.
ASIDE: BACK TO CONCATENATION
22
System.out.println("|" + num + "|");
balance = balance + amount;
The former we referred to as concatenation.
We can now formalise the rule for when concatenation
occurs: if either of the operands to an addition are strings,
the operation will be treated as a concatenation.
reversedString += password.charAt(i);
reversedString = "ni" + "t";
Here we see
concatenation
again.
23. If we want to overwrite this default behaviour, in order to,
say, print the result of some arithmetic, we can do so using
brackets.
ASIDE: BRACKETS AND CONCATENATION
23
System.out.println("|" + (1 + 2) + "|");
System.out.println("|" + 1 + 2 + "|");
24. These looks like method calls, which very much suggests that
this string variable is an object.
But why, then, do we define a new string like a primitive type…
STRING: PRIMITIVE TYPE OR CLASS?
24
Is String a primitive type or a class?
password.length() password.charAt(i);
…instead of like a class type?
String martin = "Martin";
String martin = new String("Martin");
(Although
this works
too; we’ll
see this
shortly.)
25. I didn’t discuss strings along with the other primitive types because
the answer to this question is complex.
String variables can be declared and assigned in the same way as
primitive type variables, but, behind the scenes, the String type is
actually a class (open question: where does this class come from?),
and String variables thus contain copies of this class.
• This allows us to declare variables of a commonly used
datatype, and construct literals of this type, effectively, without
having to use the new command.
• We can use the String type in typical places (because we’ve
learnt that class types can replace primitive types).
• More importantly, when we don’t explicitly request a copy of
the String class, we allow the JVM to decide whether to give us
a new copy or not.
STRINGS (3)
25
26. It’s often the case that we use the same strings throughout
a class.
COPYING STRINGS (1)
26
public void deposit(double amount) {
balance = balance + amount;
System.out.println("Your current balance is: " + balance);
}
public void withdraw(double amount) {
balance = balance - amount;
System.out.println("Your current balance is: " + balance);
}
27. COPYING STRINGS (2)
27
public class Driver {
public static void main(String[] args) {
Pair pairA = new Pair();
Pair pairB = new Pair();
pairA.setPair(1, 2);
pairB.setPair(3, 4);
System.out.println(pairA.getValueA());
System.out.println(pairB.getValueA());
}
}
public class Pair {
private int valueA;
private int valueB;
public void setPair(int passed
valueA = passedValueA;
valueB = passedValueB;
}
int getValueA() {
return valueA;
}
public int getValueB() {
return valueB;
}
}
public class Pair {
private int valueA;
private int valueB;
public void setPair(int passed
valueA = passedValueA;
valueB = passedValueB;
}
int getValueA() {
return valueA;
We are familiar with the convention of storing different copies of a
class as objects.
28. If it were also the convention to declare strings in this way,
any duplicate Strings would be separate copies.
• This is, naturally, inefficient.
COPYING STRINGS (3)
28
public static void main(String[] args) {
String a = new String("A");
String b = new String("A");
String c = new String("A");
String d = new String("A");
}
'A'
'A'
'A'
'A'
String class
copy
Field in
String class
29. So, instead, the convention is that we don’t explicitly use the new
command, but instead allow the JVM to provide us with new copies of
the String class at its discretion, depending on the string literal used.
• The JVM can thus choose to optimise by giving us one copy, which
is then shared amongst all the variables, when all of the strings
requested are identical.
COPYING STRINGS (4)
29
public static void main(String[] args) {
String a = "A";
String b = "A";
String c = "A";
String d = "A";
}
'A''A''A''A'
We can view the use of a literal
here as an abstraction over the
new command.
30. 😴
In order to avoid global changes to the shared copy, strings
copies are immutable (opposite of a mutable class, where
the state (fields) can be changed by mutator methods).
Open question (for next semester): Can we share copies of
our own classes?
COPYING STRINGS (5)
30
public static void main(String[] args) {
String a = "A";
String b = "A";
String c = "A";
String d = "A";
}
'A''A''A''A'
31. 😴
REMEMBER: OBJECTS IN MEMORY
31
In reality, unlike primitive values, objects are stored in
another area of the JVM’s memory known as the heap. The
variable containing the copy of the class is actually a
memory reference from a variable on the stack to an object
on the heap.
We will use the definition of an object quite loosely in the first
semester of PPA, in order to simplify things, and help your initial
understanding.
We’ll look at
this in more
detail next
semester.
32. 😴
There are several other phenomena that show that we’re
simplifying things at this stage.
ASIDE: INTERACTING WITH A CLASS COPY WITHOUT A VARIABLE
32
new MartinPrinter().printMartin();
copyOfMartinPrinter.printMartin();
For example, we can interact with copies of a class without
placing that copy into a variable.
password.length()
"mypassword".length();
33. In order to confirm that the JVM is sharing copies between
our variables, we can use the familiar comparison operator.
• This will print true.
BACK TO COPYING STRINGS: ASKING ABOUT COPIES
33
public static void main(String[] args) {
String a = "A";
String b = "A";
String c = "A";
String d = "A";
}
System.out.println(a == b);
We ask the JVM, `are you sharing the
same string copy between a and b’?
Are a and b equivalent in memory?
This answer one of our open questions
about the flexibility of relational
operators.
34. There are lots of benefits to allowing the JVM control over the
management of string copies.
However there are also drawbacks.
COMPARING STRINGS (1)
34
public static void main(String[] args) {
String martin = "martin";
String mart = "mart";
String in = "in";
System.out.println(mart + in);
System.out.println(martin);
System.out.println(martin == mart + in);
}
What will the following print?
35. COMPARING STRINGS (2)
35
This occurs because the JVM stores the strings ______ and
____ separately even when they are concatenated, and
are thus effectively the same string.
"mart"
"in"
36. So, although the equality operator might look like a valid
way to compare strings, it is not.
Really we want to examine the content of the strings when
checking their equality rather than simply asking about the
organisation of memory.
So, the past few slides have been a roundabout way of
saying when you compare strings, you are advised to do so
in the following way:
COMPARING STRINGS (3)
36
37. 😴
We use the .equals method in the String class* to compare
strings.
COMPARING STRINGS (4)
37
public static void main(String[] args) {
String martin = "martin";
String mart = "mart";
String in = "in";
System.out.println(mart + in);
System.out.println(martin);
System.out.println(martin == mart + in);
System.out.println(martin.equals(mart + in));
}
*it actually exists elsewhere, more to come.
39. Given this notion, we can now return to our our online bank
account, and implement the correct syntax for checking that a
password is correct:
BACK TO OUR ONLINE BANK ACCOUNT
39
public void withdraw(double amount, String password) {
if ( encrypt(password).equals(this.password) ) {
balance = balance - amount;
} else {
System.out.println("Ah ah ah, you didn't say the magic word.");
}
}
40. Let’s solve the following problem using the methods in the
String class (for practice):
• Given a string, I want to determine if all the characters
in that string are unique.
LECTURE EXERCISE: STRING MANIPULATION (1)
40
41. LECTURE EXERCISE: STRING MANIPULATION (2)
41
public boolean isUnique(String word) {
for ( int i = 0; i < word.length(); i++ ) {
if ( !(i == word.lastIndexOf(word.charAt(i))) ) return false;
}
return true;
}
Note the brackets here so that it’s
clear what the unary negation
refers to.
One potential solution:
42. 🖥
In the laboratories, consider the following problems
involving string manipulation (you may need to finish this
topic before attempting some of these):
• Determining whether a given string is a palindrome (the
same word when reversed e.g. racecar).
• Determine whether a given sentence is a palindrome
(e.g. Euston saw I was not Sue).
MORE STRING MANIPULATION
42Topic6-1
43. How did I know that this was the way in which to check for a
string’s length, and to extract a character from a string,
respectively?
• How did I know these methods existed?
We also asked where does this String class come from?
The answer to the latter is the Java library, while the answer
to the former is because the Java library is documented.
TAKING A STEP BACK…
43
password.length() password.charAt(i);
45. So far, we’ve looked at how capturing our code in classes allows
them to become reusable.
Unsurprisingly, we aren’t the first people to recognise this idea.
In fact, Java comes with lots of classes that already capture existing
piece of functionality.
• These classes are written for us by other people (typically
those who design the Java language).
• This is part of why it makes sense to teach you about classes
first.
We call these library classes.
The String class is an example of a library class.
OUR CLASSES VS. LIBRARY CLASSES
45
46. ASIDE: JDK VS. JVM VS. JDE
46
JDK
JRE
JVM
Java Libraries
Java Compiler
Library classes exist as part of the software we use to run
our programs.
47. To help us understand the functionality offered by library
classes, Java provides us with documentation for each of
these classes.
• This is often known as the Java API, but in reality the
term `API’ has a more comprehensive meaning.
JAVA DOCUMENTATION (1)
47
Googling `Java’,
followed by the
name of a class
typically yields the
documentation for
that class as the
top result.
48. 🙈
It’s because of this documentation that we are aware of the
capabilities (i.e. the methods available) of the String class.
JAVA DOCUMENTATION (2)
48
49. 😴
We use documentation to help us understand our own code, but
remember it’s also a useful tool in helping other people to
understand our code.
REMEMBER: CONTROL 1: DOCUMENTING YOUR CODE (1)
49
Accessible code documentation is something that’s indirectly
supported by object-orientation (more later).
This doesn’t stop people using your code incorrectly, but
reduces the risk of it happening.
/**
* Prints the supplied number surrounded by a box.
*/
public void printNumber(int num) {
System.out.println("+------+");
System.out.println("|" + num + "|");
System.out.println("+------+");
}
50. 🙈
BACK TO CONTROL (1)
50
/**
* Prints the supplied number surrounded by a box.
*/
public void printNumber(int num) {
System.out.println("+------+");
System.out.println("|" + num + "|");
System.out.println("+------+");
}
Object-orientation
supports accessible
documentation by
encouraging us to split our
code into methods, which
we then comment, and
these comments then
feature in generated
documentation.
51. 😴
We can make our own small (offline) addition to the Java
documentation.
BACK TO CONTROL (2)
51
53. In order to make our programs more interactive, it’s often important to
ask a user for input.
USER INPUT (1)
53
starter.setCalories(140);
These are typically non-technical users who interact with our
program while it is running.
We have previously considered technical users (e.g. other
developers) who are likely to interact with our program (i.e. our
classes) while they are developing.
We might consider a
more user friendly
version of Assignment 2,
which allows for calories
to be input while the
program is running.
54. In Java, we typically take user input from the command line.
USER INPUT (2)
54
When user input is taken from the command line (while the
program is running), the program pauses and waits for the
user to enter information into the terminal.
This information can then be used in the program.
55. To create this behaviour ourselves would obviously be quite
difficult, and as such it makes sense that we should look for
some existing code (a library class), to help us out.
There is a distinct process to go through when we want to
use a library class in our program:
• Discover which library class is appropriate for our
needs.
• Add that library class to our program.
• Use the documentation to determine how to use that
class.
USING A LIBRARY CLASS IN OUR PROGRAM
55
56. Determining which library classes will fulfil our needs (in
this case user input), can be done in a number of ways.
• Typical language resources (web searches, books,
lecture notes, etc.).
• Existing documentation.
• Links will often exist in the pages of the Java
documentation, for example, to other classes.
• Experience from other languages.
USING A LIBRARY CLASS IN OUR PROGRAM: DISCOVERY
56
57. For user input, the class we need is called Scanner.
THE SCANNER CLASS
57
58. 😴
Classes are useful to us because they offer public methods
that contain some functionality.
Remember our current rule is that any public methods
within a class within our own program can be accessed by
any other class within our program.
• This is true given the current way in which we are
organising our classes, but will change when we add
additional organisation next semester.
What about public methods in classes that are not in our
program, such as Scanner?
USING A LIBRARY CLASS IN OUR PROGRAM: ADDING A CLASS
58
59. If we want to access the methods of, or indeed make objects of, a
class that existing within an external library (or another package;
more next term), we have to import that class into our program.
This allows us to reference that class as if it were one of our own,
and thus make objects of it, and call public methods.
• But we can’t edit it directly.
• We are now the users of classes written by other people.
In the case of Scanner this necessitates the following import
statement (at the top of a class):
IMPORTING CLASSES (1)
59
import java.util.Scanner;
60. 😴
What this dot structure means should become clear next
semester, but for now it suffices to say that this information
can be gleaned from the documentation itself.
IMPORTING CLASSES (2): DOT STRUCTURE
60
import java.util.Scanner;
61. TRACKING A USER’S CALORIES (1)
61
import java.util.Scanner;
public class CalorieTracker {
public static void main(String[] args) {
If we want to facilitate user input in our calorie tracker
program, we need to import the Scanner class.
62. Earlier I said that String was a library class (an idea
supported by the presence of documentation), but I’ve been
using strings freely without importing them into my class.
ASIDE: WHY DIDN’T I NEED TO IMPORT STRING?
62
I could import String if I wanted to, but we need strings so
frequently that Java imports the String class for us.
• We’ve already seen Java doing things for us such as
adding implicit constructors.
import java.lang.String;
63. Now that we have an external class imported, using that
class typically requires us to answer two questions. We
usually answer these questions using the documentation:
• How are objects of this external class constructed?
• Which methods are available to us once we have
obtained an object of this class?
• Which parameters do they require?
• Which values do they return?
USING A LIBRARY CLASS IN OUR PROGRAM: USE
63
64. 😴
From the Scanner documentation, it is clear that there are
multiple ways in which to construct objects of this class:
CONSTRUCTING A SCANNER (1)
64
Scanner is a versatile class that can be used for many different
purposes (some of which we’ll see), but for now we’ll use it
solely for reading a stream of input from the command line.
65. For now, I am going to give you the code to construct a
Scanner object with an stream of input as boilerplate, and
then come back later to describe in more detail where this
information comes from:
CONSTRUCTING A SCANNER (2)
65
Scanner in = new Scanner(System.in);
Class Creating the copy.Object
Remember our understanding of these terms will evolve
next semester.
A parameter to
the constructor.
66. TRACKING A USER’S CALORIES (2)
66
import java.util.Scanner;
public class CalorieTracker {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
If we want to facilitate user input in our calorie tracker
program, we have to import the Scanner class and then
make an object of it (as we would with one of our own
classes).
67. Remember we’re aiming to open our CalorieTracker up to
this style of user input:
USING A SCANNER (1)
67
Any single entry (without spaces) into the terminal while our
program is running is considered to be a token of user input.
In this case, we want our program to stop and wait for a
single token of integer input.
68. We read single integer tokens using the following method in
the Scanner class:
USING A SCANNER (2)
68
in.nextInt();
As this method gives us an integer value
back, we can assign this value to a variable,
or pass it around our program as we wish.
69. TRACKING A USER’S CALORIES (3)
69
import java.util.Scanner;
public class CalorieTracker {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Person person = new Person();
System.out.println("Enter the calories in your starter:");
Dish starter = new Dish();
starter.setCalories(in.nextInt())
Every time we invoke the nextInt method, our program will
stop and wait for another token of user input.
70. TRACKING A USER’S CALORIES (4)
70
Scanner in = new Scanner(System.in);
Person person = new Person();
System.out.println("Enter the calories in your starter:");
Dish starter = new Dish();
starter.setCalories(in.nextInt());
System.out.println("Enter the calories in your main:");
Dish main = new Dish();
main.setCalories(in.nextInt());
And we can do this as many times as we wish.
71. TRACKING A USER’S CALORIES (5)
71
System.out.println("Enter the calories in your desert:");
Dish desert = new Dish();
desert.setCalories(in.nextInt());
Meal meal = new Meal();
meal.setStarter(starter);
meal.setMain(main);
meal.setDesert(desert);
person.eat(meal);
System.out.println(person.getCalories());
Compiling this code will result in a warning unless we call
the close method on our Scanner instance.
in.close();
72. We typically indicate when we have finished asking our user for
input by flagging that our scanner can no longer be used for input
using the close method.
• This also closes the underlying resource being used by the
scanner.
• This avoids us locking resources (e.g. locking an input
stream) but should be used carefully in this context, as input
from the command line cannot be re-opened.
• When dealing with user input, close is therefore usually
designed to be the last command used within the
program.
• If it cannot be then this warning can be ignored.
ASIDE: CLOSING SCANNER
72
73. 😴
What would happen if I were to enter a string for the
number of requested calories, rather than an integer?
ASIDE: ENTERING DATA IN AN UNEXPECTED FORMAT
73
We’d get a runtime error. This is something we’ll discuss
later in the course.
74. Because our program currently deals with tokens as
opposed to lines of input, if we decide to enter multiple
tokens in one line, then we can receive unexpected
behaviour:
ASIDE: MULTIPLE TOKENS
74
The program only pauses in expected places if there are still
tokens to read, otherwise it will use the tokens that have
already been entered.
75. In the same way that we made our CalorieTracker more
interactive, let’s try and make our BookReader more
interactive.
LECTURE EXERCISE: BACK TO THE BOOKS (1)
75
public class BookReader {
public static void main(String[] args) {
Book aGameOfThrones = new Book(704);
aGameOfThrones.readPage();
aGameOfThrones.readPage();
aGameOfThrones.readPage();
System.out.println(aGameOfThrones.readPageNumber());
aGameOfThrones.turnPageBack();
System.out.println(aGameOfThrones.readPageNumber());
}
}
76. Let’s implement the following functionality:
• We have two books, `A Game of Thrones’ and `A Clash of
Kings’, that constitute a (very small) library.
• We have the option to read a book from the library.
• We are given the option to select one of these books.
• When we do so, we read 10 pages from it.
LECTURE EXERCISE: BACK TO THE BOOKS (2)
76
77. LECTURE EXERCISE: BACK TO THE BOOKS (3)
77
public class Library {
private Book aGameOfThrones;
private Book aClashOfKings;
public Library() {
aGameOfThrones = new Book(704);
aClashOfKings = new Book(768);
}
78. 🙈
public void readABook() {
AutomaticBookReader automaticBookReader = new AutomaticBookReader();
Scanner in = new Scanner(System.in);
String requestedBook = in.nextLine();
if ( requestedBook.toLowerCase().equals("a game of thrones") ) {
automaticBookReader.readBook(aGameOfThrones, 10);
} else if ( requestedBook.toLowerCase().equals("a clash of kings") ) {
automaticBookReader.readBook(aClashOfKings, 10);
} else {
System.out.println("Book not found.");
}
in.close();
}
}
LECTURE EXERCISE: BACK TO THE BOOKS (4)
78
We built this class in Topic 4.
We make one
request for
input and
store the
result.
Transforming the string to
lowercase stops us being concerned
about the capitalisation employed
by the user.
79. 🖥
We can do some interesting things if we combine the use of
a scanner with a loop.
In the laboratory, use the methods of the Scanner class to
implement the following functionality:
• A program that keeps asking a user for numbers until
they enter a `-1’. The total of these numbers should
then be printed.
• A program that keeps asking a user for numbers until
they enter a string. The total of these numbers should
then be printed.
SCANNER AND LOOPS
79Topic6-2
80. I mentioned in Topic 5 that there was another type of loop
that I would talk about during Topic 6.
• This is because this loop is most commonly suited to
user input:
A PREVIEW: DO WHILE
80
Scanner in = new Scanner(System.in);
String password;
do {
System.out.println("What's the password?");
password = in.nextLine();
} while ( !password.equals(this.password) );
• You might like to use a do while loop to help you with
the previous questions.
We could put a default value
here (a sentinel value), but this
reduces readability.
We get
one
iteration
of the
loop
before the
condition
is tested.
82. We’ve already seen lots of examples of when arithmetic is
useful when programming:
USING ARITHMETIC WHEN PROGRAMMING
82
currentPage + 1;
currentPage - 1;
balance - amount
balance + amount
balance - ( amount + 20 );
balance - ( amount + 50 );
83. Most of the arithmetic operators we’ve seen so far have
been simple addition and subtraction operators.
The form of these operators intuitively matches their form
in regular mathematics.
ADDITION AND SUBTRACTION OPERATORS
83
currentPage + 1; currentPage - 1;
84. We have other operators available to us, but their formation
differs from regular mathematics:
MULTIPLICATION AND DIVISION OPERATORS
84
Java Mathematical Notation Description
+ + Addition
- - Subtraction
/ ÷ Division
* × Multiplication
85. When dividing, if at least one of the operands isn’t in floating
point format, the result of the operation won’t have the
required precision.
INTEGER DIVISION
85
System.out.println(1/2);
There are a number of simple solutions to avoid avoid integer
division:
System.out.println(1/2.0); System.out.println(1.0/2);
System.out.println(1f/2); System.out.println(1/2d);
86. Recall that operators of equivalent precedence are evaluated from left
to right in almost all cases.
Because of this rule, programming languages like Java often employ a
useful tool called short-circuit evaluation.
When the evaluation of a sequence of operators short circuits, it cuts
out before the end. Languages like Java typically do this when the truth
value of a boolean operator can already be determined before
completing the evaluation.
We can leverage this behaviour in our programs, in order to ensure
that conditions that would result in an error, given a state in the
program, are not evaluated.
ASIDE: SHORT-CIRCUIT EVALUATION
86
check for dangerous thing && dangerous thing
if ( b > 0 && 10 / b > 4 ) {
87. The type resulting from an arithmetic operation is the same
as the operand with the highest precision.
ASIDE: TYPE RESULTING FROM AN ARITHMETIC OPERATION
87
System.out.println(((Object)( )).getClass().getName());
1/3.0
Double
1/3.0f
Float
1d * 3l
Double
To confirm this, you can use the following boilerplate code:
Expression here
88. 🤐
A large number of decimal numbers have an infinite
representation in binary.
• This is typically due to the binary conversion process itself
(e.g. representing 0.1 in binary), or because those numbers
themselves have an infinite decimal expansion (e.g. π).
Representing these numbers in finite memory therefore often
involves rounding, which results in approximations of true
decimal values.
As such, the result of arithmetic operations with decimals may
not always be accurate.
ASIDE: FLOATING POINT ARITHMETIC ACCURACY (1)
88
89. 🤐
For example, consider the following simple addition of double
values:
ASIDE: FLOATING POINT ARITHMETIC ACCURACY (2)
89
System.out.println(5.6 + 5.8);
This occurs because, in reality, 5.6 and 5.8 (both of which have
an infinite binary form), when converted to binary floating point,
end up being rounded approximations of their true values.
• We can confirm this if we translate each of these values to
(double precision) binary floating point and then convert
them back to decimal again (receiving the (truncated)
values 5.5999999999999996 and 5.7999999999999998, resp.).
90. 🤐
Even floating point arithmetic that appears to behave normal
may actually just be the result of fortunate rounding.
ASIDE: FLOATING POINT ARITHMETIC ACCURACY (3)
90
Here, a fuller precision result is actually
10.199999999999999289…, but when rounded and stored as a
double (typically to between 15 and 17 digits), the result
given is 10.20000000000000 (presented as just 10.2).
System.out.println(5.1 + 5.1);
91. 🤐
One solution here, if exact results are required, is to use the
library class BigDecimal.
ASIDE: FLOATING POINT ARITHMETIC ACCURACY (4)
91
BigDecimal fivePointSix = new BigDecimal("5.6");
BigDecimal fivePointEight = new BigDecimal("5.8");
System.out.println(fivePointSix.add(fivePointEight));
Other solutions include:
• Introducing a tolerance factor into if statements.
• Rounding (more shortly)
• Using fixed point representations (e.g. number of pennies)
But in this course we won’t be too concerned with the small margins
of error introduced by floating point numbers.
92. An operator that deserves a special mention is the modulo
operator.
THE MODULO OPERATOR
92
As in regular mathematics, this returns the remainder after
a division.
System.out.println(7 % 3);
Modulo allows us to do some interesting things, such as
testing for multiples.
93. It is commonly reported (https://blog.codinghorror.com/
why-cant-programmers-program/) that many candidates for
programming jobs during interviews cannot solve the
following problem:
• ‘Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the
number and for the multiples of five print "Buzz". For
numbers which are multiples of both three and five
print "FizzBuzz".’
LECTURE EXERCISE: FIZZ BUZZ (1)
93
94. LECTURE EXERCISE: FIZZ BUZZ (2)
94
for ( int i = 1; i <= 100; i++ ) {
if ( i % 3 == 0 && i % 5 == 0 ) {
System.out.println("Fizzbuzz");
} else if ( i % 3 == 0 ) {
System.out.println("Fizz");
} else if ( i % 5 == 0 ) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
There are lots of
interesting optimisations
to this basic solution,
particular in terms of
how multiples of both 3
and 5 are dealt with.
95. Earlier we noted that rounding might be useful to help us
with the (lack of) precision of floating point numbers.
There are also a number of other useful operations that
aren’t immediately representable using the basic arithmetic
operations we’ve seen so far.
• What about raising 2 to the power of 8?
• What about finding the square root of 17?
MORE POWERFUL MATHEMATICAL OPERATIONS (1)
95
96. Given the title of this topic, it probably intuitive that there is
a library class available to help us with this.
MORE POWERFUL MATHEMATICAL OPERATIONS: THERE’S A CLASS FOR THAT
96
97. Methods from the Math class allow us to perform the
operations noted previously:
THE MATH CLASS
97
The Math class is also so regularly used that we do not need
to import it.
There are also other classes that allow us to round numbers.
Math.round((5.6 + 5.8) * 100.0) / 100.0;
Detailed rules for these operations are given in the API.
Math.pow(2, 8);
Math.sqrt(17);
99. When we were using the methods in the Math class, you’ll
notice that we didn’t make an object of the Math class
before calling those methods.
Instead, we simply wrote the name of the class (Math)
followed by the name of the method.
NO OBJECTS
99
Math.pow(2, 8);
100. As you’ve probably already seen from your own
experiments, we can call a method in a class without
creating an object of that class if that method is static.
STATIC METHODS (1)
100
We’ve already seen several examples of static methods in
the course, without explicitly identifying them as such:
System.currentTimeMillis();
out.println();
We’ll discuss the
`System’ part
shortly.
System.nanoTime();
101. We can imagine a single shared copy of all static identifiers,
existing within the class type itself, such that we can access
those identifiers using our familiar dot syntax.
STATIC METHODS (2)
101
But remember, as with our class copies, this is just a
simplified abstraction, to help our understanding.
Math.pow(2, 8);
Math.sqrt(17);
static double pow(double a, double b) {
}
static double sqrt(double a) {
}
102. Given this new (or not new) knowledge, we could, if we wanted to,
go back and evolve some of early examples of methods, to instead
be static.
• This simplifies their use, but leaving these methods non-
static is still perfectly fine; a style choice.
BACK TO MARTIN PRINTER AND NUMBER PRINTER
102
public static void printMartin() {
System.out.println("+------+");
System.out.println("|Martin|");
System.out.println("+------+");
}
public static void printNumber(int num) {
System.out.println("+------+");
System.out.println("|" + num + "|");
System.out.println("+------+");
}
MartinPrinter.printMartin();
NumberPrinter.printNumber(1);
103. This seems like quite a nice shorthand. Can we apply this to
all our examples?
THE CONSEQUENCES OF STATIC
103
public class Pair {
private int valueA;
private int valueB;
public static void setPair(int passedValueA, int passedValueB) {
valueA = passedValueA;
valueB = passedValueB;
}
public static int getValueA() {
return valueA;
}
public static int getValueB() {
return valueB;
}
Pair.setPair(1, 2);
105. This error makes sense, because only the static methods are
included in the shared copy of static identifiers, not the
fields being referenced.
STATIC METHODS (3)
105
Pair.setPair(1, 2);
public static void setPair( … ) {
valueA = passedValueA;
…
}
public static int getValueA() {
}
public static int getValueB() {
}
106. PREVIEW: STATIC FIELDS (1)
106
public class Pair {
private static int valueA;
private static int valueB;
public static void setPair(int passedValueA, int passedValueB) {
valueA = passedValueA;
valueB = passedValueB;
}
public static int getValueA() {
return valueA;
}
public static int getValueB() {
return valueB;
}
}
One solution would be to make these fields static too, and
thus add them to the shared copy of static identifiers…
107. But hopefully it’s clear that this would result in undesired behaviour, when
we want to use multiple pairs.
• Within this single shared copy of static identifiers, we’d only be able to
store one set of values at a time.
PREVIEW: STATIC FIELDS (2)
107
Pair.setPair(1, 2);
Pair.setPair(3, 4);
private static int valueA;
private static int valueB;
public static void setPair( … ) {
valueA = passedValueA;
…
}
public static int getValueA() {
}
public static int getValueB() {
108. 🤓
What’s the solution here? Well, there isn’t really one. Instead, static
and non-static methods have different uses:
• Static methods are used when the operation within that
method does not involve non-static fields (e.g. Number printer).
• We call these instance fields (variables), because they are
designed to hold different values for each instantiated
object.
• Also, of course, if we wish to access static fields.
• Non-static methods are used to interact with and update
instance fields, as we have seen (e.g. Pair).
• But they can also access static fields, more to come.
STATIC VS. NON-STATIC METHODS
108
109. 🤔
My main use for static methods is within Utility classes, that
perform some common tasks that I will need multiple times:
ASIDE: UTILITY CLASSES
109
This class would
have a private
constructor.
Every variable
referenced here
is defined within
the scope of the
method.
110. It’s worth saying that it is possible to call static methods
and fields via an object.
But this is conceptually awkward, and thus you are warned
by the compiler when doing this.
So why permit this?
• An error in the design of the language?
• Most languages are not perfect.
ASIDE: CALLING STATIC METHODS VIA AN OBJECT
110
111. We now know a even more about main.
• We know that main can never return anything (where would it go
anyway?)
• This is a parameter, so main must accept some information.
• But unfortunately, we still aren’t in a position to discuss what is
passed to the main method.
REMEMBER: BACK TO MAIN
111
public static void main(String[] args) {
• We know that main has to be visible from outside the class, so that it can
be run by the JVM (Topic 4).
• We know that main can be accessed without having to make an object of
our driver class, which makes things easier for the JVM.
112. There was an implication before that static fields were
somehow bad because they can’t be virtually copied in
order to store different values.
• This contrast instance fields, which are virtually copied
with each object of a class, and thus allow us to store
different values.
But static fields do have a place, both conceptually and
practically.
STATIC FIELDS
112
113. The fields of these classes are clear; common features that we can all
identify as a part of the shared concept.
But fields often hold different data; things in the world are in different
states.
REMEMBER: CLASSES AND OBJECTS IN THE REAL WORLD (3): STATE
113
114. 🤓
STATIC FIELDS IN THE REAL WORLD
114
public class Dog {
private String colour;
private int earLength;
We say that these fields are part of the concept (the class;
the shared static copy), rather than the instance.
It’s true that different
instances our our dog will
have different values for
attributes such as these.
But there are also attributes
that will be the same for
each instance.
It therefore makes sense for these fields to be static.
A change in the concept, should invoke a change in all the
instances.
private int numberOfLegs;
private int numberOfEyes;
static
static
115. When a field is static because it is being used to represent an
attribute of a class (concept) that is the same for each
instance, it doesn’t really make conceptual sense to make
this field variable.
• A variable field implies that this attribute will be used to
hold multiple different values, which it won’t in this
case.
So, instead, we should mark this field as a constant, which is
the opposite of a variable.
FRIENDS OF STATIC (1): FINAL
115
We do this by using the modifier final.
private static final int numberOfLegs;
private static final int numberOfEyes;
116. When we make a field constant instead of variable, there are a couple
of other things we should also do:
• We should assign values to that field immediately.
• I noted priorly that this was bad practice. This is the only
exception to this rule (in my opinion).
• Because the value will never be changed, there is no chance of
inefficient reassignment.
• This is also the only place we can assign the field (non-static
final fields can also be assigned in the constructor).
FRIENDS OF STATIC (2): FINAL
116
private static final int numberOfLegs = 4;
private static final int numberOfEyes = 2;
117. When we make a field constant instead of variable, there are a
couple of things we should also do:
• We should write the variable name in uppercase
• This signifies that the variable is a constant.
FRIENDS OF STATIC (3): FINAL
117
private final static int NUMBER_OF_LEGS = 4;
private final static int NUMBER_OF_EYES = 2;
118. When we make a field constant instead of variable, there are a couple of
things we should also do:
• Finally, we should also make this variable public.
• Again, I noted priorly that this was bad practice, but this should
be the only exception to this rule (in my opinion).
• This doesn’t violate encapsulation, because the value can never
be changed.
• This allows us to efficiently view the data in the field, to quickly
learn about the features of a class (without static this would not
be possible).
FRIENDS OF STATIC (4): PUBLIC
118
public final static int NUMBER_OF_LEGS = 4;
public final static int NUMBER_OF_EYES = 2;
119. While public, constant, static fields have a conceptual
relevance, they also have a practical use (non-exhaustive):
• They can allow us to quickly extract important, practical
information from a class.
PRACTICAL USES OF PUBLIC CONSTANT STATIC FIELDS
119
• They can allow us to quickly
extract important objects from
a class.
System.in System.out.println("");
120. 🤔
Another common use for public statics final fields is to
define our own keywords, which can help improve the
readability of our code:
ASIDE: ENUM VS. PUBLIC STATIC FINAL (1)
120
public class BankAccountTypes {
public static final int CURRENT = 0;
public static final int SAVINGS = 1;
}
public BankAccount(int type) {
if ( type == BankAccountType.CURRENT ) {
…
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount(BankAccountType.CURRENT);
121. 🤔
Java provides enum types to support this practice more formally.
• More specialised, but have to be defined as a separate type.
ASIDE: ENUM VS. PUBLIC STATIC FINAL (2)
121
public enum BankAccountType {
CURRENT, SAVINGS;
}
public BankAccount(BankAccountType type) {
if ( type == BankAccountType.CURRENT ) {
…
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount(BankAccountType.CURRENT);
}
122. Previously we saw that non-constant, non-public static
fields were typically undesirable, as they only exist within
the shared copy of static identifiers, and thus cannot be
used to store different values for each object.
• We can see this issue more explicitly if we access these
static fields through an object.
NON-CONSTANT, NON-PUBLIC STATIC FIELDS (1)
122
Pair pairA = new Pair();
pairA.setPair(1, 2);
private static int valueA;
private static int valueB;
public void setPair(int valueA, int valueB) {
this.valueA = valueA;
}
We should really qualify valueA
here with the class name. Open
question: Why is this possible,
given valueA is private?
123. Non-constant (and thus non-public) static fields also have a
use.
• Why is it useful to update the values in a field in all
objects of a class?
• A common reason is to record the number of instances
that are created of a class.
NON-CONSTANT, NON-PUBLIC STATIC FIELDS (2)
123
public static int getNumberOfPairs() {
return numberOfPairs;
}
private static int numberOfPairs;
public Pair() {
numberOfPairs++;
}
Why is this useful?
124. Let’s represent a Miner who can add Blocks to a Blockchain.
• We’ll do this in a very abstract way.
LECTURE EXERCISE: BLOCKCHAIN (1)
124
Blockchain technology (distributed ledger technology) gives
us a secure, ordered and replicated way to store data
(typically financial data).
125. When representing blocks for a blockchain:
• There must be a sequential order to the blocks.
• We must know how many blocks there are.
• We cannot hold any information about the sequencing of the
blocks centrally (i.e. the information must be held in the blocks
themselves).
• It should not be possible for a user to manipulate this ordering.
Timestamp?
• If multiple blocks are generated at the same time, a timestamp
will be useless.
LECTURE EXERCISE: BLOCKCHAIN (2)
125
126. LECTURE EXERCISE: BLOCKCHAIN (3) - BLOCK
126
public class Block {
private static int blocks;
private int blockNumber;
public Block() {
blockNumber = blocks++;
}
public int blockNumber() {
return blockNumber;
}
}
Here we use the information
in a static field to give each
block a unique, sequential
number.
Keeping both these values
private is important for the
integrity of our numbering
system.
127. LECTURE EXERCISE: BLOCKCHAIN (4) - MINER AND BLOCKCHAIN
127
public class Miner {
public static void main(String[] args) {
Block myBlock = new Block();
Blockchain chain = new Blockchain();
chain.addBlock(myBlock);
}
}
public class Blockchain {
public void addBlock(Block block) {
}
}
Keep a list of blocks
Add the block to a list
How do we do this?
On to Topic 7!
129. With so many libraries available to us, a natural question is
can’t we use a library for everything?
• When working as developers, we should try and reuse
code via libraries as much as possible.
• Or at least tailor the functionality of an existing library.
• When completing assignments during our education, it’s
best to only use a library if that library has been covered
already during lectures, as the functionality you’re reusing
may be the subject of assessment.
• The coursework will only require libraries that have
been shown.
ASIDE: GETTING THE BALANCE RIGHT
129
130. Be aware of the existence of library classes when defining
your own class names, as this can cause unexpected
behaviour.
ASIDE: CONFLICT BETWEEN USER CLASSES AND LIBRARY CLASSES
130
public class String {
}
public static void main(String[] args) {
String x = "abc";
}
131. 😴
We will see lots more examples of library classes in this
course, especially next semester, when we look at library
classes for creating graphical user interfaces.
In the interim, you can look at the library classes for the
following pieces of functionality:
• Generating random numbers
• Time
• File Input
ASIDE: MORE LIBRARY CLASSES TO EXPLORE
131
132. Dr. Martin Chapman
programming@kcl.ac.uk
martinchapman.co.uk/teaching
Programming Practice and Applications (4CCS1PPA)
Topic 6: Library Classes
These slides will be available on KEATS, but will be subject to
ongoing amendments. Therefore, please always download a new
version of these slides when approaching an assessed piece of work,
or when preparing for a written assessment. 132
Thursday 27th October