The document discusses programming techniques for a course, including an overview of programming and the program development life cycle which involves analyzing a problem, designing an algorithm to solve it, implementing the algorithm in code, and maintaining the program if needed. It also provides examples of programming concepts like identifiers, comments, and errors that can occur during the programming process.
The document provides an introduction to the Java programming language. It discusses object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It then describes the Java programming language, how Java programs are structured using classes and methods, and how comments are used. It also discusses program development processes like compiling, interpreting and debugging programs as well as object-oriented problem solving and design.
A programming language specifies the words and symbols that we can use to write a program
A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements
The Java programming language was created by Sun Microsystems, Inc.
It was introduced in 1995 and it's popularity has grown quickly since then.
C,c++,java,php,.net training institute in delhi, best training institute for ...MCM COmpetitive Classes
Java is an object-oriented programming language created by Sun Microsystems. The document provides an overview of Java, including its history, features, uses in different types of applications, and how the Java Virtual Machine works. It also describes CPD Technologies' Java training program, which covers core Java concepts as well as advanced topics like servlets, JSP, EJB, Struts, Hibernate, and live project development.
This document provides an introduction and overview of a course on Java software solutions and program design. It discusses the focus of the course on object-oriented software development and the Java programming language. It also covers topics like Java program structure, comments, identifiers, reserved words, and the basic process of program development including writing code, compiling, executing and debugging programs.
The document outlines the course details for a Mobile App Development class. It includes:
- The course instructor's contact information.
- Recommended reference books and websites for learning Java.
- The marking criteria for assignments, projects, exams.
- General classroom rules around cell phones, food, and behavior.
- An outline of lecture topics that will cover what Java is, its history and features.
Java Programming - Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This document provides an overview of programming in Java. It outlines the course objectives which are to teach object-oriented programming fundamentals in Java, how to develop Java applications and applets, and create GUI-based apps that run across platforms. It then lists some reference books and introduces basic concepts like Java's history, data types, variables, and control structures. The document also compares Java to C/C++ and outlines the Java compilation and interpretation process.
This document provides an introduction to Java programming, including setting up a development environment. It discusses downloading and installing the Java Development Kit (JDK) and Eclipse integrated development environment. It then provides an overview of key concepts in the Java language and platform, such as object-oriented programming, the Java compiler, Java virtual machine, garbage collection, and Java Development Kit. The document is intended to help new Java developers get started with building Java applications.
The document provides an introduction to the Java programming language. It discusses object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It then describes the Java programming language, how Java programs are structured using classes and methods, and how comments are used. It also discusses program development processes like compiling, interpreting and debugging programs as well as object-oriented problem solving and design.
A programming language specifies the words and symbols that we can use to write a program
A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements
The Java programming language was created by Sun Microsystems, Inc.
It was introduced in 1995 and it's popularity has grown quickly since then.
C,c++,java,php,.net training institute in delhi, best training institute for ...MCM COmpetitive Classes
Java is an object-oriented programming language created by Sun Microsystems. The document provides an overview of Java, including its history, features, uses in different types of applications, and how the Java Virtual Machine works. It also describes CPD Technologies' Java training program, which covers core Java concepts as well as advanced topics like servlets, JSP, EJB, Struts, Hibernate, and live project development.
This document provides an introduction and overview of a course on Java software solutions and program design. It discusses the focus of the course on object-oriented software development and the Java programming language. It also covers topics like Java program structure, comments, identifiers, reserved words, and the basic process of program development including writing code, compiling, executing and debugging programs.
The document outlines the course details for a Mobile App Development class. It includes:
- The course instructor's contact information.
- Recommended reference books and websites for learning Java.
- The marking criteria for assignments, projects, exams.
- General classroom rules around cell phones, food, and behavior.
- An outline of lecture topics that will cover what Java is, its history and features.
Java Programming - Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
This document provides an overview of programming in Java. It outlines the course objectives which are to teach object-oriented programming fundamentals in Java, how to develop Java applications and applets, and create GUI-based apps that run across platforms. It then lists some reference books and introduces basic concepts like Java's history, data types, variables, and control structures. The document also compares Java to C/C++ and outlines the Java compilation and interpretation process.
This document provides an introduction to Java programming, including setting up a development environment. It discusses downloading and installing the Java Development Kit (JDK) and Eclipse integrated development environment. It then provides an overview of key concepts in the Java language and platform, such as object-oriented programming, the Java compiler, Java virtual machine, garbage collection, and Java Development Kit. The document is intended to help new Java developers get started with building Java applications.
This document provides an overview of the different versions of Java Development Kits (JDKs) and Java platforms, including JDK 1.0 through 1.4, Java 2 Standard Edition (J2SE) 1.2 through 1.4, Java 2 Enterprise Edition (J2EE), and Java 2 Micro Edition (J2ME). It describes the major additions and improvements in each release, such as new APIs, features, and deprecated classes. It also discusses the differences between the Java language and platforms. Finally, it provides support for the statement that while the Java language specification has not changed dramatically since JDK 1.1, the Java APIs have improved significantly.
This document provides an overview of a Core Java programming tutorial, including an introduction to Java's history and objectives of the course. The course syllabus is outlined which covers topics ranging from basic Java concepts like variables and data types to more advanced topics like methods and loops over 15 chapters. Finally, the document discusses key features, advantages and uses of Java for web and mobile application development.
Java was developed by James Gosling at Sun Microsystems in 1991. It is a popular, object-oriented programming language that is robust, secure, portable, and high-performance. Java code is compiled to bytecode that runs on a Java Virtual Machine, allowing it to run on any platform. The document discusses Java naming conventions, data types, literals, and control statements. It also provides examples of Java code.
Java is a programming language and platform that is commonly used to develop desktop applications, web applications, mobile apps, and more. The document introduces Java by explaining what it is, where it is used, the types of Java applications that can be created, and how the Java compilation and execution process works at a high level. It also provides an example "Hello World" Java program to demonstrate the basic anatomy of a Java file, including classes, methods, and how the main method acts as the program entry point.
Java is an object-oriented programming language that is high-level, robust, secure, portable and multi-threaded. It was developed by James Gosling at Sun Microsystems in the early 1990s. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) making Java platform independent. The JVM interprets the bytecode and performs tasks like memory management and security.
This document provides an overview of Java programming including:
- A brief history of Java originating from Sun Microsystems' Green project in the 1990s.
- An introduction to core Java concepts like the Java Virtual Machine, bytecode, and platforms independence.
- A discussion of object-oriented programming principles like abstraction, encapsulation, and polymorphism and how they are implemented in Java.
- Descriptions of common Java program types like applications and applets and how they are processed by the Java runtime environment.
- An introduction to Unified Modeling Language (UML) diagrams used for software design.
The document provides an introduction to Java programming including:
- Java is an object-oriented language where programs are written as classes and allows "write once, run anywhere" functionality.
- Key features of Java include being simple, robust, secure, multi-threaded, and dynamically flexible.
- The Java architecture includes the compiler, JVM, JRE and JDK which work together to compile and execute Java code.
- Common Java applications include mobile apps, desktop apps, web apps, games, cloud apps, and IoT apps.
- A basic Java program structure includes documentation, packages, imports, classes, and a main method.
Demo Lecture 01 Notes.pptx by Sabki KakshaGandhiSarthak
This document provides an introduction and overview of the Java programming language. It begins by explaining why Java is a useful language to learn, highlighting its high demand, versatility, platform independence, large community, and ability to provide a strong foundation for other languages. It then defines Java as a high-level, object-oriented programming language that utilizes bytecode to run on any system with a Java Virtual Machine. The document also presents a simple "Hello World" Java program and explains the key components and how it works. Finally, it outlines some of Java's key features like its robustness, security, and support for multithreading.
Here are the key differences:
Reserved words: These are words that have special meaning in Java like class, public, etc. They cannot be used as regular identifiers.
Modifiers: Modifiers like public, private, static etc. specify attributes of classes, methods and variables.
Package: A package is a namespace that organizes related classes and interfaces. It provides access protection.
Libraries: Libraries are pre-compiled classes that provide useful functionality that can be included in programs using import statements.
JVM version: The Java Virtual Machine version specifies the Java runtime environment. Programs need to be compatible with the JVM version.
JVM: The Java Virtual Machine is an abstract computing machine that
This document outlines the syllabus for an Object Oriented Programming course in Java. The course aims to teach students the principles of OOP using Java, including classes, objects, inheritance, polymorphism, exceptions handling, and more. It covers topics like Java basics, GUI programming, JDBC, collections, and multithreading. The course objectives are to enable students to write Java programs that solve problems and demonstrate good OOP skills. The content includes revising Java principles, learning about classes, interfaces, packages and more.
This document outlines the syllabus for an Object Oriented Programming course in Java. The course aims to teach students the principles of OOP using Java, including classes, objects, inheritance, polymorphism, interfaces, exceptions handling, and more. It will cover both programming concepts in Java as well as GUI, database connectivity, collections, and multithreading. The course content is presented over several classes and includes lectures, practical sessions, and assessed exercises.
The document outlines an advanced programming course covering various programming paradigms including structured, object-oriented, procedural, and functional paradigms. It discusses key concepts of each paradigm such as classes, inheritance, polymorphism, and functions. It also covers defining functions, parameters, anonymous functions, and object-oriented concepts in Python like method overriding and constructors/destructors.
Java was originally created at Sun Microsystems in 1991 to program home appliances. It was designed to simplify compiler writing for different processors by using an intermediate bytecode language. This bytecode is the same for all processors and only requires a small program to translate to machine code for each specific processor. Java became widely used for internet applications when web browsers began incorporating Java applets in 1994-1995. Key aspects of Java include its object-oriented design with classes and methods, and its portability achieved through compiling to bytecode that runs on a virtual machine.
Rod Johnson created the Spring Framework, an open-source Java application framework. Spring is considered a flexible, low-cost framework that improves coding efficiency. It helps developers perform functions like creating database transaction methods without transaction APIs. Spring removes configuration work so developers can focus on writing business logic. The Spring Framework uses inversion of control (IoC) and dependency injection (DI) principles to manage application objects and dependencies between them.
Java v/s .NET is an age old debate! We have compared both Java and .NET on parameters like technical performance and future scope. NIIT provides certification courses for both Java and .NET. View our presentation and choose which course to enrol for at NIIT!
The document discusses key concepts in Java programming including:
- Java is a platform independent, object-oriented language that is designed to run on any system that supports Java.
- The main features of Java include being robust, secure, portable, and having high performance.
- Java supports important concepts like abstraction, encapsulation, inheritance, polymorphism, and exceptions.
- The document outlines Java keywords, comments, data types, variables, basic programs, and common operators.
This document provides an overview of the Java programming language by discussing what Java is, where it is used, types of Java applications, and the history and features of Java. Some key points:
- Java is an object-oriented programming language and platform that is widely used to create desktop, web, enterprise, mobile, and other applications.
- Java applications can run on many platforms due to its platform independence. It uses a virtual machine to execute bytecode, allowing code to run on different operating systems.
- The Java language was originally developed by James Gosling and Sun Microsystems in the early 1990s and was released in 1995. It has since evolved through many versions.
- Common features of
This document provides an overview of the different versions of Java Development Kits (JDKs) and Java platforms, including JDK 1.0 through 1.4, Java 2 Standard Edition (J2SE) 1.2 through 1.4, Java 2 Enterprise Edition (J2EE), and Java 2 Micro Edition (J2ME). It describes the major additions and improvements in each release, such as new APIs, features, and deprecated classes. It also discusses the differences between the Java language and platforms. Finally, it provides support for the statement that while the Java language specification has not changed dramatically since JDK 1.1, the Java APIs have improved significantly.
This document provides an overview of a Core Java programming tutorial, including an introduction to Java's history and objectives of the course. The course syllabus is outlined which covers topics ranging from basic Java concepts like variables and data types to more advanced topics like methods and loops over 15 chapters. Finally, the document discusses key features, advantages and uses of Java for web and mobile application development.
Java was developed by James Gosling at Sun Microsystems in 1991. It is a popular, object-oriented programming language that is robust, secure, portable, and high-performance. Java code is compiled to bytecode that runs on a Java Virtual Machine, allowing it to run on any platform. The document discusses Java naming conventions, data types, literals, and control statements. It also provides examples of Java code.
Java is a programming language and platform that is commonly used to develop desktop applications, web applications, mobile apps, and more. The document introduces Java by explaining what it is, where it is used, the types of Java applications that can be created, and how the Java compilation and execution process works at a high level. It also provides an example "Hello World" Java program to demonstrate the basic anatomy of a Java file, including classes, methods, and how the main method acts as the program entry point.
Java is an object-oriented programming language that is high-level, robust, secure, portable and multi-threaded. It was developed by James Gosling at Sun Microsystems in the early 1990s. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) making Java platform independent. The JVM interprets the bytecode and performs tasks like memory management and security.
This document provides an overview of Java programming including:
- A brief history of Java originating from Sun Microsystems' Green project in the 1990s.
- An introduction to core Java concepts like the Java Virtual Machine, bytecode, and platforms independence.
- A discussion of object-oriented programming principles like abstraction, encapsulation, and polymorphism and how they are implemented in Java.
- Descriptions of common Java program types like applications and applets and how they are processed by the Java runtime environment.
- An introduction to Unified Modeling Language (UML) diagrams used for software design.
The document provides an introduction to Java programming including:
- Java is an object-oriented language where programs are written as classes and allows "write once, run anywhere" functionality.
- Key features of Java include being simple, robust, secure, multi-threaded, and dynamically flexible.
- The Java architecture includes the compiler, JVM, JRE and JDK which work together to compile and execute Java code.
- Common Java applications include mobile apps, desktop apps, web apps, games, cloud apps, and IoT apps.
- A basic Java program structure includes documentation, packages, imports, classes, and a main method.
Demo Lecture 01 Notes.pptx by Sabki KakshaGandhiSarthak
This document provides an introduction and overview of the Java programming language. It begins by explaining why Java is a useful language to learn, highlighting its high demand, versatility, platform independence, large community, and ability to provide a strong foundation for other languages. It then defines Java as a high-level, object-oriented programming language that utilizes bytecode to run on any system with a Java Virtual Machine. The document also presents a simple "Hello World" Java program and explains the key components and how it works. Finally, it outlines some of Java's key features like its robustness, security, and support for multithreading.
Here are the key differences:
Reserved words: These are words that have special meaning in Java like class, public, etc. They cannot be used as regular identifiers.
Modifiers: Modifiers like public, private, static etc. specify attributes of classes, methods and variables.
Package: A package is a namespace that organizes related classes and interfaces. It provides access protection.
Libraries: Libraries are pre-compiled classes that provide useful functionality that can be included in programs using import statements.
JVM version: The Java Virtual Machine version specifies the Java runtime environment. Programs need to be compatible with the JVM version.
JVM: The Java Virtual Machine is an abstract computing machine that
This document outlines the syllabus for an Object Oriented Programming course in Java. The course aims to teach students the principles of OOP using Java, including classes, objects, inheritance, polymorphism, exceptions handling, and more. It covers topics like Java basics, GUI programming, JDBC, collections, and multithreading. The course objectives are to enable students to write Java programs that solve problems and demonstrate good OOP skills. The content includes revising Java principles, learning about classes, interfaces, packages and more.
This document outlines the syllabus for an Object Oriented Programming course in Java. The course aims to teach students the principles of OOP using Java, including classes, objects, inheritance, polymorphism, interfaces, exceptions handling, and more. It will cover both programming concepts in Java as well as GUI, database connectivity, collections, and multithreading. The course content is presented over several classes and includes lectures, practical sessions, and assessed exercises.
The document outlines an advanced programming course covering various programming paradigms including structured, object-oriented, procedural, and functional paradigms. It discusses key concepts of each paradigm such as classes, inheritance, polymorphism, and functions. It also covers defining functions, parameters, anonymous functions, and object-oriented concepts in Python like method overriding and constructors/destructors.
Java was originally created at Sun Microsystems in 1991 to program home appliances. It was designed to simplify compiler writing for different processors by using an intermediate bytecode language. This bytecode is the same for all processors and only requires a small program to translate to machine code for each specific processor. Java became widely used for internet applications when web browsers began incorporating Java applets in 1994-1995. Key aspects of Java include its object-oriented design with classes and methods, and its portability achieved through compiling to bytecode that runs on a virtual machine.
Rod Johnson created the Spring Framework, an open-source Java application framework. Spring is considered a flexible, low-cost framework that improves coding efficiency. It helps developers perform functions like creating database transaction methods without transaction APIs. Spring removes configuration work so developers can focus on writing business logic. The Spring Framework uses inversion of control (IoC) and dependency injection (DI) principles to manage application objects and dependencies between them.
Java v/s .NET is an age old debate! We have compared both Java and .NET on parameters like technical performance and future scope. NIIT provides certification courses for both Java and .NET. View our presentation and choose which course to enrol for at NIIT!
The document discusses key concepts in Java programming including:
- Java is a platform independent, object-oriented language that is designed to run on any system that supports Java.
- The main features of Java include being robust, secure, portable, and having high performance.
- Java supports important concepts like abstraction, encapsulation, inheritance, polymorphism, and exceptions.
- The document outlines Java keywords, comments, data types, variables, basic programs, and common operators.
This document provides an overview of the Java programming language by discussing what Java is, where it is used, types of Java applications, and the history and features of Java. Some key points:
- Java is an object-oriented programming language and platform that is widely used to create desktop, web, enterprise, mobile, and other applications.
- Java applications can run on many platforms due to its platform independence. It uses a virtual machine to execute bytecode, allowing code to run on different operating systems.
- The Java language was originally developed by James Gosling and Sun Microsystems in the early 1990s and was released in 1995. It has since evolved through many versions.
- Common features of
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
4. What is programing and program development life cycle ?
• Programing is the process of problem solving
• Step 1:analyze the problem
- understand the overall problem
- Define problem requirements
• Does a program require user interaction
– If yes, what is the input?
• What is the expected output?
- Design steps (algorithm) to solve the problem
Algorithm: step by step problem-solving process.
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
5. • Step 2: implement the algorithm
– implement the algorithm in code
– Verify that the algorithm works
• Step 3:maintenance
– Use and modify the program if the problem domain
changes
– If the problem is complex, divided it to sub-problems
– Analyze each sub-problem as above
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
What is programing and program development life cycle ?
6. Example
• Write a program to find area of rectangle?
The area of rectangle is given by the following formula:
area=rect length* rect width
Input
Rectangle length, Rectangle width
Process
area=rect length* rect width
Output
Print out the area.
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
7. Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
8. Java
• The Java programming language was created by
Sun Microsystems, Inc.
• It was introduced in 1995 and it's popularity has
grown quickly since
• A programming language specifies the words and
symbols that we can use to write a program
• A programming language employs a set of rules
that dictate how the words and symbols can be put
together to form valid program statements
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
9. Java Program Structure
• In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
• These terms will be explored in detail throughout
the course
• A Java application always contains a method
called main
• See Lincoln.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
10. Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
//********************************************************************
// Lincoln.java Author: Lewis/Loftus
//
// Demonstrates the basic structure of a Java application.
//********************************************************************
public class Lincoln
{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
System.out.println ("Whatever you are, be a good one.");
}
}
11. Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
//********************************************************************
// Lincoln.java Author: Lewis/Loftus
//
// Demonstrates the basic structure of a Java application.
//********************************************************************
public class Lincoln
{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
System.out.println ("Whatever you are, be a good one.");
}
}
Output
A quote by Abraham Lincoln:
Whatever you are, be a good one.
12. Java Program Structure
public class MyProgram
{
}
// comments about the class
class header
class body
Comments can be placed almost anywhere
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
13. Java Program Structure
public class MyProgram
{
}
// comments about the class
public static void main (String[] args)
{
}
// comments about the method
method header
method body
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
14. Comments
• Comments should be included to explain the
purpose of the program and describe processing
steps
• They do not affect how a program works
• Java comments can take three forms:
// this comment runs to the end of the line
/* this comment runs to the terminating
symbol, even across line breaks */
/** this is a javadoc comment */
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
15. Identifiers
• Identifiers are the "words" in a program
• A Java identifier can be made up of letters, digits,
the underscore character ( _ ), and the dollar sign
• Identifiers cannot begin with a digit
• Java is case sensitive: Total, total, and
TOTAL are different identifiers
• By convention, programmers use different case
styles for different types of identifiers, such as
– title case for class names - Lincoln
– upper case for constants - MAXIMUM
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
16. Identifiers
• Sometimes the programmer chooses the
identifier(such as Lincoln)
• Sometimes we are using another programmer's
code, so we use the identifiers that he or she
chose (such as println)
• Often we use special identifiers called reserved
words that already have a predefined meaning in
the language
• A reserved word cannot be used in any other way
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
17. Reserved Words
• The Java reserved words:
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
18. Quick Check
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
Which of the following are valid Java identifiers?
grade
quizGrade
NetworkConnection
frame2
3rdTestScore
MAXIMUM
MIN_CAPACITY
student#
Shelves1&2
19. Program Development
• The mechanics of developing a program include
several activities:
– writing the program in a specific programming language
(such as Java)
– translating the program into a form that the computer
can execute
– investigating and fixing various types of errors that can
occur
• Software tools can be used to help with all parts
of this process
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
20. Programming Languages
• Each type of CPU executes only a particular
machine language
• A program must be translated into machine
language before it can be executed
• A compiler is a software tool which translates
source code into a specific target language
• Sometimes, that target language is the machine
language for a particular CPU type
• The Java approach is somewhat different
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
21. Java Translation
• The Java compiler translates Java source code
into a special representation called bytecode
• Java bytecode is not the machine language for
any traditional CPU
• Bytecode is executed by the Java Virtual Machine
(JVM)
• Therefore Java bytecode is not tied to any
particular machine
• Java is considered to be architecture-neutral
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
22. Java Translation
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
23. Development Environments
• There are many programs that support the
development of Java software, including:
– Java Development Kit (JDK)
– Eclipse
– NetBeans
– BlueJ
– jGRASP
• Though the details of these environments differ,
the basic compilation and execution process is
essentially the same
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
24. Syntax and Semantics
• The syntax rules of a language define how we can
put together symbols, reserved words, and
identifiers to make a valid program
• The semantics of a program statement define
what that statement means (its purpose or role in
a program)
• A program that is syntactically correct is not
necessarily logically (semantically) correct
• A program will always do what we tell it to do, not
what we meant to tell it to do
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
25. Errors
• A program can have three types of errors
• The compiler will find syntax errors and other basic
problems (compile-time errors)
– If compile-time errors exist, an executable version of the program is
not created
• A problem can occur during program execution, such as
trying to divide by zero, which causes a program to
terminate abnormally (run-time errors)
• A program may run, but produce incorrect results, perhaps
using an incorrect formula (logical errors)
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
26. Basic Program Development
errors?
errors?
Edit and
save program
Compile program
Execute program and
evaluate results
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
27. Outline
What is programing and program development
life cycle ?
The Java Programming Language
Program Development
Object-Oriented Programming
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
28. Object-Oriented Programming
• Java is an object-oriented programming language
• As the term implies, an object is a fundamental
entity in a Java program
• Objects can be used effectively to represent real-
world entities
• For instance, an object might represent a particular
employee in a company
• Each employee object handles the processing and
data management related to that employee
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
29. Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or what can be done to it)
• The state of a bank account includes its account
number and its current balance
• The behaviors associated with a bank account
include the ability to make deposits and
withdrawals
• Note that the behavior of an object might change
its state
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
30. Classes
• An object is defined by a class
• A class is the blueprint of an object
• The class uses methods to define the behaviors of
the object
• The class that contains the main method of a Java
program represents the entire program
• A class represents a concept, and an object
represents the embodiment of that concept
• Multiple objects can be created from the same
class
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
31. Class = Blueprint
• One blueprint to create several similar, but
different, houses:
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
32. Objects and Classes
Bank
Account
A class
(the concept)
John’s Bank Account
Balance: $5,257
An object
(the realization)
Bill’s Bank Account
Balance: $1,245,069
Mary’s Bank Account
Balance: $16,833
Multiple objects
from the same class
Slides adapted from Java Software Solutions Foundations of Program Design 8th ,
John Lewis • William Loftus
33. The print Method
• The System.out object provides another service
as well
• The print method is similar to the println
method, except that it does not advance to the
next line
• Therefore anything printed after a print
statement will appear on the same line
• See Countdown.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
34. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
public class Countdown
{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main(String[] args)
{
System.out.print("Three... ");
System.out.print("Two... ");
System.out.print("One... ");
System.out.print("Zero... ");
System.out.println("Liftoff!"); // appears on first output line
System.out.println("Houston, we have a problem.");
}
}
35. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
public class Countdown
{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main(String[] args)
{
System.out.print("Three... ");
System.out.print("Two... ");
System.out.print("One... ");
System.out.print("Zero... ");
System.out.println("Liftoff!"); // appears on first output line
System.out.println("Houston, we have a problem.");
}
}
Output
Three... Two... One... Zero... Liftoff!
Houston, we have a problem.
36. String Concatenation
• The string concatenation operator (+) is used to
append one string to the end of another
"Peanut butter " + "and jelly"
• It can also be used to append a number to a string
• A string literal cannot be broken across two lines
in a program
• See Facts.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
37. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Facts.java Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************
public class Facts
{
//-----------------------------------------------------------------
// Prints various facts.
//-----------------------------------------------------------------
public static void main(String[] args)
{
// Strings can be concatenated into one long string
System.out.println("We present the following facts for your "
+ "extracurricular edification:");
System.out.println();
// A string can contain numeric digits
System.out.println("Letters in the Hawaiian alphabet: 12");
continue
38. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continue
// A numeric value can be concatenated to a string
System.out.println("Dialing code for Antarctica: " + 672);
System.out.println("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println("Speed of ketchup: " + 40 + " km per year");
}
}
39. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continue
// A numeric value can be concatenated to a string
System.out.println ("Dialing code for Antarctica: " + 672);
System.out.println ("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println("Speed of ketchup: " + 40 + " km per year");
}
}
Output
We present the following facts for your extracurricular edification:
Letters in the Hawaiian alphabet: 12
Dialing code for Antarctica: 672
Year in which Leonardo da Vinci invented the parachute: 1515
Speed of ketchup: 40 km per year
40. String Concatenation
• The + operator is also used for arithmetic addition
• The function that it performs depends on the type of the
information on which it operates
• If both operands are strings, or if one is a string and one is
a number, it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but parentheses
can be used to force the order
• See Addition.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
41. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main(String[] args)
{
System.out.println("24 and 45 concatenated: " + 24 + 45);
System.out.println("24 and 45 added: " + (24 + 45));
}
}
42. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main(String[] args)
{
System.out.println("24 and 45 concatenated: " + 24 + 45);
System.out.println("24 and 45 added: " + (24 + 45));
}
}
Output
24 and 45 concatenated: 2445
24 and 45 added: 69
43. Variables
• A variable is a name for a location in memory that
holds a value
• A variable declaration specifies the variable's name
and the type of information that it will hold
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
44. Variable Initialization
• A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
• When a variable is referenced in a program, its
current value is used
• See PianoKeys.java
45. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
public class PianoKeys
{
//-----------------------------------------------------------------
// Prints the number of keys on a piano.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int keys = 88;
System.out.println("A piano has " + keys + " keys.");
}
}
46. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
public class PianoKeys
{
//-----------------------------------------------------------------
// Prints the number of keys on a piano.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int keys = 88;
System.out.println("A piano has " + keys + " keys.");
}
}
Output
A piano has 88 keys.
47. Assignment
• An assignment statement changes the value of a
variable
• The assignment operator is the = sign
total = 55;
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
• The value that was in total is overwritten
• You can only assign a value to a variable that is
consistent with the variable's declared type
• See Geometry.java
48. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Geometry.java Author: Lewis/Loftus
//
// Demonstrates the use of an assignment statement to change the
// value stored in a variable.
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int sides = 7; // declaration with initialization
System.out.println("A heptagon has " + sides + " sides.");
sides = 10; // assignment statement
System.out.println("A decagon has " + sides + " sides.");
sides = 12;
System.out.println("A dodecagon has " + sides + " sides.");
}
}
49. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Geometry.java Author: Lewis/Loftus
//
// Demonstrates the use of an assignment statement to change the
// value stored in a variable.
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println ("A heptagon has " + sides + " sides.");
sides = 10; // assignment statement
System.out.println ("A decagon has " + sides + " sides.");
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
Output
A heptagon has 7 sides.
A decagon has 10 sides.
a dodecagon has 12 sides.
50. Constants
• A constant is an identifier that is similar to a
variable except that it holds the same value during
its entire existence
• As the name implies, it is constant, not variable
• The compiler will issue an error if you try to change
the value of a constant
• In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
51. Interactive Programs
• Programs generally need input on which to
operate
• The Scanner class provides convenient methods
for reading input values of various types
• A Scanner object can be set up to read input from
various sources, including the user typing values
on the keyboard
• Keyboard input is represented by the System.in
object
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
52. Reading Input
• The following line creates a Scanner object that
reads from the keyboard:
Scanner scan = new Scanner(System.in);
• The new operator creates the Scanner object
• Once created, the Scanner object can be used to
invoke various input methods, such as:
answer = scan.nextLine();
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
53. Reading Input
• The Scanner class is part of the java.util class
library, and must be imported into a program to be
used
• The nextLine method reads all of the input until
the end of the line is found
• See Echo.java
• The details of object creation and class libraries are
discussed further in Chapter 3
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
54. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main(String[] args)
{
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a line of text:");
message = scan.nextLine();
System.out.println("You entered: "" + message + """);
}
}
55. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main(String[] args)
{
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a line of text:");
message = scan.nextLine();
System.out.println("You entered: "" + message + """);
}
}
Sample Run
Enter a line of text:
You want fries with that?
You entered: "You want fries with that?"
56. Input Tokens
• Unless specified otherwise, white space is used to
separate the elements (called tokens) of the input
• White space includes space characters, tabs, new
line characters
• The next method of the Scanner class reads the
next input token and returns it as a string
• Methods such as nextInt and nextDouble
read data of particular types
• See GasMileage.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
57. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//
// Demonstrates the use of the Scanner class to read numeric data.
//********************************************************************
import java.util.Scanner;
public class GasMileage
{
//-----------------------------------------------------------------
// Calculates fuel efficiency based on values entered by the
// user.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int miles;
double gallons, mpg;
Scanner scan = new Scanner(System.in);
continue
58. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continue
System.out.print("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
System.out.println("Miles Per Gallon: " + mpg);
}
}
59. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continue
System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
System.out.println("Miles Per Gallon: " + mpg);
}
}
Sample Run
Enter the number of miles: 328
Enter the gallons of fuel used: 11.2
Miles Per Gallon: 29.28571428571429
60. Creating Objects
• A variable holds either a primitive value or a
reference to an object
• A class name can be used as a type to declare an
object reference variable
String title;
• No object is created with this declaration
• An object reference variable holds the address of
an object
• The object itself must be created separately
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
61. Creating Objects
• Generally, we use the new operator to create an
object
• Creating an object is called instantiation
• An object is an instance of a particular class
title = new String("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
62. Invoking Methods
• We've seen that once an object has been
instantiated, we can use the dot operator to invoke
its methods
numChars = title.length()
• A method may return a value, which can be used in
an assignment or expression
• A method invocation can be thought of as asking an
object to perform a service
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
63. References
• Note that a primitive variable contains the value
itself, but an object variable contains the address of
the object
• An object reference can be thought of as a pointer
to the location of the object
• Rather than dealing with arbitrary addresses, we
often depict a reference graphically
"Steve Jobs"
name1
num1 38
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
64. Assignment Revisited
• The act of assignment takes a copy of a value and
stores it in a variable
• For primitive types:
num1 38
num2 96
Before:
num2 = num1;
num1 38
num2 38
After:
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
65. Reference Assignment
• For object references, assignment copies the
address:
name2 = name1;
name1
name2
Before:
"Steve Jobs"
"Steve Wozniak"
name1
name2
After:
"Steve Jobs"
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
66. Aliases
• Two or more references that refer to the same
object are called aliases of each other
• That creates an interesting situation: one object
can be accessed using multiple reference variables
• Aliases can be useful, but should be managed
carefully
• Changing an object through one reference
changes it for all of its aliases, because there is
really only one object
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
67. Garbage Collection
• When an object no longer has any valid references
to it, it can no longer be accessed by the program
• The object is useless, and therefore is called
garbage
• Java performs automatic garbage collection
periodically, returning an object's memory to the
system for future use
• In other languages, the programmer is responsible
for performing garbage collection
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
68. The String Class
• Because strings are so common, we don't have to
use the new operator to create a String object
title = "Java Software Solutions";
• This is special syntax that works only for strings
• Each string literal (enclosed in double quotes)
represents a String object
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
69. String Methods
• Once a String object has been created, neither
its value nor its length can be changed
• Therefore we say that an object of the String
class is immutable
• However, several methods of the String class
return new String objects that are modified
versions of the original
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
70. String Indexes
• It is occasionally helpful to refer to a particular
character within a string
• This can be done by specifying the character's
numeric index
• The indexes begin at zero in each string
• In the string "Hello", the character 'H' is at
index 0 and the 'o' is at index 4
• See StringMutation.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
71. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// StringMutation.java Author: Lewis/Loftus
//
// Demonstrates the use of the String class and its methods.
//********************************************************************
public class StringMutation
{
//-----------------------------------------------------------------
// Prints a string and various mutations of it.
//-----------------------------------------------------------------
public static void main(String[] args)
{
String phrase = "Change is inevitable";
String mutation1, mutation2, mutation3, mutation4;
System.out.println("Original string: "" + phrase + """);
System.out.println("Length of string: " + phrase.length());
mutation1 = phrase.concat(", except from vending machines.");
mutation2 = mutation1.toUpperCase();
mutation3 = mutation2.replace('E', 'X');
mutation4 = mutation3.substring(3, 30);
continued
72. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
// Print each mutated string
System.out.println("Mutation #1: " + mutation1);
System.out.println("Mutation #2: " + mutation2);
System.out.println("Mutation #3: " + mutation3);
System.out.println("Mutation #4: " + mutation4);
System.out.println("Mutated length: " + mutation4.length());
}
}
73. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
// Print each mutated string
System.out.println ("Mutation #1: " + mutation1);
System.out.println ("Mutation #2: " + mutation2);
System.out.println ("Mutation #3: " + mutation3);
System.out.println ("Mutation #4: " + mutation4);
System.out.println("Mutated length: " + mutation4.length());
}
}
Output
Original string: "Change is inevitable"
Length of string: 20
Mutation #1: Change is inevitable, except from vending machines.
Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES.
Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS.
Mutation #4: NGX IS INXVITABLX, XXCXPT F
Mutated length: 27
74. Class Libraries
• A class library is a collection of classes that we can
use when developing programs
• The Java standard class library is part of any Java
development environment
• Its classes are not part of the Java language per se,
but we rely on them heavily
• Various classes we've already used (System ,
Scanner, String) are part of the Java standard
class library
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
75. Packages
• For purposes of accessing them, classes in the
Java API are organized into packages
• These often overlap with specific APIs
• Examples:
Package
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
javax.xml.parsers
Purpose
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities
Network communication
Utilities
XML document processing
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
76. The import Declaration
• When you want to use a class from a package, you
could use its fully qualified name
java.util.Scanner
• Or you can import the class, and then use just the
class name
import java.util.Scanner;
• To import all classes in a particular package, you
can use the * wildcard character
import java.util.*;
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
77. The import Declaration
• All classes of the java.lang package are
imported automatically into all programs
• It's as if all programs contain the following line:
import java.lang.*;
• That's why we didn't have to import the System or
String classes explicitly in earlier programs
• The Scanner class, on the other hand, is part of
the java.util package, and therefore must be
imported
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
78. The Random Class
• The Random class is part of the java.util
package
• It provides methods that generate pseudorandom
numbers
• See RandomNumbers.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
79. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// RandomNumbers.java Author: Lewis/Loftus
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println("From 0 to 9: " + num1);
continued
80. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
num1 = generator.nextInt(10) + 1;
System.out.println("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println("From 1 to 6: " + num1);
}
}
81. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println("From 1 to 6: " + num1);
}
}
Sample Run
A random integer: 672981683
From 0 to 9: 0
From 1 to 10: 3
From 20 to 34: 30
From -10 to 9: -4
A random float (between 0-1): 0.18538326
From 1 to 6: 3
82. Quick Check
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
Given a Random object named gen, what range of
values are produced by the following expressions?
gen.nextInt(25)
gen.nextInt(6) + 1
gen.nextInt(100) + 10
gen.nextInt(50) + 100
gen.nextInt(10) – 5
gen.nextInt(22) + 12
83. Quick Check
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
Given a Random object named gen, what range of
values are produced by the following expressions?
gen.nextInt(25)
gen.nextInt(6) + 1
gen.nextInt(100) + 10
gen.nextInt(50) + 100
gen.nextInt(10) – 5
gen.nextInt(22) + 12
Range
0 to 24
1 to 6
10 to 109
100 to 149
-5 to 4
12 to 33
84. The Math Class
• The Math class is part of the java.lang package
• The Math class contains methods that perform
various mathematical functions
• These include:
– absolute value
– square root
– exponentiation
– trigonometric functions
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
85. The Math Class
• The methods of the Math class are static methods
(also called class methods)
• Static methods are invoked through the class name
– no object of the Math class is needed
value = Math.cos(90) + Math.sqrt(delta);
• We discuss static methods further in Chapter 7
• See Quadratic.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
86. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Quadratic.java Author: Lewis/Loftus
//
// Demonstrates the use of the Math class to perform a calculation
// based on user input.
//********************************************************************
import java.util.Scanner;
public class Quadratic
{
//-----------------------------------------------------------------
// Determines the roots of a quadratic equation.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int a, b, c; // ax^2 + bx + c
double discriminant, root1, root2;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the coefficient of x squared: ");
a = scan.nextInt();
continued
87. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
System.out.print("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print("Enter the constant: ");
c = scan.nextInt();
// Use the quadratic formula to compute the roots.
// Assumes a positive discriminant.
discriminant = Math.pow(b, 2) - (4 * a * c);
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Root #1: " + root1);
System.out.println("Root #2: " + root2);
}
}
88. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
System.out.print ("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print ("Enter the constant: ");
c = scan.nextInt();
// Use the quadratic formula to compute the roots.
// Assumes a positive discriminant.
discriminant = Math.pow(b, 2) - (4 * a * c);
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Root #1: " + root1);
System.out.println("Root #2: " + root2);
}
}
Sample Run
Enter the coefficient of x squared: 3
Enter the coefficient of x: 8
Enter the constant: 4
Root #1: -0.6666666666666666
Root #2: -2.0
89. Formatting Output
• It is often necessary to format output values in
certain ways so that they can be presented properly
• The Java standard class library contains classes
that provide formatting capabilities
• The NumberFormat class allows you to format
values as currency or percentages
• The DecimalFormat class allows you to format
values based on a pattern
• Both are part of the java.text package
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
90. Formatting Output
• The NumberFormat class has static methods that
return a formatter object
getCurrencyInstance()
getPercentInstance()
• Each formatter object has a method called
format that returns a string with the specified
information in the appropriate format
• See Purchase.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
91. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// Purchase.java Author: Lewis/Loftus
//
// Demonstrates the use of the NumberFormat class to format output.
//********************************************************************
import java.util.Scanner;
import java.text.NumberFormat;
public class Purchase
{
//-----------------------------------------------------------------
// Calculates the final price of a purchased item using values
// entered by the user.
//-----------------------------------------------------------------
public static void main(String[] args)
{
final double TAX_RATE = 0.06; // 6% sales tax
int quantity;
double subtotal, tax, totalCost, unitPrice;
Scanner scan = new Scanner(System.in);
continued
92. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print("Enter the quantity: ");
quantity = scan.nextInt();
System.out.print("Enter the unit price: ");
unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
System.out.println("Subtotal: " + fmt1.format(subtotal));
System.out.println("Tax: " + fmt1.format(tax) + " at "
+ fmt2.format(TAX_RATE));
System.out.println("Total: " + fmt1.format(totalCost));
}
}
93. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
System.out.print("Enter the unit price: ");
unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
System.out.println("Subtotal: " + fmt1.format(subtotal));
System.out.println("Tax: " + fmt1.format(tax) + " at "
+ fmt2.format(TAX_RATE));
System.out.println("Total: " + fmt1.format(totalCost));
}
}
Sample Run
Enter the quantity: 5
Enter the unit price: 3.87
Subtotal: $19.35
Tax: $1.16 at 6%
Total: $20.51
94. Formatting Output
• The DecimalFormat class can be used to format
a floating point value in various ways
• For example, you can specify that the number
should be truncated to three decimal places
• The constructor of the DecimalFormat class
takes a string that represents a pattern for the
formatted number
• See CircleStats.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
95. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// CircleStats.java Author: Lewis/Loftus
//
// Demonstrates the formatting of decimal values using the
// DecimalFormat class.
//********************************************************************
import java.util.Scanner;
import java.text.DecimalFormat;
public class CircleStats
{
//-----------------------------------------------------------------
// Calculates the area and circumference of a circle given its
// radius.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int radius;
double area, circumference;
Scanner scan = new Scanner(System.in);
continued
96. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
System.out.print ("Enter the circle's radius: ");
radius = scan.nextInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The circle's area: " + fmt.format(area));
System.out.println ("The circle's circumference: "
+ fmt.format(circumference));
}
}
97. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
System.out.print ("Enter the circle's radius: ");
radius = scan.nextInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The circle's area: " + fmt.format(area));
System.out.println("The circle's circumference: "
+ fmt.format(circumference));
}
}
Sample Run
Enter the circle's radius: 5
The circle's area: 78.54
The circle's circumference: 31.416
98. Enumerated Types
• Java allows you to define an enumerated type,
which can then be used to declare variables
• An enumerated type declaration lists all possible
values for a variable of that type
• The values are identifiers of your own choosing
• The following declaration creates an enumerated
type called Season
enum Season {winter, spring, summer, fall};
• Any number of values can be listed
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
99. Enumerated Types
• Once a type is defined, a variable of that type can
be declared:
Season time;
• And it can be assigned a value:
time = Season.fall;
• The values are referenced through the name of the
type
• Enumerated types are type-safe – you cannot
assign any value other than those listed
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
100. Ordinal Values
• Internally, each value of an enumerated type is
stored as an integer, called its ordinal value
• The first value in an enumerated type has an
ordinal value of zero, the second one, and so on
• However, you cannot assign a numeric value to an
enumerated type, even if it corresponds to a valid
ordinal value
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
101. Enumerated Types
• The declaration of an enumerated type is a special
type of class, and each variable of that type is an
object
• The ordinal method returns the ordinal value of
the object
• The name method returns the name of the identifier
corresponding to the object's value
• See IceCream.java
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
102. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
//********************************************************************
// IceCream.java Author: Lewis/Loftus
//
// Demonstrates the use of enumerated types.
//********************************************************************
public class IceCream
{
enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee,
rockyRoad, mintChocolateChip, cookieDough}
//-----------------------------------------------------------------
// Creates and uses variables of the Flavor type.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Flavor cone1, cone2, cone3;
cone1 = Flavor.rockyRoad;
cone2 = Flavor.chocolate;
System.out.println("cone1 value: " + cone1);
System.out.println("cone1 ordinal: " + cone1.ordinal());
System.out.println("cone1 name: " + cone1.name());
continued
103. Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
continued
System.out.println();
System.out.println("cone2 value: " + cone2);
System.out.println("cone2 ordinal: " + cone2.ordinal());
System.out.println("cone2 name: " + cone2.name());
cone3 = cone1;
System.out.println();
System.out.println("cone3 value: " + cone3);
System.out.println("cone3 ordinal: " + cone3.ordinal());
System.out.println("cone3 name: " + cone3.name());
}
}
105. Wrapper Classes
• The java.lang package contains wrapper
classes that correspond to each primitive type:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
106. Wrapper Classes
• The following declaration creates an Integer
object which represents the integer 40 as an object
Integer age = new Integer(40);
• An object of a wrapper class can be used in any
situation where a primitive value will not suffice
• For example, some objects serve as containers of
other objects
• Primitive values could not be stored in such
containers, but wrapper objects could be
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
107. Wrapper Classes
• Wrapper classes also contain static methods that
help manage the associated type
• For example, the Integer class contains a
method to convert an integer stored in a String
to an int value:
num = Integer.parseInt(str);
• They often contain useful constants as well
• For example, the Integer class contains
MIN_VALUE and MAX_VALUE which hold the
smallest and largest int values
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
108. Autoboxing
• Autoboxing is the automatic conversion of a
primitive value to a corresponding wrapper object:
Integer obj;
int num = 42;
obj = num;
• The assignment creates the appropriate Integer
object
• The reverse conversion (called unboxing) also
occurs automatically as needed
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
109. Quick Check
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
Are the following assignments valid? Explain.
Double value = 15.75;
Character ch = new Character('T');
char myChar = ch;
110. Quick Check
Slides adapted from Java Software Solutions Foundations of Program Design 8th , John
Lewis • William Loftus
Are the following assignments valid? Explain.
Double value = 15.75;
Character ch = new Character('T');
char myChar = ch;
Yes. The double literal is autoboxed into a Double object.
Yes, the char in the object is unboxed before the assignment.