Strings in Java are objects of the String class that represent sequences of characters. Strings are immutable, meaning their contents cannot be modified once created. The StringBuffer class represents mutable strings that can be modified by methods like append(), insert(), delete(), and replace(). Some key String methods include length(), charAt(), equals(), concat(), and indexOf(), while common StringBuffer methods allow modifying the string through insertion, deletion, replacement and reversal of characters.
The document discusses Strings in Java. Some key points:
- A String represents a sequence of characters. The String class is used to create string objects which can exist in the string pool or heap.
- Char arrays are preferable over Strings for passwords due to security reasons. Strings can be manipulated more easily.
- The String class has many useful methods like length(), charAt(), indexOf(), replace(), toLowerCase(), substring() etc to work with and manipulate string values.
- StringBuffer is used to create mutable string objects that can be modified after creation using methods like append(), insert(), delete() etc. It is preferable over String for performance reasons while manipulating strings.
This document summarizes Chapter 10 of the textbook "Starting Out with Java: From Control Structures through Data Structures" which discusses text processing and wrapper classes in Java. The chapter covers introduction to wrapper classes, the Character class for character testing and conversion, additional String methods for searching and extracting substrings, the StringBuilder class, and wrapper classes for numeric primitive data types. Example code is provided to demonstrate various string and character methods.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
This document discusses string handling in Java. It covers key topics like:
- Strings are immutable objects in Java
- The String, StringBuffer, and StringBuilder classes can be used to manipulate strings
- Common string methods like length(), concat(), indexOf(), and replace()
- Strings can be compared using equals(), startsWith(), and compareTo()
- Immutability avoids security issues when strings are passed as parameters
The document discusses String handling in Java. It describes how Strings are implemented as objects in Java rather than character arrays. It also summarizes various methods available in the String and StringBuffer classes for string concatenation, character extraction, comparison, modification, and value conversion. These methods allow extracting characters, comparing strings, modifying strings, and converting between string and other data types.
Here are solutions to the exercises:
1. Write a program that reverses a string:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("Reversed string: " + reversed);
}
}
```
2. Write a program to
This document provides an overview of arrays in C#, including:
- Arrays are fixed-length collections that store elements of the same type. They can be one-dimensional or multidimensional.
- Elements are accessed via an index that starts at 0. The Length property returns the array size.
- Common operations include initialization, iteration with for loops and foreach, and passing arrays to methods.
- Strings are objects that can be treated similarly to character arrays. Common string methods include comparison, searching, and manipulation.
- The StringBuilder class provides a mutable alternative to immutable strings for efficient string operations.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
The document discusses strings, arrays, pointers, and sorting algorithms in C programming. It provides definitions and examples of:
1) Strings as null-terminated character arrays. It demonstrates initializing and printing a string.
2) One-dimensional and two-dimensional arrays. It shows how to declare, initialize, access, and print multi-dimensional arrays.
3) Pointers as variables that store memory addresses. It explains pointer declaration and dereferencing pointers using asterisk (*) operator.
4) Bubble sort algorithm that iterates through an array and swaps adjacent elements if out of order, putting largest elements at the end of the array in each iteration.
Programing with java for begniers .pptxadityaraj7711
Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
The document discusses strings and StringBuffers in Java. Strings are immutable sequences of characters represented by the String class. StringBuffers allow modifying character sequences and are represented by the StringBuffer class. The summary provides an overview of common string and StringBuffer operations like concatenation, extraction, comparison, and modification.
The document discusses the String class in Java. It covers string literals, immutability of strings, common string methods like length(), charAt(), substring(), and concatenation. It also discusses converting between strings and numbers, formatting strings, and the StringBuffer mutable string class. The Character class is described as having useful methods for classifying characters.
The document summarizes key concepts about Strings in Java including:
1. Strings can be created using double quotes or by converting a character array to a String.
2. The length() method returns the number of characters in a String.
3. Strings can be concatenated using the + operator or concat() method.
4. The format() method can be used to create formatted String outputs.
5. Common String methods include charAt(), compareTo(), indexOf(), and length().
- Variables in PHP are prefixed with a $ sign and can contain any type of data value. Variable names are case-sensitive.
- PHP supports scalar data types like integers, floats, booleans, and strings as well as complex types like arrays and objects. Variables do not require explicit typing.
- Arrays allow storing multiple values in a single variable through numeric or associative indexes. Arrays can be nested to any level and PHP provides many functions for manipulating array values and structure.
The document discusses various Java string concepts:
1. Java strings are immutable sequences of characters that are objects of the String class. The StringBuffer class can be used to modify strings.
2. Common string methods include length(), charAt(), compareTo(), concat(), and substring().
3. The StringBuffer class represents mutable strings and defines methods like append(), insert(), delete(), and replace() to modify the string content.
4. Enumerated types in Java can be defined using the enum keyword to represent a fixed set of constants, like the days of the week.
The document discusses Java's Number class and wrapper classes. It describes that wrapper classes allow primitive data types to be used as objects. The six wrapper classes are Integer, Byte, Float, Short, Long and Double. Wrapper classes allow boxing (converting primitives to objects) and unboxing. Number class methods like intValue(), doubleValue() convert between primitive types and objects. Other methods like compareTo(), equals() compare values or check equality. Static methods like valueOf() and parseInt() create Number objects from primitives and strings.
The document discusses processing strings in Java using the String, StringBuffer, and StringTokenizer classes. It provides details on constructing and manipulating strings, including obtaining length, retrieving characters, concatenation, substrings, comparisons, and conversions. It also covers the StringBuffer class for processing mutable strings, and the StringTokenizer class for extracting tokens from strings. Examples provided demonstrate checking palindromes, counting letters, using StringBuffer for output, and processing command-line arguments.
This document provides information about strings and characters in Java. It includes definitions of strings and characters, examples of using string methods like length(), substring(), indexOf(), and equals(). It also discusses formatting output with printf and comparing/modifying strings and characters. The document is from a textbook on building Java programs and is copyrighted material. It contains exercises for students to complete.
The document discusses String handling in Java. It describes how Strings are implemented as objects in Java rather than character arrays. It also summarizes various methods available in the String and StringBuffer classes for string concatenation, character extraction, comparison, modification, and value conversion. These methods allow extracting characters, comparing strings, modifying strings, and converting between string and other data types.
Here are solutions to the exercises:
1. Write a program that reverses a string:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("Reversed string: " + reversed);
}
}
```
2. Write a program to
This document provides an overview of arrays in C#, including:
- Arrays are fixed-length collections that store elements of the same type. They can be one-dimensional or multidimensional.
- Elements are accessed via an index that starts at 0. The Length property returns the array size.
- Common operations include initialization, iteration with for loops and foreach, and passing arrays to methods.
- Strings are objects that can be treated similarly to character arrays. Common string methods include comparison, searching, and manipulation.
- The StringBuilder class provides a mutable alternative to immutable strings for efficient string operations.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
The document discusses strings, arrays, pointers, and sorting algorithms in C programming. It provides definitions and examples of:
1) Strings as null-terminated character arrays. It demonstrates initializing and printing a string.
2) One-dimensional and two-dimensional arrays. It shows how to declare, initialize, access, and print multi-dimensional arrays.
3) Pointers as variables that store memory addresses. It explains pointer declaration and dereferencing pointers using asterisk (*) operator.
4) Bubble sort algorithm that iterates through an array and swaps adjacent elements if out of order, putting largest elements at the end of the array in each iteration.
Programing with java for begniers .pptxadityaraj7711
Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
The document discusses strings and StringBuffers in Java. Strings are immutable sequences of characters represented by the String class. StringBuffers allow modifying character sequences and are represented by the StringBuffer class. The summary provides an overview of common string and StringBuffer operations like concatenation, extraction, comparison, and modification.
The document discusses the String class in Java. It covers string literals, immutability of strings, common string methods like length(), charAt(), substring(), and concatenation. It also discusses converting between strings and numbers, formatting strings, and the StringBuffer mutable string class. The Character class is described as having useful methods for classifying characters.
The document summarizes key concepts about Strings in Java including:
1. Strings can be created using double quotes or by converting a character array to a String.
2. The length() method returns the number of characters in a String.
3. Strings can be concatenated using the + operator or concat() method.
4. The format() method can be used to create formatted String outputs.
5. Common String methods include charAt(), compareTo(), indexOf(), and length().
- Variables in PHP are prefixed with a $ sign and can contain any type of data value. Variable names are case-sensitive.
- PHP supports scalar data types like integers, floats, booleans, and strings as well as complex types like arrays and objects. Variables do not require explicit typing.
- Arrays allow storing multiple values in a single variable through numeric or associative indexes. Arrays can be nested to any level and PHP provides many functions for manipulating array values and structure.
The document discusses various Java string concepts:
1. Java strings are immutable sequences of characters that are objects of the String class. The StringBuffer class can be used to modify strings.
2. Common string methods include length(), charAt(), compareTo(), concat(), and substring().
3. The StringBuffer class represents mutable strings and defines methods like append(), insert(), delete(), and replace() to modify the string content.
4. Enumerated types in Java can be defined using the enum keyword to represent a fixed set of constants, like the days of the week.
The document discusses Java's Number class and wrapper classes. It describes that wrapper classes allow primitive data types to be used as objects. The six wrapper classes are Integer, Byte, Float, Short, Long and Double. Wrapper classes allow boxing (converting primitives to objects) and unboxing. Number class methods like intValue(), doubleValue() convert between primitive types and objects. Other methods like compareTo(), equals() compare values or check equality. Static methods like valueOf() and parseInt() create Number objects from primitives and strings.
The document discusses processing strings in Java using the String, StringBuffer, and StringTokenizer classes. It provides details on constructing and manipulating strings, including obtaining length, retrieving characters, concatenation, substrings, comparisons, and conversions. It also covers the StringBuffer class for processing mutable strings, and the StringTokenizer class for extracting tokens from strings. Examples provided demonstrate checking palindromes, counting letters, using StringBuffer for output, and processing command-line arguments.
This document provides information about strings and characters in Java. It includes definitions of strings and characters, examples of using string methods like length(), substring(), indexOf(), and equals(). It also discusses formatting output with printf and comparing/modifying strings and characters. The document is from a textbook on building Java programs and is copyrighted material. It contains exercises for students to complete.
The department of business management at Vikrama Simhapuri University was re-established in 2021. It offers a 2-year MBA program with 66 seats across specializations in finance, human resources, and marketing. The department aims to produce graduates with an entrepreneurial mindset ready to provide leadership. It has qualified faculty and infrastructure like computer labs and a library. The MBA curriculum spans 4 semesters with internal and external electives, and the department regularly revises the syllabus and introduces new skill-oriented courses.
This document discusses mushroom culture and preparation of growth medium. It lists several edible mushroom species commonly cultivated, including white button mushroom, oyster mushroom, paddy straw mushroom, shiitake, and chanterelle. It also covers preserving mushroom cultures through periodic transfer to solid substrate or agar media, and isolating pure cultures from spores or tissues of fresh fruit bodies. Proper maintenance of pure mushroom cultures is important to retain vigor and productivity over time.
Node.js is an open-source server-side JavaScript runtime environment built on Chrome's V8 JavaScript engine. It provides an event-driven, non-blocking asynchronous I/O model to build highly scalable network applications. Node.js uses JavaScript for server-side development and can build various types of applications like web applications, REST APIs, real-time applications etc. It was created by Ryan Dahl in 2009 and has advantages like being open-source, lightweight, asynchronous and cross-platform. Node.js handles requests differently than traditional web servers by using a single thread event loop model. It also includes modules, functions and objects to work with files, streams, network etc.
This document provides information about Java applets. It discusses what applets are, the Applet class, applet architecture and lifecycle, methods like init(), start(), stop(), destroy(), and paint(). It covers displaying output, requesting repainting, using the status window, the HTML <applet> tag and passing parameters. It also discusses getting the code base and document base, the AppletContext interface, and the two types of applets - those based on Applet and those based on JApplet.
An interface in Java is a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. An interface cannot have method bodies and can only contain abstract methods and variables that are public, static, and final by default. Classes implement interfaces to inherit their methods. Since Java 8, interfaces can also contain default and static methods.
software engineering modules iii & iv.pptxrani marri
The document discusses software quality and the ongoing issues related to it. It notes that in 2005 and 2006, publications lamented the prevalence of bad software plaguing organizations and the sorry state of software quality. Today, software quality remains a problem, with customers blaming developers for low-quality software due to sloppy practices, while developers blame unrealistic schedules and changing requirements for quality issues. The document examines perspectives on who or what is responsible for ongoing software quality problems.
The document discusses various metrics that can be used to measure different aspects of software products and processes. It describes McCall's quality factors for software products and defines measures, metrics, and indicators. It also outlines principles for software measurement, the measurement process, and goal-oriented measurement using the Goal/Question/Metric paradigm. Finally, it discusses different types of metrics including product, process, project, quality, functional, size, and object-oriented design metrics.
The Common Object Request Broker Architecture (CORBA) is a standard for distributed object systems that allows objects written in different languages and running on different machines to communicate. CORBA uses Interface Definition Language (IDL) to define object interfaces and an Object Request Broker (ORB) to handle requests and responses between objects. The CORBA specification defines protocols like General Inter-ORB Protocol (GIOP) and Inter-ORB Protocol (IIOP) to allow ORBs from different vendors to interoperate. CORBA also provides services like the Naming Service for object lookup and Object Services for common needs like concurrency, events, logging etc.
The document discusses Enterprise Java Beans (EJB) technology. It begins with an introduction to Java 2 Enterprise Edition (J2EE) and its value propositions. It then describes the various J2EE technologies including EJB, Servlets, JavaServer Pages (JSP), Java Message Service (JMS), and others. The remainder of the document focuses on EJB, describing the different EJB types (entity, session, message-driven), their life cycles, roles in development, and how applications are built and deployed using multiple EJBs.
Binary trees and binary search trees are discussed. Binary trees have nodes with at most two children, while binary search trees have the additional property that for every node, all keys in its left subtree are smaller than the node's key and all keys in its right subtree are larger. Common tree operations like searching, insertion, and deletion can be performed in O(log n) time on balanced binary search trees. AVL trees are discussed as one way to balance binary search trees through rotations.
This document discusses data structures and algorithm efficiency. It defines data structures as representations of logical relationships between data elements. Data structures are classified as primitive (basic types like integers) and non-primitive (derived types like lists, stacks, queues, trees, graphs). The document explains various non-primitive data structures and their implementations. It also discusses measuring algorithm efficiency, including analyzing best, worst, and average cases. Asymptotic analysis using Big O notation is introduced as a machine-independent way to compare algorithm growth rates and determine asymptotic complexity classes.
1. The document discusses operators and flow control in PHP including math operators, assignment operators, comparison operators, logical operators, and control structures like if/else statements, switch statements, loops, and functions.
2. Regular expressions and pattern matching are introduced as ways to validate user input data with functions like ereg(), split(), and ereg_replace(). Common patterns and character classes are explained.
3. Form validation is discussed including checking for empty fields, using custom arrays for form data, and redirecting with HTTP headers. Server variables are also described.
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsDrNidhiAgarwal
Unemployment is a major social problem, by which not only rural population have suffered but also urban population are suffered while they are literate having good qualification.The evil consequences like poverty, frustration, revolution
result in crimes and social disorganization. Therefore, it is
necessary that all efforts be made to have maximum.
employment facilities. The Government of India has already
announced that the question of payment of unemployment
allowance cannot be considered in India
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsesushreesangita003
what is pulse ?
Purpose
physiology and Regulation of pulse
Characteristics of pulse
factors affecting pulse
Sites of pulse
Alteration of pulse
for BSC Nursing 1st semester
for Gnm Nursing 1st year
Students .
vitalsign
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
Exploring Substances:
Acidic, Basic, and
Neutral
Welcome to the fascinating world of acids and bases! Join siblings Ashwin and
Keerthi as they explore the colorful world of substances at their school's
National Science Day fair. Their adventure begins with a mysterious white paper
that reveals hidden messages when sprayed with a special liquid.
In this presentation, we'll discover how different substances can be classified as
acidic, basic, or neutral. We'll explore natural indicators like litmus, red rose
extract, and turmeric that help us identify these substances through color
changes. We'll also learn about neutralization reactions and their applications in
our daily lives.
by sandeep swamy
How to Subscribe Newsletter From Odoo 18 WebsiteCeline George
Newsletter is a powerful tool that effectively manage the email marketing . It allows us to send professional looking HTML formatted emails. Under the Mailing Lists in Email Marketing we can find all the Newsletter.
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...larencebapu132
This is short and accurate description of World war-1 (1914-18)
It can give you the perfect factual conceptual clarity on the great war
Regards Simanchala Sarab
Student of BABed(ITEP, Secondary stage)in History at Guru Nanak Dev University Amritsar Punjab 🙏🙏
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
How to Manage Opening & Closing Controls in Odoo 17 POSCeline George
In Odoo 17 Point of Sale, the opening and closing controls are key for cash management. At the start of a shift, cashiers log in and enter the starting cash amount, marking the beginning of financial tracking. Throughout the shift, every transaction is recorded, creating an audit trail.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
1. CSC 128 - JAVA II
Part 1
Wrapper Classes
&
Strings
2. 9-2
Chapter Topics
We will cover the following topics in this order:
• 7.3.2 Wrapper Classes
• 2.5.6 Type Conversion (Parse Methods)
• 2.3.3 Operations on Strings
• 5.3.1 Some Built-in Classes (StringBuilder)
3. 9-3
Wrapper Classes
• Java provides 8 primitive data types: byte, short, int, long, float,
double, boolean, char
• One of the limitations of the primitive data types is that we
cannot create ArrayLists of primitive data types.
• However, this limitation turns out not to be very limiting after
all, because of the so-called wrapper classes:
– Byte, Short, Integer, Long, Float, Double, Boolean, Character
• These wrapper classes are part of java.lang (just like String and
Math) and there is no need to import them.
4. 9-4
Wrapper Classes Examples
• Creating a new object:
Integer studentCount = new Integer(12);
• Changing the value stored in the object:
studentCount = new Integer(20);
• Getting a primitive data type from the object:
int count = studentCount.intValue();
5. 9-5
Auto Boxing / UnBoxing
• You can also assign a primitive value to a wrapper class
object directly without creating an object. This is called
Autoboxing
Integer studentCount = 12;
• You can get the primitive value out of the wrapper class
object directly without calling a method (as we did when
we called .intValue()). This is called Unboxing
System.out.println(studentCount);
6. 9-6
Wrapper Classes and ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner k = new Scanner(System.in);
System.out.println("Enter some non-zero integers. Enter 0 to end.");
int number = k.nextInt();
while (number != 0)
{
list.add(number); // autoboxing happening here
number = k.nextInt();
}
System.out.println("Your numbers in reverse are:");
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i)); // unboxing happening here
}
7. 9-7
The Parse Methods
• One of the useful methods on the Wrapper classes is the parse
methods. These are static methods that allow you to convert a
String to a number.
• Each class has a different name for its parse method:
– The Integer class has a parseInt method that converts a String to an int
– The Short class has a parseShort method that converts a String to a Short
– The Float class has a parseFloat method that converts a String to a Float
– Etc.
8. 9-8
The Parse Methods Examples
byte b = Byte.parseByte("8");
short sVar = Short.parseShort("17");
int num = Integer.parseInt("28");
long longVal = Long.parseLong("149");
float f = Float.parseFloat("3.14");
double price = Double.parseDouble("18.99");
• If the String cannot be converted to a number, an exception is
thrown. We will discuss exceptions later.
9. 9-9
Helpful Methods on Wrapper Classes
• The toString is static method that can convert a number back to a
String:
int months = 12;
double PI = 3.14;
String monthsStr = Integer.toString(months);
String PIStr = Double.toString(PI);
• The Integer and Long classes have three additional methods to
do base conversions: toBinaryString, toHexString, and
toOctalString
int number = 16;
System.out.print(Integer.toBinaryString(number) + “ “ +
Integer.toHexString(number) + “ “ + Integer.toOctalString(number));
– output: 10000 10 20
10. 9-10
Helpful Static Variables on Wrapper
Classes
• The numeric wrapper classes each have a set of static final
variables to know the range of allowable values for the data
type:
– MIN_VALUE
– MAX_VALUE
System.out.println("The minimum val for an int is “ +
Integer.MIN_VALUE);
System.out.println("The maximum val for an int is “ +
Integer.MAX_VALUE);
11. 9-11
Character Testing and Conversion With The
Character Class
• The Character class allows a char data type to
be wrapped in an object.
Character x = new Character(‘K’);
• The Character class provides methods that
allow easy testing, processing, and conversion of
character data.
12. 9-12
The Character Class – Static Methods
Method Description
boolean isDigit(
char ch)
Returns true if the argument passed into ch is a
digit from 0 through 9. Otherwise returns false.
boolean isLetter(
char ch)
Returns true if the argument passed into ch is an
alphabetic letter. Otherwise returns false.
boolean isLetterOrDigit(
char ch)
Returns true if the character passed into ch
contains a digit (0 through 9) or an alphabetic
letter. Otherwise returns false.
boolean isLowerCase(
char ch)
Returns true if the argument passed into ch is a
lowercase letter. Otherwise returns false.
boolean isUpperCase(
char ch)
Returns true if the argument passed into ch is an
uppercase letter. Otherwise returns false.
boolean isSpaceChar(
char ch)
Returns true if the argument passed into ch is a
space character. Otherwise returns false.
13. 9-13
Character Testing and Conversion
With The Character Class
• The Character class provides two methods that will
change the case of a character.
Method Description
char toLowerCase(
char ch)
Returns the lowercase equivalent of the
argument passed to ch.
char toUpperCase(
char ch)
Returns the uppercase equivalent of the
argument passed to ch.
14. public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
System.out.println("Enter a character please: ");
char ch = k.nextLine().charAt(0);
if (Character.isLetter(ch))
{
System.out.println("Found a letter!");
if (Character.isLowerCase(ch))
System.out.println("Found a lowercase letter!");
if (Character.isUpperCase(ch))
System.out.println("Found an uppercase letter!");
}
if (Character.isDigit(ch))
System.out.println("Found a digit!");
if (Character.isSpaceChar(ch))
System.out.println("Found a single space!");
if (Character.isWhitespace(ch))
System.out.println("Found a whitespace! (could be tab or enter too");
}
Example
15. 9-15
Substrings
• The String class provides several methods that search for a string
inside of a string.
• A substring is a string that is part of another string.
• Some of the substring searching methods provided by the String
class:
boolean startsWith(String str)
boolean endsWith(String str)
boolean regionMatches(int start, String str, int start2,
int n)
boolean regionMatches(boolean ignoreCase, int start,
String str, int start2, int n)
16. 9-16
Searching Strings - startsWith
• The startsWith method determines whether a
string begins with a specified substring.
String str = "Four score and seven years ago";
if (str.startsWith("Four"))
System.out.println("The string starts with Four.");
else
System.out.println("The string does not start with Four.");
• str.startsWith("Four") returns true because
str does begin with “Four”.
• startsWith is a case sensitive comparison.
17. 9-17
Searching Strings - endsWith
• The endsWith method determines whether a string
ends with a specified substring.
String str = "Four score and seven years ago";
if (str.endsWith("ago"))
System.out.println("The string ends with ago.");
else
System.out.println("The string does not end with ago.");
• The endsWith method also performs a case sensitive
comparison.
18. 9-18
Searching Strings - regionMatches
• The String class provides methods that determine if
specified regions of two strings match.
– regionMatches(int start, String str, int start2,
int n)
• returns true if the specified regions match or false if they
don’t
• Case sensitive comparison
– regionMatches(boolean ignoreCase, int start,
String str, int start2, int n)
• If ignoreCase is true, it performs case insensitive
comparison
19. 9-19
Searching Strings - regionMatches
String str = "Four score and seven years ago";
String str2 = “Those seven years passed quickly!”;
if (str.regionMatches(15, str2, 6, 11))
System.out.println("The regions match.");
else
System.out.println("The regions do not match.");
String str = "Four score and seven years ago";
String str2 = “THOSE SEVEN YEARS PASSED QUICKLY!”;
if (str.regionMatches(true, 15, str2, 6, 11))
System.out.println("The regions match.");
else
System.out.println("The regions do not match.");
Location 15
Location 6
11 characters
to be compared
true:
means
ignore the
case when
comparing
20. 9-20
Searching Strings – indexOf, lastIndexOf
• The String class also provides methods that will
locate the position of a substring.
– indexOf
• returns the first location of a substring or character in the
calling String Object.
– lastIndexOf
• returns the last location of a substring or character in the
calling String Object.
21. 9-21
Searching Strings – indexOf, lastIndexOf
String str = "Four score and seven years ago";
int first, last;
first = str.indexOf('r');
last = str.lastIndexOf('r');
System.out.println("The letter r first appears at position " + first);
System.out.println("The letter r last appears at position " + last);
// This code will find ALL occurences
String str = "and a one and a two and a three";
int position;
System.out.println("The word and appears at the following
locations.");
position = str.indexOf("and");
while (position != -1)
{
System.out.println(position);
position = str.indexOf("and", position + 1);
}
24. 9-24
Extracting Substrings
• The String class provides methods to extract
substrings in a String object.
– The substring method returns a substring beginning at a
start location and an optional ending location.
String fullName = "Cynthia Susan Smith";
String lastName = fullName.substring(14);
String firstName = fullName.substring(0, 7);
System.out.println("The full name is “ + fullName);
System.out.println("The last name is “ + lastName);
25. 9-25
Extracting Characters to Arrays
• The String class provides methods to extract substrings in a String object
and store them in char arrays.
– getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
• Stores a substring in a char array
• srcBegin: first index to start copying from in the src string getChars is called on (e.g.
src.getChars(…)
• srcEnd: index after the last character in the string to copy
• dst: the destination array to copy to. Must be created already
• dstBegin: the start offset in the destination array to start copying
– toCharArray()
• Returns the String object’s contents in an array of char values.
String fullName = "Cynthia Susan Smith";
char[] nameArray = fullName.toCharArray();
char[] middleName;
fullName.getChars(8, 13, middleName, 0);
char[] chars = fullName.toCharArray();
8 13
26. 9-26
Returning Modified Strings
• The String class provides methods that return
modified String objects.
– concat(String str)
• Returns a String object that is the concatenation of two String
objects; the original and the str given as input.
String s1 = “Hello”;
s1 = s1.concat(“ there”);
– replace(char oldChar, char newChar)
• Returns a String object with all occurrences of one character being
replaced by another character.
s1 = s1.replace(‘l’, ‘L’);
– trim()
• Returns a String object with all leading and trailing whitespace
characters removed.
s1 = s1.trim();
27. 9-27
The valueOf Methods
• The String class provides several overloaded valueOf
methods.
• They return a String object representation of
– a primitive value or
– a character array.
String.valueOf(true) will return "true".
String.valueOf(5.0) will return "5.0".
String.valueOf(‘C’) will return "C".
28. 9-28
The valueOf Methods
boolean b = true;
char [] letters = { 'a', 'b', 'c', 'd', 'e' };
double d = 2.4981567;
int i = 7;
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(letters));
System.out.println(String.valueOf(letters, 1, 3));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(i));
• Produces the following output:
true
abcde
bcd
2.4981567
7
29. 9-29
CW Part-1-1: Wrapper Classes, Strings and Characters
Write a program that:
Part A: asks the user for a series of floats until the user enters -1. The program
should store the numbers in an ArrayList of Floats then calls the Collections.sort
method to sort the ArrayList and print the contents back on separate lines.
Part B: asks the user for a String. The program reads in the String and displays the
following statistics:
– Number of upper case letters
– Number of digits
– Number of white spaces
– The location/index of all occurrences of the letter ‘e’. If there are no e’s, it should
print “String has no e’s”. Use an ArrayList to collect the location of all the e’s.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/csc128-part-1-classwork
then choose CSC128-Classwork-1-1
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
30. 9-30
The StringBuilder Class
• The String class is immutable – changes cannot made to an
existing String.
• The StringBuilder class is a class similar to the String class, but
it is mutable – changes can be made.
• There are three ways to construct a StringBuilder:
– StringBuilder(): create an empty StringBuilder of length 16
– StringBuilder(int length): create an empty StringBuilder with
the specified length
– StringBuilder(String str): create a StringBuilder with the
string’s contents.
31. 9-31
Common Methods between String and
StringBuilder
• The String and StringBuilder have some methods in common:
char charAt(int position)
void getChars(int start, int end,
char[] array, int arrayStart)
int indexOf(String str)
int indexOf(String str, int start)
int lastIndexOf(String str)
int lastIndexOf(String str, int start)
int length()
String substring(int start)
String substring(int start, int end)
32. 9-32
Appending to a StringBuilder Object
• The StringBuilder class has several overloaded versions
of a method named append.
• They append a string representation of their argument to the
calling object’s current contents.
• The general form of the append method is:
object.append(item);
– where object is an instance of the StringBuilder
class and item is:
• a primitive literal or variable.
• a char array, or
• a String literal or object.
33. 9-33
• After the append method is called, a string representation of
item will be appended to object’s contents.
StringBuilder str = new StringBuilder();
str.append("We sold ");
str.append(12);
str.append(" doughnuts for $");
str.append(15.95);
System.out.println(str);
• This code will produce the following output:
We sold 12 doughnuts for $15.95
Appending to a StringBuilder Object
34. 9-34
• The StringBuilder class also has several overloaded
versions of a method named insert
object.insert(start, item);
• These methods accept two arguments:
– start: an int that specifies the position to begin insertion, and
– item: the value to be inserted.
• The value to be inserted may be
– a primitive literal or variable.
– a char array, or
– a String literal or object.
Appending to a StringBuilder Object
35. 9-35
• The StringBuilder class has a replace method that
replaces a specified substring with a string.
object.replace(start, end, str);
• start: an int that specifies the starting position of a substring in
the calling object
• end: an int that specifies the ending position of the substring.
(The starting position is included in the substring, but the ending
position is not.)
• str: String object to replace in the original string
– After the method executes, the substring will be replaced
with str.
Replacing a Substring in a StringBuilder Object
36. 9-36
• The replace method in this code replaces the word
“Chicago” with “New York”.
StringBuilder str = new StringBuilder(
"We moved from Chicago to Atlanta.");
str.replace(14, 21, "New York");
System.out.println(str);
• The code will produce the following output:
We moved from New York to Atlanta.
Replacing a Substring in a StringBuilder Object
37. 9-37
Other StringBuilder Methods
• The StringBuilder class also provides methods to set and
delete characters in an object.
StringBuilder str = new StringBuilder(
"I ate 100 blueberries!");
// Display the StringBuilder object.
System.out.println(str);
// Delete the '0'.
str.deleteCharAt(8);
// Delete "blue".
str.delete(9, 13); // starting at 9 and ending at 13
// Display the StringBuilder object.
System.out.println(str);
// Change the '1' to '5'
str.setCharAt(6, '5');
// Display the StringBuilder object.
System.out.println(str);
38. Other StringBuilder Methods
• The toString method
– You can call a StringBuilder's toString
method to convert that StringBuilder object to
a regular String
StringBuilder strb = new StringBuilder("This is a test.");
String str = strb.toString();
39. 9-39
Tokenizing Strings
• Use the String class’s split method
• Tokenizes a String object and returns an array of String
objects
• Each array element is one token.
// Create a String to tokenize.
String str = "one two three four";
// Get the tokens from the string.
String[] tokens = str.split(" ");
// Display each token.
for (String s : tokens)
System.out.println(s);
• This code will produce the following output:
one
two
three
four
40. 9-40
CW Part-1-2: String Tokenizer
• Ask the user for the prices of items bought for lunch. The prices should
be entered separated by commas using a single String. (e.g. $6.99, $1.09,
$1.99)
• Read in the String, remove the $ signs and use the split method to get a
String[] of the prices entered.
• Trim the white spaces around the strings and convert the Strings to
floats using the parse methods and add them all up.
• Display the total price to be paid.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/csc128-part-1-classwork
then choose CSC128-Classwork-1-2
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
41. 9-41
Programming Assignment (50 Points)
Write a class with the following static methods:
• WordCounter: This method takes a String and returns the number of words in the String.
• convertToString: This method takes an ArrayList of Characters and returns a String
representation of the characters.
• mostFound: This method takes a String and returns the character that appears the most in the
String. Ignore the case when counting.
• replacePart: This method takes 3 Strings original, toReplace, replaceWith. It finds all
occurrences of toReplace in the original String and returns the original String with toReplace
replaced with replaceWith. For example, if the original String was “I have two dogs and two
cats”, toReplace is “two” and replaceWith is “three”, the method returns the String “I have
three dogs and three cats”.
Write a main method that:
• Asks the user for a String, a toReplace String and a replaceWith String. It prints:
– Number of words in the String
– The character that appears the most in the String
– The new String after calling replacePart
• Asks the user for a series of characters and creates an ArrayList of these characters. The user
should press . when done entering characters. It then prints out the Characters as a String
(using convertToString) and prints the String in all upper case.
Compile and test your code in NetBeans and then on Hackerrank at
https://www.hackerrank.com/contests/csc128-programmingassignments then choose CSC128-Part-1-PA
Submit your .java file and a screenshot of passing all test cases on Hackerrank.
42. Acknowledgment
"Java II – Part 1 – Wrapper Classes and
Strings" by Ibtsam Mahfouz, Manchester
Community College is licensed under CC BY-
NC-SA 4.0 / A derivative from the original
work