Java Programming: Applications and Concepts
VerifiedAdded on 2020/01/28
|24
|6942
|313
Project
AI Summary
This assignment delves into the world of Java programming, showcasing its versatility through various application examples. It covers topics like high-performance computing, database management, information retrieval, graph theory, object-oriented design principles, and exception handling. Students are expected to analyze these examples, understand the underlying concepts, and potentially implement similar solutions. References to academic papers, online resources, and books are provided for further exploration.
Contribute Materials
Your contribution can guide someone’s learning journey. Share your
documents today.
JAVA PROGRAMMING AND ITS BENEFITS
SECTION1
1.0 Features of Java Programming Language
A. Simple
• Java is Easy to compose and more coherent and eye getting.
• Java has a compact, strong arrangement of elements that makes it simple
to learn and utilize.
• Most of the ideas are drew from C++ in this manner making Java learning
less difficult Y. (Daniel Liang, 2012).
B. Secure
• Java program can't hurt other framework, in this way making it secure.
• Java gives a protected method for making Internet applications.
• Java gives secure approach to get to web applications
(http://www.c4learn.com/java/java-qualities highlights/, April 2016).
C. Portable
Java programs can execute in any environment for which there is a Java run-time
system-JVM (http://www.c4learn.com/java/java-characteristics-features/, April
2016).
Java programs can be run on any platform (Linux, Window, Mac)
Java programs can be transferred over World Wide Web (e.g applets)
D. Object-oriented
• Java writing computer programs is article arranged programming dialect.
• Like C++ java gives the vast majority of the item situated components (Daniel
Liang, 2012).
• Java is immaculate OOP. Dialect. (While C++ is semi object situated)
E. Robust
Java supports mistake free programming by being entirely written and
performing run-time checks.
F. Multithreaded
• Java gives incorporated backing to multithreaded programming (Daniel
Liang, 2012).
• Architecture-nonpartisan:
• Java is not attached to a particular machine or working framework design.
SECTION1
1.0 Features of Java Programming Language
A. Simple
• Java is Easy to compose and more coherent and eye getting.
• Java has a compact, strong arrangement of elements that makes it simple
to learn and utilize.
• Most of the ideas are drew from C++ in this manner making Java learning
less difficult Y. (Daniel Liang, 2012).
B. Secure
• Java program can't hurt other framework, in this way making it secure.
• Java gives a protected method for making Internet applications.
• Java gives secure approach to get to web applications
(http://www.c4learn.com/java/java-qualities highlights/, April 2016).
C. Portable
Java programs can execute in any environment for which there is a Java run-time
system-JVM (http://www.c4learn.com/java/java-characteristics-features/, April
2016).
Java programs can be run on any platform (Linux, Window, Mac)
Java programs can be transferred over World Wide Web (e.g applets)
D. Object-oriented
• Java writing computer programs is article arranged programming dialect.
• Like C++ java gives the vast majority of the item situated components (Daniel
Liang, 2012).
• Java is immaculate OOP. Dialect. (While C++ is semi object situated)
E. Robust
Java supports mistake free programming by being entirely written and
performing run-time checks.
F. Multithreaded
• Java gives incorporated backing to multithreaded programming (Daniel
Liang, 2012).
• Architecture-nonpartisan:
• Java is not attached to a particular machine or working framework design.
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
• Machine Independent i.e. Java is autonomous of equipment
(http://www.c 4learn.com/java/java-attributes highlights/, April 2016).
G. Interpreted
• Java bolsters cross-stage code using Java bytecode. Bytecode can be
deciphered on any stage by JVM.
H. High performance
• Byte-codes are exceedingly enhanced.
• JVM can executed them much quicker (Daniel Liang, 2012).
I. Distributed
• Java was planned with the conveyed environment.
• Java can be transmit, keep running over web.
J. Dynamic
Java programs convey with them significant measures of run-time sort data that is
utilized to confirm and resolve gets to objects at run time
(http://www.c4learn.com/java/java-attributes highlights/, April 2016).
1.1. JAVA Runtime Environment
Daniel Liang (2012), the Java Runtime Environment (JRE) is a set of software tools for
development of Java applications. It combines the Java Virtual Machine (JVM), platform
core classes and supporting libraries (https://www.techopedia.com/definition
/5442/java-runtime-environment-jre, April 2016).
From (https://www.techopedia.com/definition/5442/java-runtime-environment-jre,
April 2016), JRE consists of the following components:
i. Deployment technologies, including deployment, Java Web Start and Java Plug-in.
ii. User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java
2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input
methods.
iii. Integration libraries, including Interface Definition Language (IDL), Java
Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI),
Remote Method Invocation (RMI), Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP) and scripting (https://www.techopedia.com/definition
/5442/java-runtime-environment-jre, April 2016).
(http://www.c 4learn.com/java/java-attributes highlights/, April 2016).
G. Interpreted
• Java bolsters cross-stage code using Java bytecode. Bytecode can be
deciphered on any stage by JVM.
H. High performance
• Byte-codes are exceedingly enhanced.
• JVM can executed them much quicker (Daniel Liang, 2012).
I. Distributed
• Java was planned with the conveyed environment.
• Java can be transmit, keep running over web.
J. Dynamic
Java programs convey with them significant measures of run-time sort data that is
utilized to confirm and resolve gets to objects at run time
(http://www.c4learn.com/java/java-attributes highlights/, April 2016).
1.1. JAVA Runtime Environment
Daniel Liang (2012), the Java Runtime Environment (JRE) is a set of software tools for
development of Java applications. It combines the Java Virtual Machine (JVM), platform
core classes and supporting libraries (https://www.techopedia.com/definition
/5442/java-runtime-environment-jre, April 2016).
From (https://www.techopedia.com/definition/5442/java-runtime-environment-jre,
April 2016), JRE consists of the following components:
i. Deployment technologies, including deployment, Java Web Start and Java Plug-in.
ii. User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java
2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input
methods.
iii. Integration libraries, including Interface Definition Language (IDL), Java
Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI),
Remote Method Invocation (RMI), Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP) and scripting (https://www.techopedia.com/definition
/5442/java-runtime-environment-jre, April 2016).
iv. Other base libraries, including international support, input/output (I/O),
extension mechanism, Beans, Java Management Extensions (JMX), Java Native
Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization
and Java for XML Processing (XML JAXP).
v. Lang and util base libraries, including lang and util, management, versioning, zip,
instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR),
Logging, Preferences API, Ref Objects and Regular Expressions (https://www.
techopedia.com/definition /5442/java-runtime-environment-jre, April 2016).
vi. Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual
Machines.
1.2. Environmental flexibility of Java Runtime
Existing programming situations are either helpful (Java), or they are adaptable (Jini,
Java RMI), or they are exceptionally beneficial (MPI). The greatest test is to give a
programming situation and a runtime framework that consolidate very compelling
execution and correspondence with the adaptability to continue running on effectively
changing arrangements of heterogeneous processors and frameworks.
Various scientists assume that Java will be a valuable innovation to diminish the many-
sided quality of matrix application programming (V. Getov, 2001). In perspective of an
all around characterized virtual machine and class libraries, Java is intrinsically more
versatile than dialects like C and Fortran, which are statically incorporated in a
conventional manner. Java grants undertakings to continue running on a heterogeneous
arrangement of assets with no prerequisite for recompilation or porting. Advanced In
the nick of time compilers (JITs, for example, the IBM JIT (A. D. Alexandrov et. at., 1997)
or Sun HotSpot2 get execution speed that is engaged to dialects like C or Fortran (J.M.
Bull, et. al., 2001). Other strong reasons for Java for matrix applications incorporate sort
security and coordinated backing for parallel and appropriated programming. Java gives
Remote Technique Invocation (RMI) for straightforward correspondence between Java
Virtual Machines (JVMs).
extension mechanism, Beans, Java Management Extensions (JMX), Java Native
Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization
and Java for XML Processing (XML JAXP).
v. Lang and util base libraries, including lang and util, management, versioning, zip,
instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR),
Logging, Preferences API, Ref Objects and Regular Expressions (https://www.
techopedia.com/definition /5442/java-runtime-environment-jre, April 2016).
vi. Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual
Machines.
1.2. Environmental flexibility of Java Runtime
Existing programming situations are either helpful (Java), or they are adaptable (Jini,
Java RMI), or they are exceptionally beneficial (MPI). The greatest test is to give a
programming situation and a runtime framework that consolidate very compelling
execution and correspondence with the adaptability to continue running on effectively
changing arrangements of heterogeneous processors and frameworks.
Various scientists assume that Java will be a valuable innovation to diminish the many-
sided quality of matrix application programming (V. Getov, 2001). In perspective of an
all around characterized virtual machine and class libraries, Java is intrinsically more
versatile than dialects like C and Fortran, which are statically incorporated in a
conventional manner. Java grants undertakings to continue running on a heterogeneous
arrangement of assets with no prerequisite for recompilation or porting. Advanced In
the nick of time compilers (JITs, for example, the IBM JIT (A. D. Alexandrov et. at., 1997)
or Sun HotSpot2 get execution speed that is engaged to dialects like C or Fortran (J.M.
Bull, et. al., 2001). Other strong reasons for Java for matrix applications incorporate sort
security and coordinated backing for parallel and appropriated programming. Java gives
Remote Technique Invocation (RMI) for straightforward correspondence between Java
Virtual Machines (JVMs).
Tragically, a hard and energetic issue is Java's menial correspondence speed.
Specifically, Java's RMI execution is abundantly reprimanded (F. Breg, 2001). The
correspondence overhead can be maybe two or three solicitations of degree higher than
that of lower-level models like MPI or RPC (C. Thekkath et. al., 2009). In earlier
exploration on RMI (J. Maassen, 2001), we have tackled this execution issue by utilizing
a local compiler (Manta), supplanting the standard serialization tradition by an
exceptionally compelling, compiler-created zero-duplicate tradition written in C.
Shockingly, this strategy comes up short for matrix programming, as it requires a
custom Java runtime framework that can't be incorporated with standard JVMs. Along
these lines, an imperative exploration issue is the manner by which to get great
correspondence execution for Java without turning to techniques that surrender the
advantages of its virtual machine approach.
1.2.1 PROJECTS DONE WITH JAVA
Java’s open source ecosystem is strong and healthy, one of the primary reasons for our
creation of OSCON Java. Over the last decade, several projects have traveled beyond
mere adoption and had effects dominating the Java world, into software development in
general, and some even further into the daily lives of users (http://radar.
oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.1 JUnit
Ported to Java by Kent Beck and Erich Gamma from Beck’s work in unit testing in
Smalltalk, JUnit has been largely responsible for popularizing test-driven development
over the last decade. Many implementations have been created, in .NET, C, Python, Perl
and just about every language in popular use (http://radar.oreilly .com/2011/07/7-
java-projects.html, April 2016).
1.2.1.2 Eclipse
As Java and its APIs matured in the early 2000s, the Eclipse IDE provided a way for
programmers to be productive and negotiate the growing Java ecosystem. Eclipse was
also the first major project to use the SWT UI toolkit, providing important competition
to Sun’s Swing and showing that Java programs can provide a rich native interface.
Specifically, Java's RMI execution is abundantly reprimanded (F. Breg, 2001). The
correspondence overhead can be maybe two or three solicitations of degree higher than
that of lower-level models like MPI or RPC (C. Thekkath et. al., 2009). In earlier
exploration on RMI (J. Maassen, 2001), we have tackled this execution issue by utilizing
a local compiler (Manta), supplanting the standard serialization tradition by an
exceptionally compelling, compiler-created zero-duplicate tradition written in C.
Shockingly, this strategy comes up short for matrix programming, as it requires a
custom Java runtime framework that can't be incorporated with standard JVMs. Along
these lines, an imperative exploration issue is the manner by which to get great
correspondence execution for Java without turning to techniques that surrender the
advantages of its virtual machine approach.
1.2.1 PROJECTS DONE WITH JAVA
Java’s open source ecosystem is strong and healthy, one of the primary reasons for our
creation of OSCON Java. Over the last decade, several projects have traveled beyond
mere adoption and had effects dominating the Java world, into software development in
general, and some even further into the daily lives of users (http://radar.
oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.1 JUnit
Ported to Java by Kent Beck and Erich Gamma from Beck’s work in unit testing in
Smalltalk, JUnit has been largely responsible for popularizing test-driven development
over the last decade. Many implementations have been created, in .NET, C, Python, Perl
and just about every language in popular use (http://radar.oreilly .com/2011/07/7-
java-projects.html, April 2016).
1.2.1.2 Eclipse
As Java and its APIs matured in the early 2000s, the Eclipse IDE provided a way for
programmers to be productive and negotiate the growing Java ecosystem. Eclipse was
also the first major project to use the SWT UI toolkit, providing important competition
to Sun’s Swing and showing that Java programs can provide a rich native interface.
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Eclipse has evolved toward a goal of being a universal IDE, and it now provides a rich
foundation for platform vendors to integrate with (http://radar.oreilly.com/2011/07/7
-java-projects.html, April 2016).
1.2.1.3 Spring
The Spring Framework has played an important role in enabling Java developers to be
productive, managing a balance between simplicity and features. Spring gives Java
developers a set of services providing commonly used application functionality such as
data access and transaction management. As a competitor to Sun’s Enterprise Java
Beans system, Spring enabled an alternative and simpler path for Java applications, as
well as ensuring a healthy competition of ideas in the way Java applications are
constructed (http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.4 Solr
The Solr server, and the Lucene search engine it encapsulates, has been for many years
a simple and practical solution to providing search capabilities to web and enterprise
applications. Solr’s genius is in providing HTTP access to the powerful and fast Lucene
search library, enabling it to become a part of any system, regardless of whether it is
implemented in Java or not. More than any other project, Solr has ensured that good
search is a checkbox item for modern web applications (http://radar.
oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.5 Hudson and Jenkins
Originally developed as Hudson, and now also as Jenkins, this continuous integration
tool is a key part of a Java development setup. Jenkins provides automated build and
testing of a software project, continuing in the footsteps of JUnit in enabling agile
development on the Java platform. While both Hudson and Jenkins persist for now as
forks of each other, it doesn’t detract from the work of Kohsuke Kawaguchi in creating a
world-class continuous integration platform and so enhancing the quality of much Java
development. (http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016)
1.2.1.6 Hadoop
foundation for platform vendors to integrate with (http://radar.oreilly.com/2011/07/7
-java-projects.html, April 2016).
1.2.1.3 Spring
The Spring Framework has played an important role in enabling Java developers to be
productive, managing a balance between simplicity and features. Spring gives Java
developers a set of services providing commonly used application functionality such as
data access and transaction management. As a competitor to Sun’s Enterprise Java
Beans system, Spring enabled an alternative and simpler path for Java applications, as
well as ensuring a healthy competition of ideas in the way Java applications are
constructed (http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.4 Solr
The Solr server, and the Lucene search engine it encapsulates, has been for many years
a simple and practical solution to providing search capabilities to web and enterprise
applications. Solr’s genius is in providing HTTP access to the powerful and fast Lucene
search library, enabling it to become a part of any system, regardless of whether it is
implemented in Java or not. More than any other project, Solr has ensured that good
search is a checkbox item for modern web applications (http://radar.
oreilly.com/2011/07/7-java-projects.html, April 2016).
1.2.1.5 Hudson and Jenkins
Originally developed as Hudson, and now also as Jenkins, this continuous integration
tool is a key part of a Java development setup. Jenkins provides automated build and
testing of a software project, continuing in the footsteps of JUnit in enabling agile
development on the Java platform. While both Hudson and Jenkins persist for now as
forks of each other, it doesn’t detract from the work of Kohsuke Kawaguchi in creating a
world-class continuous integration platform and so enhancing the quality of much Java
development. (http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016)
1.2.1.6 Hadoop
This Java implementation of the famous MapReduce model is the powerhouse that has
enabled most “big data” systems. By lowering the cost of extracting value from large
data sets, Hadoop has made practical the personalization and advertising businesses of
Facebook and Yahoo, and many other companies. In the same way that Linux enabled
large websites to be built on cheap hardware, Hadoop enables large-scale distributed
computing by handling failure at the software level. Both Hadoop and the above-
mentioned Lucene are the product of the work of Doug Cutting
(http://radar.oreilly.com /2011/07/7-java-projects.html, April 2016).
1.2.1.7 Android
Controversy is never that far from Java, whether the custodian be Sun or Oracle.
Google’s choice to use Java as the programming language for its massively
popular Android mobile operating system has led to a renewed interest in the language
from whole new communities of software developers. Android programs undergo a
further step to convert JVM bytecode to Dalvik bytecode — Dalvik being a virtual
machine optimized for mobile devices. Google has been able to leverage Eclipse to
provide software developers with a mature development environment for creating
Android applications (http://radar.oreilly.com/2011/07/7-java-projects.html, April
2016). Oracle and Google are currently engaged in a lawsuit over a claim that Android
infringes on multiple patents held by Oracle. The results of that suit notwithstanding,
Android has done much to recruit developers and perpetuate the use of Java in client-
side software development.
SECTION 2
enabled most “big data” systems. By lowering the cost of extracting value from large
data sets, Hadoop has made practical the personalization and advertising businesses of
Facebook and Yahoo, and many other companies. In the same way that Linux enabled
large websites to be built on cheap hardware, Hadoop enables large-scale distributed
computing by handling failure at the software level. Both Hadoop and the above-
mentioned Lucene are the product of the work of Doug Cutting
(http://radar.oreilly.com /2011/07/7-java-projects.html, April 2016).
1.2.1.7 Android
Controversy is never that far from Java, whether the custodian be Sun or Oracle.
Google’s choice to use Java as the programming language for its massively
popular Android mobile operating system has led to a renewed interest in the language
from whole new communities of software developers. Android programs undergo a
further step to convert JVM bytecode to Dalvik bytecode — Dalvik being a virtual
machine optimized for mobile devices. Google has been able to leverage Eclipse to
provide software developers with a mature development environment for creating
Android applications (http://radar.oreilly.com/2011/07/7-java-projects.html, April
2016). Oracle and Google are currently engaged in a lawsuit over a claim that Android
infringes on multiple patents held by Oracle. The results of that suit notwithstanding,
Android has done much to recruit developers and perpetuate the use of Java in client-
side software development.
SECTION 2
2.1 REAL TIME PROBLEM AND SOLUTION WITH JAVA
PROBLEM: A program that lets the user play Blackjack. The game will be a simplified
version of Blackjack as it is played in a casino. The computer will act as the dealer.
EXPLANATION: You should first compose a subroutine in which the customer plays one
redirection. The subroutine should give back a boolean quality to demonstrate whether
the customer wins or not. Return genuine if the customer wins, false if the merchant
wins. The framework needs an object of class Deck and two objects of sort Blackjack
Hand, one for the merchant and one for the customer. The general thing in Blackjack is
to get a hand of cards whose quality is as near 21 as could be normal considering the
present situation, without going over. The redirection goes like this:
Initial, two cards are managed into every player's hand. If the merchant's hand has an
estimation of 21 right now, then the merchant wins. Something else, if the customer has
21, then the customer wins. (This is known as a "Blackjack".) Note that the merchant
wins on a tie, so if both players have Blackjack, then the merchant wins.
Right away, if the amusement has not finished, the customer gets a chance to add a
couple cards to her hand. In this stage, the customer sees her own particular cards and
sees one of the merchant's two cards. (In a club, the merchant gives himself one card
face up and one card face down. All the customer's cards are managed face up.) The
customer settles on a decision whether to "Hit", which intends to add another card to
her hand, or to "Stand", which intends to stop taking cards
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-aaswer. html, April, 2016).
If the customer Hits, there is a plausibility that the customer will go more than 21. All
things considered, the preoccupation is over and the customer loses. If not, then the
method continues. The customer finds the opportunity to pick again whether to Hit or
Stand.
In case the customer Stands, the preoccupation will end, however first the merchant
gets a chance to draw cards. The merchant just takes after principles, with no decision.
The guideline is that the length of the estimation of the merchant's hand is not exactly
or equivalent to 16, the merchant Hits (that is, takes another card). The customer
PROBLEM: A program that lets the user play Blackjack. The game will be a simplified
version of Blackjack as it is played in a casino. The computer will act as the dealer.
EXPLANATION: You should first compose a subroutine in which the customer plays one
redirection. The subroutine should give back a boolean quality to demonstrate whether
the customer wins or not. Return genuine if the customer wins, false if the merchant
wins. The framework needs an object of class Deck and two objects of sort Blackjack
Hand, one for the merchant and one for the customer. The general thing in Blackjack is
to get a hand of cards whose quality is as near 21 as could be normal considering the
present situation, without going over. The redirection goes like this:
Initial, two cards are managed into every player's hand. If the merchant's hand has an
estimation of 21 right now, then the merchant wins. Something else, if the customer has
21, then the customer wins. (This is known as a "Blackjack".) Note that the merchant
wins on a tie, so if both players have Blackjack, then the merchant wins.
Right away, if the amusement has not finished, the customer gets a chance to add a
couple cards to her hand. In this stage, the customer sees her own particular cards and
sees one of the merchant's two cards. (In a club, the merchant gives himself one card
face up and one card face down. All the customer's cards are managed face up.) The
customer settles on a decision whether to "Hit", which intends to add another card to
her hand, or to "Stand", which intends to stop taking cards
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-aaswer. html, April, 2016).
If the customer Hits, there is a plausibility that the customer will go more than 21. All
things considered, the preoccupation is over and the customer loses. If not, then the
method continues. The customer finds the opportunity to pick again whether to Hit or
Stand.
In case the customer Stands, the preoccupation will end, however first the merchant
gets a chance to draw cards. The merchant just takes after principles, with no decision.
The guideline is that the length of the estimation of the merchant's hand is not exactly
or equivalent to 16, the merchant Hits (that is, takes another card). The customer
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
should see all the merchant's cards at this moment. In a matter of seconds, the champ
can be determined: If the merchant has gone more than 21, the customer wins.
Something else, if the merchant's aggregate is more vital than or equivalent to the
customer's aggregate, then the merchant wins. Something else, the customer wins
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html, April, 2016).
Two notes on programming: At any point in the subroutine, when you know who the
champ is, you can say "return genuine;" or "return false;" to end the subroutine and
come back to the primary framework. To abstain from having an abundance of variables
in your subroutine, remember that a capacity call, for example,
userHand.getBlackjackValue() can be used anyplace that a number could be used,
incorporating into a yield articulation or in the state of an if explanation
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html, April, 2016).
Compose a fundamental program that allows the customer to play a couple of
amusements of Blackjack. To make things fascinating, give the customer 100 dollars,
and let the customer make wagers on the amusement. In case the customer loses,
subtract the wager from the customer's cash. In case the customer wins, add a total
equivalent to the wager to the customer's cash. End the undertaking when the customer
needs to stop or when she comes up short on cash.
SOLUTION:
/*
This program lets the user play Blackjack. The computer
acts as the dealer. The user has a stake of $100, and
makes a bet on each game. The user can leave at any time,
or will be kicked out when he loses all the money.
House rules: The dealer hits on a total of 16 or less
and stands on a total of 17 or more. Dealer wins ties.
A new deck of cards is used for each game.
*/
public class Blackjack {
public static void main(String[] args) {
can be determined: If the merchant has gone more than 21, the customer wins.
Something else, if the merchant's aggregate is more vital than or equivalent to the
customer's aggregate, then the merchant wins. Something else, the customer wins
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html, April, 2016).
Two notes on programming: At any point in the subroutine, when you know who the
champ is, you can say "return genuine;" or "return false;" to end the subroutine and
come back to the primary framework. To abstain from having an abundance of variables
in your subroutine, remember that a capacity call, for example,
userHand.getBlackjackValue() can be used anyplace that a number could be used,
incorporating into a yield articulation or in the state of an if explanation
(http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html, April, 2016).
Compose a fundamental program that allows the customer to play a couple of
amusements of Blackjack. To make things fascinating, give the customer 100 dollars,
and let the customer make wagers on the amusement. In case the customer loses,
subtract the wager from the customer's cash. In case the customer wins, add a total
equivalent to the wager to the customer's cash. End the undertaking when the customer
needs to stop or when she comes up short on cash.
SOLUTION:
/*
This program lets the user play Blackjack. The computer
acts as the dealer. The user has a stake of $100, and
makes a bet on each game. The user can leave at any time,
or will be kicked out when he loses all the money.
House rules: The dealer hits on a total of 16 or less
and stands on a total of 17 or more. Dealer wins ties.
A new deck of cards is used for each game.
*/
public class Blackjack {
public static void main(String[] args) {
int money; // Amount of money the user has.
int bet; // Amount user bets on a game.
boolean userWins; // Did the user win the game?
TextIO.putln("Welcome to the game of blackjack.");
TextIO.putln();
money = 100; // User starts with $100.
while (true) {
TextIO.putln("You have " + money + " dollars.");
do {
TextIO.putln("How many dollars do you want to bet? (Enter 0 to end.)");
TextIO.put("? ");
bet = TextIO.getlnInt();
if (bet < 0 || bet > money)
TextIO.putln("Your answer must be between 0 and " + money + '.');
} while (bet < 0 || bet > money);
if (bet == 0)
break;
userWins = playBlackjack();
if (userWins)
money = money + bet;
else
money = money - bet;
TextIO.putln();
if (money == 0) {
TextIO.putln("Looks like you've are out of money!");
break;
}
}
TextIO.putln();
TextIO.putln("You leave with $" + money + '.');
int bet; // Amount user bets on a game.
boolean userWins; // Did the user win the game?
TextIO.putln("Welcome to the game of blackjack.");
TextIO.putln();
money = 100; // User starts with $100.
while (true) {
TextIO.putln("You have " + money + " dollars.");
do {
TextIO.putln("How many dollars do you want to bet? (Enter 0 to end.)");
TextIO.put("? ");
bet = TextIO.getlnInt();
if (bet < 0 || bet > money)
TextIO.putln("Your answer must be between 0 and " + money + '.');
} while (bet < 0 || bet > money);
if (bet == 0)
break;
userWins = playBlackjack();
if (userWins)
money = money + bet;
else
money = money - bet;
TextIO.putln();
if (money == 0) {
TextIO.putln("Looks like you've are out of money!");
break;
}
}
TextIO.putln();
TextIO.putln("You leave with $" + money + '.');
} // end main()
static boolean playBlackjack() {
// Let the user play one game of Blackjack.
// Return true if the user wins, false if the user loses.
Deck deck; // A deck of cards. A new deck for each game.
BlackjackHand dealerHand; // The dealer's hand.
BlackjackHand userHand; // The user's hand.
deck = new Deck();
dealerHand = new BlackjackHand();
userHand = new BlackjackHand();
/* Shuffle the deck, then deal two cards to each player. */
deck.shuffle();
dealerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
userHand.addCard( deck.dealCard() );
userHand.addCard( deck.dealCard() );
TextIO.putln();
TextIO.putln();
/* Check if one of the players has Blackjack (two cards totaling to 21).
The player with Blackjack wins the game. Dealer wins ties.
*/
if (dealerHand.getBlackjackValue() == 21) {
TextIO.putln("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
TextIO.putln("User has the " + userHand.getCard(0)
+ " and the " + userHand.getCard(1) + ".");
static boolean playBlackjack() {
// Let the user play one game of Blackjack.
// Return true if the user wins, false if the user loses.
Deck deck; // A deck of cards. A new deck for each game.
BlackjackHand dealerHand; // The dealer's hand.
BlackjackHand userHand; // The user's hand.
deck = new Deck();
dealerHand = new BlackjackHand();
userHand = new BlackjackHand();
/* Shuffle the deck, then deal two cards to each player. */
deck.shuffle();
dealerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
userHand.addCard( deck.dealCard() );
userHand.addCard( deck.dealCard() );
TextIO.putln();
TextIO.putln();
/* Check if one of the players has Blackjack (two cards totaling to 21).
The player with Blackjack wins the game. Dealer wins ties.
*/
if (dealerHand.getBlackjackValue() == 21) {
TextIO.putln("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
TextIO.putln("User has the " + userHand.getCard(0)
+ " and the " + userHand.getCard(1) + ".");
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
TextIO.putln();
TextIO.putln("Dealer has Blackjack. Dealer wins.");
return false;
}
if (userHand.getBlackjackValue() == 21) {
TextIO.putln("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
TextIO.putln("User has the " + userHand.getCard(0)
+ " and the " + userHand.getCard(1) + ".");
TextIO.putln();
TextIO.putln("You have Blackjack. You win.");
return true;
}
/* If neither player has Blackjack, play the game. First the user
gets a chance to draw cards (i.e., to "Hit"). The while loop ends
when the user chooses to "Stand". If the user goes over 21,
the user loses immediately.
*/
while (true) {
/* Display user's cards, and let user decide to Hit or Stand. */
TextIO.putln();
TextIO.putln();
TextIO.putln("Your cards are:");
for ( int i = 0; i < userHand.getCardCount(); i++ )
TextIO.putln(" " + userHand.getCard(i));
TextIO.putln("Your total is " + userHand.getBlackjackValue());
TextIO.putln();
TextIO.putln("Dealer is showing the " + dealerHand.getCard(0));
TextIO.putln();
TextIO.putln("Dealer has Blackjack. Dealer wins.");
return false;
}
if (userHand.getBlackjackValue() == 21) {
TextIO.putln("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
TextIO.putln("User has the " + userHand.getCard(0)
+ " and the " + userHand.getCard(1) + ".");
TextIO.putln();
TextIO.putln("You have Blackjack. You win.");
return true;
}
/* If neither player has Blackjack, play the game. First the user
gets a chance to draw cards (i.e., to "Hit"). The while loop ends
when the user chooses to "Stand". If the user goes over 21,
the user loses immediately.
*/
while (true) {
/* Display user's cards, and let user decide to Hit or Stand. */
TextIO.putln();
TextIO.putln();
TextIO.putln("Your cards are:");
for ( int i = 0; i < userHand.getCardCount(); i++ )
TextIO.putln(" " + userHand.getCard(i));
TextIO.putln("Your total is " + userHand.getBlackjackValue());
TextIO.putln();
TextIO.putln("Dealer is showing the " + dealerHand.getCard(0));
TextIO.putln();
TextIO.put("Hit (H) or Stand (S)? ");
char userAction; // User's response, 'H' or 'S'.
do {
userAction = Character.toUpperCase( TextIO.getlnChar() );
if (userAction != 'H' && userAction != 'S')
TextIO.put("Please respond H or S: ");
} while (userAction != 'H' && userAction != 'S');
/* If the user Hits, the user gets a card. If the user Stands,
the loop ends (and it's the dealer's turn to draw cards).
*/
if ( userAction == 'S' ) {
// Loop ends; user is done taking cards.
break;
}
else { // userAction is 'H'. Give the user a card.
// If the user goes over 21, the user loses.
Card newCard = deck.dealCard();
userHand.addCard(newCard);
TextIO.putln();
TextIO.putln("User hits.");
TextIO.putln("Your card is the " + newCard);
TextIO.putln("Your total is now " + userHand.getBlackjackValue());
if (userHand.getBlackjackValue() > 21) {
TextIO.putln();
TextIO.putln("You busted by going over 21. You lose.");
TextIO.putln("Dealer's other card was the "
+ dealerHand.getCard(1));
return false;
}
}
} // end while loop
char userAction; // User's response, 'H' or 'S'.
do {
userAction = Character.toUpperCase( TextIO.getlnChar() );
if (userAction != 'H' && userAction != 'S')
TextIO.put("Please respond H or S: ");
} while (userAction != 'H' && userAction != 'S');
/* If the user Hits, the user gets a card. If the user Stands,
the loop ends (and it's the dealer's turn to draw cards).
*/
if ( userAction == 'S' ) {
// Loop ends; user is done taking cards.
break;
}
else { // userAction is 'H'. Give the user a card.
// If the user goes over 21, the user loses.
Card newCard = deck.dealCard();
userHand.addCard(newCard);
TextIO.putln();
TextIO.putln("User hits.");
TextIO.putln("Your card is the " + newCard);
TextIO.putln("Your total is now " + userHand.getBlackjackValue());
if (userHand.getBlackjackValue() > 21) {
TextIO.putln();
TextIO.putln("You busted by going over 21. You lose.");
TextIO.putln("Dealer's other card was the "
+ dealerHand.getCard(1));
return false;
}
}
} // end while loop
/* If we get to this point, the user has Stood with 21 or less. Now, it's
the dealer's chance to draw. Dealer draws cards until the dealer's
total is > 16. If dealer goes over 21, the dealer loses.
*/
TextIO.putln();
TextIO.putln("User stands.");
TextIO.putln("Dealer's cards are");
TextIO.putln(" " + dealerHand.getCard(0));
TextIO.putln(" " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
TextIO.putln("Dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
TextIO.putln();
TextIO.putln("Dealer busted by going over 21. You win.");
return true;
}
}
TextIO.putln("Dealer's total is " + dealerHand.getBlackjackValue());
/* If we get to this point, both players have 21 or less. We
can determine the winner by comparing the values of their hands. */
TextIO.putln();
if (dealerHand.getBlackjackValue() == userHand.getBlackjackValue()) {
TextIO.putln("Dealer wins on a tie. You lose.");
return false;
}
else if (dealerHand.getBlackjackValue() > userHand.getBlackjackValue()) {
TextIO.putln("Dealer wins, " + dealerHand.getBlackjackValue()
+ " points to " + userHand.getBlackjackValue() + ".");
return false;
the dealer's chance to draw. Dealer draws cards until the dealer's
total is > 16. If dealer goes over 21, the dealer loses.
*/
TextIO.putln();
TextIO.putln("User stands.");
TextIO.putln("Dealer's cards are");
TextIO.putln(" " + dealerHand.getCard(0));
TextIO.putln(" " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
TextIO.putln("Dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
TextIO.putln();
TextIO.putln("Dealer busted by going over 21. You win.");
return true;
}
}
TextIO.putln("Dealer's total is " + dealerHand.getBlackjackValue());
/* If we get to this point, both players have 21 or less. We
can determine the winner by comparing the values of their hands. */
TextIO.putln();
if (dealerHand.getBlackjackValue() == userHand.getBlackjackValue()) {
TextIO.putln("Dealer wins on a tie. You lose.");
return false;
}
else if (dealerHand.getBlackjackValue() > userHand.getBlackjackValue()) {
TextIO.putln("Dealer wins, " + dealerHand.getBlackjackValue()
+ " points to " + userHand.getBlackjackValue() + ".");
return false;
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
}
else {
TextIO.putln("You win, " + userHand.getBlackjackValue()
+ " points to " + dealerHand.getBlackjackValue() + ".");
return true;
}
} // end playBlackjack()
} // end class Blackjack
Code Source: http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html,
April, 2016
2.2 The Components, Data and File Structures Required to Implement a
Design
2.2.1 Logical or physical organisation and data independence
There is one critical qualification that must be made at the beginning when talking
about record structures. What's more, that is the contrast between the legitimate and
physical association of the information. In general a document structure will determine
the sensible structure of the information, that is the associations that will exist between
information things unreservedly of the course in which these associations may really be
acknowledged inside of any PC. It is this sensible point of view that we will concentrate
on. The physical association is a great deal more stressed with streamlining the
utilization of the capacity medium when a particular sensible structure is secured on, or
in it. Normally for each unit of physical store there will be various units of the consistent
structure (presumably records) to be secured in it. For instance, on the off chance that
we some way or another happened to store a tree structure on an attractive circle, the
physical association would be concerned with the best strategy for pressing the center
points of the tree on the plate given the entrance qualities of the plate
(http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
The work on information bases has been particularly stressed with an idea called
information autonomy. The point of this work is to enable activities to be composed
uninhibitedly of the legitimate structure of the information they would associate with.
else {
TextIO.putln("You win, " + userHand.getBlackjackValue()
+ " points to " + dealerHand.getBlackjackValue() + ".");
return true;
}
} // end playBlackjack()
} // end class Blackjack
Code Source: http://math.hws.edu/eck/cs124/javanotes4/c5/ex-5-5-answer.html,
April, 2016
2.2 The Components, Data and File Structures Required to Implement a
Design
2.2.1 Logical or physical organisation and data independence
There is one critical qualification that must be made at the beginning when talking
about record structures. What's more, that is the contrast between the legitimate and
physical association of the information. In general a document structure will determine
the sensible structure of the information, that is the associations that will exist between
information things unreservedly of the course in which these associations may really be
acknowledged inside of any PC. It is this sensible point of view that we will concentrate
on. The physical association is a great deal more stressed with streamlining the
utilization of the capacity medium when a particular sensible structure is secured on, or
in it. Normally for each unit of physical store there will be various units of the consistent
structure (presumably records) to be secured in it. For instance, on the off chance that
we some way or another happened to store a tree structure on an attractive circle, the
physical association would be concerned with the best strategy for pressing the center
points of the tree on the plate given the entrance qualities of the plate
(http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
The work on information bases has been particularly stressed with an idea called
information autonomy. The point of this work is to enable activities to be composed
uninhibitedly of the legitimate structure of the information they would associate with.
The flexibility takes the accompanying structure, should the document structure
overnight transformed from a turned around to a serial record the venture should stay
unaffected. This autonomy is accomplished by mediating an information model between
the customer and the information base. The customer sees the information display
instead of the information base, and every one of his ventures speak with the model.
The customer in this way has no enthusiasm for the structure of the document
(http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
2.2.2 A language for describing file structures
Like all subjects in software engineering the phrasing of document structures has
created willy nilly without much sympathy toward consistency, vagueness, or whether
it was conceivable to make the kind of qualifications that were vital. It was simply much
later that the prerequisite for an all around characterized, unambiguous dialect to
portray document structures got the chance to be clear. Specifically, there rose a need to
pass on considerations regarding record structures without getting obstructed by gear
contemplations (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
The framework is vital for the comprehension of any record structure. The phrasing
relies on upon that displayed by Hsiao and Harary (2013). Their wording has been
altered and extended by Severance. Jonkers(2010) has formalized an alternate
framework which gives an intriguing complexity to the one portrayed here.
2.2.3 Sequential files
A successive record is the most primitive of all document structures. It has no registry
and no connecting pointers. The records are all around composed in lexicographic
solicitation on the estimation of some key. At the end of the day, a particular quality is
picked whose value will choose the solicitation of the records. Now and again when the
property estimation is consistent for incalculable a second key is given a solicitation
when the main key fails to separate. The usage of this document structure requires the
utilization of a sorting routine (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html,
April 2016).
Its principle favorable circumstances are:
a. It is anything however hard to execute;
overnight transformed from a turned around to a serial record the venture should stay
unaffected. This autonomy is accomplished by mediating an information model between
the customer and the information base. The customer sees the information display
instead of the information base, and every one of his ventures speak with the model.
The customer in this way has no enthusiasm for the structure of the document
(http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
2.2.2 A language for describing file structures
Like all subjects in software engineering the phrasing of document structures has
created willy nilly without much sympathy toward consistency, vagueness, or whether
it was conceivable to make the kind of qualifications that were vital. It was simply much
later that the prerequisite for an all around characterized, unambiguous dialect to
portray document structures got the chance to be clear. Specifically, there rose a need to
pass on considerations regarding record structures without getting obstructed by gear
contemplations (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html, April 2016).
The framework is vital for the comprehension of any record structure. The phrasing
relies on upon that displayed by Hsiao and Harary (2013). Their wording has been
altered and extended by Severance. Jonkers(2010) has formalized an alternate
framework which gives an intriguing complexity to the one portrayed here.
2.2.3 Sequential files
A successive record is the most primitive of all document structures. It has no registry
and no connecting pointers. The records are all around composed in lexicographic
solicitation on the estimation of some key. At the end of the day, a particular quality is
picked whose value will choose the solicitation of the records. Now and again when the
property estimation is consistent for incalculable a second key is given a solicitation
when the main key fails to separate. The usage of this document structure requires the
utilization of a sorting routine (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html,
April 2016).
Its principle favorable circumstances are:
a. It is anything however hard to execute;
b. It gives brisk access to the following record utilizing lexicographic solicitation.
2.2.4 Trees
Disregarding the fact that PC researchers have embraced trees as record structures,
their properties were initially investigated by mathematicians. Honestly, a considerable
part of the Theory of Graphs is committed to the investigation of trees. Magnificent
books on the investigative parts of trees (and charts) have been composed by Berge
(2006), Harary et al., (2013) and Metal (2009). Harary's book additionally contains a
valuable glossary of ideas in chart hypothesis. Furthermore, Knuth (2012) talk about
points in diagram hypothesis with applications in data preparing.
There are various meanings of trees. I have picked an especially basic one from Berge.
In the event that we think about a diagram as an arrangement of centers (or centers or
vertices) and an arrangement of lines (or edges) such that every line interfaces
precisely two center points, then a tree is characterized to be a limited associated chart
without any cycles, and having no under two center points. To characterize a cycle we
first characterize a chain. We speak to the line uk joining two centers x and y by uk =
[x,y]. A chain is an arrangement of lines, in which every line uk has one center point
quite recently the same as the previous line uk-1, and the other vertex in the same
manner as the succeeding line uk+1. A sample of a chain is [a,x1], [x1,x2], [x2,x3], [x3,b].
A cycle is a limited chain which starts at a center and closures at the same center point
(i.e. in the illustration a = b). (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html,
April 2016).
3.3. Relationships between Objects to Implement Design Requirements
Because class diagrams are utilized for a variety of purposes - from understanding
prerequisites to describing your detailed configuration - you should apply an alternate
style in each circumstance. This area portrays style guidelines pertaining to various
sorts of class diagrams
(http://agilemodeling.com/style/classDiagram .htm#sthash.vjLK63Ih.dpuf, April 2016)
2.2.4 Trees
Disregarding the fact that PC researchers have embraced trees as record structures,
their properties were initially investigated by mathematicians. Honestly, a considerable
part of the Theory of Graphs is committed to the investigation of trees. Magnificent
books on the investigative parts of trees (and charts) have been composed by Berge
(2006), Harary et al., (2013) and Metal (2009). Harary's book additionally contains a
valuable glossary of ideas in chart hypothesis. Furthermore, Knuth (2012) talk about
points in diagram hypothesis with applications in data preparing.
There are various meanings of trees. I have picked an especially basic one from Berge.
In the event that we think about a diagram as an arrangement of centers (or centers or
vertices) and an arrangement of lines (or edges) such that every line interfaces
precisely two center points, then a tree is characterized to be a limited associated chart
without any cycles, and having no under two center points. To characterize a cycle we
first characterize a chain. We speak to the line uk joining two centers x and y by uk =
[x,y]. A chain is an arrangement of lines, in which every line uk has one center point
quite recently the same as the previous line uk-1, and the other vertex in the same
manner as the succeeding line uk+1. A sample of a chain is [a,x1], [x1,x2], [x2,x3], [x3,b].
A cycle is a limited chain which starts at a center and closures at the same center point
(i.e. in the illustration a = b). (http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html,
April 2016).
3.3. Relationships between Objects to Implement Design Requirements
Because class diagrams are utilized for a variety of purposes - from understanding
prerequisites to describing your detailed configuration - you should apply an alternate
style in each circumstance. This area portrays style guidelines pertaining to various
sorts of class diagrams
(http://agilemodeling.com/style/classDiagram .htm#sthash.vjLK63Ih.dpuf, April 2016)
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Fig 1. Analysis and design versions of a class
Source: http://agilemodeling.com/style/classDiagram.htm, April 2016
PATIENT-PATIENT RECORD
public class Patient {
private String name;
private String socialsecuritnumber;
private PatientRecords pr;
public Patient(String name, String s) {
this.name = name;
this.socialsecuritnumber = s;
pr = null;
}
public void setPatientRecords(PatientRecords r) {
this.pr = r;
}
}
public class PatientRecords {
private String doctor;
private Patient p;
public PatientRecords(String doctor) {
Source: http://agilemodeling.com/style/classDiagram.htm, April 2016
PATIENT-PATIENT RECORD
public class Patient {
private String name;
private String socialsecuritnumber;
private PatientRecords pr;
public Patient(String name, String s) {
this.name = name;
this.socialsecuritnumber = s;
pr = null;
}
public void setPatientRecords(PatientRecords r) {
this.pr = r;
}
}
public class PatientRecords {
private String doctor;
private Patient p;
public PatientRecords(String doctor) {
this.doctor = doctor;
p = null;
}
public void setPatient(Patient p) {
this.p = p;
}
Source:http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-relationships.pdf,
April 2016
3.4 Implementing object behaviours using control structures to meet the
design algorithms
public class Main {
public static void main(String[] args) {
Patient a = new Patient("Joe", "123-45-6789");
PatientRecords b = new PatientRecords("dr. evans");
a.setPatientRecords(b); // patient has a link to its record
b.setPatient(a); // record has a link to its patient
}
}
Source: http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-relationships.pdf
3.5 Implementation of opportunities for error handling and reporting
Special case is a blunder occasion that can happen amid the execution of an undertaking
and upsets its ordinary stream. Java gives a hearty and thing arranged approach to
handle special case situations, known as Java Exemption Handling. Java being a thing
situated programming dialect, at whatever point a screw up happens while executing an
announcement, makes an exception article and after that the typical stream of the
undertaking stops and JRE tries to discover some individual that can deal with the
raised special case. The special case object contains a great deal of investigating data, for
example, method chain of command, line number where the exception happened, kind
of special case and so forward. At the point when the exclusion happens in a method,
the technique of making the special case dissent and giving it over to runtime
p = null;
}
public void setPatient(Patient p) {
this.p = p;
}
Source:http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-relationships.pdf,
April 2016
3.4 Implementing object behaviours using control structures to meet the
design algorithms
public class Main {
public static void main(String[] args) {
Patient a = new Patient("Joe", "123-45-6789");
PatientRecords b = new PatientRecords("dr. evans");
a.setPatientRecords(b); // patient has a link to its record
b.setPatient(a); // record has a link to its patient
}
}
Source: http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-relationships.pdf
3.5 Implementation of opportunities for error handling and reporting
Special case is a blunder occasion that can happen amid the execution of an undertaking
and upsets its ordinary stream. Java gives a hearty and thing arranged approach to
handle special case situations, known as Java Exemption Handling. Java being a thing
situated programming dialect, at whatever point a screw up happens while executing an
announcement, makes an exception article and after that the typical stream of the
undertaking stops and JRE tries to discover some individual that can deal with the
raised special case. The special case object contains a great deal of investigating data, for
example, method chain of command, line number where the exception happened, kind
of special case and so forward. At the point when the exclusion happens in a method,
the technique of making the special case dissent and giving it over to runtime
environment is called "tossing the exception"
(https://www.javacodegeeks.com/2013/07/java-special case taking care of -
instructional exercise - with-cases and-best-practices.html, April 2016).
Once runtime gets the special case object, it tries to discover the handler for the
exclusion. Exception Handler is the square of code that can prepare the special case
object. The rationale to discover the exclusion handler is straightforward – beginning
the inquiry in the strategy where botch happened, if no appropriate handler discovered,
then move to the visitor procedure and so on. So if systems call stack is A->B->C and
special case is raised in strategy C, then the mission for fitting handler will move from C-
>B->A. In case suitable special case handler is discovered, exception article is gone to
the handler to process it. The handler is said to be "getting the special case". If there are
no suitable exclusion handler discovered then program closes printing data about the
exception(https://www.javacodegeeks.com/2013/07/java-special case taking care of -
instructional exercise - with-illustrations and-best-practices.html, April 2016).
3.5.1 Exception Handling Keywords
Java provides specific keywords for exception handling purposes, we will look after
them first and then we will write a simple program showing how to use them for
exception handling (https://www.javacodegeeks.com/2013/07/java-exception-
handling -tutorial -with-examples-and-best-practices.html, April 2016).
Throw: We know that if any exception occurs, an exception object is getting created and
then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication program
we should throw exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it (https://www.javacodegeeks.com
/2013/07/java-exception-handling -tutorial -with-examples-and-best-practices. html,
April 2016).
Throws: When we are throwing any exception in a method and not handling it, then we
need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle these
exceptions or propagate it to it’s caller method using throws keyword. We can provide
(https://www.javacodegeeks.com/2013/07/java-special case taking care of -
instructional exercise - with-cases and-best-practices.html, April 2016).
Once runtime gets the special case object, it tries to discover the handler for the
exclusion. Exception Handler is the square of code that can prepare the special case
object. The rationale to discover the exclusion handler is straightforward – beginning
the inquiry in the strategy where botch happened, if no appropriate handler discovered,
then move to the visitor procedure and so on. So if systems call stack is A->B->C and
special case is raised in strategy C, then the mission for fitting handler will move from C-
>B->A. In case suitable special case handler is discovered, exception article is gone to
the handler to process it. The handler is said to be "getting the special case". If there are
no suitable exclusion handler discovered then program closes printing data about the
exception(https://www.javacodegeeks.com/2013/07/java-special case taking care of -
instructional exercise - with-illustrations and-best-practices.html, April 2016).
3.5.1 Exception Handling Keywords
Java provides specific keywords for exception handling purposes, we will look after
them first and then we will write a simple program showing how to use them for
exception handling (https://www.javacodegeeks.com/2013/07/java-exception-
handling -tutorial -with-examples-and-best-practices.html, April 2016).
Throw: We know that if any exception occurs, an exception object is getting created and
then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication program
we should throw exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it (https://www.javacodegeeks.com
/2013/07/java-exception-handling -tutorial -with-examples-and-best-practices. html,
April 2016).
Throws: When we are throwing any exception in a method and not handling it, then we
need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle these
exceptions or propagate it to it’s caller method using throws keyword. We can provide
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
multiple exceptions in the throws clause and it can be used with main() method also
(https://www.javacodegeeks.com /2013/07/java-exception-handling -tutorial -with-
examples-and-best-practices. html, April 2016).
Try-catch: We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception
(https://www.javacodegeeks.com /2013/07/java-exception-handling -tutorial -with-
examples-and-best-practices. html, April 2016).
Finally: finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will
not get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not (https://www.javacodegeeks.com /2013/07/java-exception-
handling -tutorial -with-examples-and-best-practices. html, April 2016).
CODE
package com.journaldev.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionHandling {
public static void main(String[] args) throws FileNotFoundException, IOException {
try{
testException(-5);
testException(-10);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
(https://www.javacodegeeks.com /2013/07/java-exception-handling -tutorial -with-
examples-and-best-practices. html, April 2016).
Try-catch: We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception
(https://www.javacodegeeks.com /2013/07/java-exception-handling -tutorial -with-
examples-and-best-practices. html, April 2016).
Finally: finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will
not get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not (https://www.javacodegeeks.com /2013/07/java-exception-
handling -tutorial -with-examples-and-best-practices. html, April 2016).
CODE
package com.journaldev.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionHandling {
public static void main(String[] args) throws FileNotFoundException, IOException {
try{
testException(-5);
testException(-10);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
System.out.println("Releasing resources");
}
testException(15);
}
public static void testException(int i) throws FileNotFoundException, IOException{
if(i < 0){
FileNotFoundException myException = new FileNotFoundException("Negative Integer
"+i);
throw myException;
}else if(i > 10){
throw new IOException("Only supported for index 0 to 10");
}
}
}
Source: (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016).
Output of above program
view sourceprint?
java.io.FileNotFoundException: Negative Integer -5
at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10)
Releasing resources
Exception in thread "main" java.io.IOException: Only supported for index 0 to 10
at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19)
}
testException(15);
}
public static void testException(int i) throws FileNotFoundException, IOException{
if(i < 0){
FileNotFoundException myException = new FileNotFoundException("Negative Integer
"+i);
throw myException;
}else if(i > 10){
throw new IOException("Only supported for index 0 to 10");
}
}
}
Source: (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016).
Output of above program
view sourceprint?
java.io.FileNotFoundException: Negative Integer -5
at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10)
Releasing resources
Exception in thread "main" java.io.IOException: Only supported for index 0 to 10
at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19)
The testException() method is throwing exception using throw keyword and method
signature uses throws keyword to let caller know the type of exceptions it might throw.
In main() method, the try-catch handling exception block in main() method was used
and when I am not handling it, I am propagating it to runtime with throws clause in
main method. Notice that testException(-10) never gets executed because of exception
and then execution of finally block after try-catch block is executed. The
printStackTrace() is one of the useful method in Exception class and used for debugging
purpose (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016).
signature uses throws keyword to let caller know the type of exceptions it might throw.
In main() method, the try-catch handling exception block in main() method was used
and when I am not handling it, I am propagating it to runtime with throws clause in
main method. Notice that testException(-10) never gets executed because of exception
and then execution of finally block after try-catch block is executed. The
printStackTrace() is one of the useful method in Exception class and used for debugging
purpose (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016).
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
REFERENCES
1. (http://www.c4learn.com/java/java-characteristics-features/, April 2016).
2. (https://www.techopedia.com/definition/5442/java-runtime-environment-jre,
April 2016).
3. Rob V. van Nieuwpoort, Jason Maassen, 2013. Ibis: a Flexible and Efficient Java-
based Grid Programming Environment. De Boelelaan 1081a, 1081.
4. V. Getov, G. von Laszewski, M. Philippsen, and I. Foster. Multiparadigm
Communications in Java for Grid Computing. Comm. of the ACM, 44(10):118–125,
2001
5. A. D. Alexandrov, M. Ibel, K. E. Schauser, and C. J. Scheiman. SuperWeb: Research
Issues in Java-Based Global Computing. Concurrency: Practice and Experience,
9(6):535–553, June 1997.
6. J.M. Bull, L.A. Smith, L. Pottage, and R. Freeman. Benchmarking Java against C and
Fortran for Scientific Applications. In ACM 2001 Java Grande/ISCOPE Conf., pages
97–105, 2001.
7. F. Breg. Java for High Performance Computing. PhD thesis, University of Leiden,
November 2001.
8. C.A. Thekkath and H.M. Levy. Limits to Low-Latency Communication on High-
Speed Networks. ACM Trans. on Computer Systems, 11(2):179–203, May 2009.
9. J. Maassen, Rob V. van Nieuwpoort, R. Veldema, H.E. Bal, T. Kielmann, C. Jacobs,
and R. Hofman. Efficient Java RMI for Parallel Programming. ACM Trans. on
Programming Languages and Systems, 23(6):747–775, 2001.
10.Y. Daniel Liang, 2012. Supplement for Introduction to Java Programming.
11. http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016.
12. JONKERS, H. L., 2010 'A straightforward and flexible design method for complex
data base management systems', Information Storage and Retrieval, 9, 401-415 .
13. HSIAO, D. and HARARY, F., 2013 'A formal system for information retrieval from
files', Communications of the ACM, 13, 67-7 3.
14. BERGE, C., 2006 The Theory of Graphs and its Applications, Methuen, London.
15. ORE, 0., 2009. Graphs and their Uses, Random House, New York.
16. KNUTH, D. E., 2013. The Art of Computer Programming, Vol. 1, Fundamental
Algorithms, Addison-Wesley, Reading, Massachusetts.
1. (http://www.c4learn.com/java/java-characteristics-features/, April 2016).
2. (https://www.techopedia.com/definition/5442/java-runtime-environment-jre,
April 2016).
3. Rob V. van Nieuwpoort, Jason Maassen, 2013. Ibis: a Flexible and Efficient Java-
based Grid Programming Environment. De Boelelaan 1081a, 1081.
4. V. Getov, G. von Laszewski, M. Philippsen, and I. Foster. Multiparadigm
Communications in Java for Grid Computing. Comm. of the ACM, 44(10):118–125,
2001
5. A. D. Alexandrov, M. Ibel, K. E. Schauser, and C. J. Scheiman. SuperWeb: Research
Issues in Java-Based Global Computing. Concurrency: Practice and Experience,
9(6):535–553, June 1997.
6. J.M. Bull, L.A. Smith, L. Pottage, and R. Freeman. Benchmarking Java against C and
Fortran for Scientific Applications. In ACM 2001 Java Grande/ISCOPE Conf., pages
97–105, 2001.
7. F. Breg. Java for High Performance Computing. PhD thesis, University of Leiden,
November 2001.
8. C.A. Thekkath and H.M. Levy. Limits to Low-Latency Communication on High-
Speed Networks. ACM Trans. on Computer Systems, 11(2):179–203, May 2009.
9. J. Maassen, Rob V. van Nieuwpoort, R. Veldema, H.E. Bal, T. Kielmann, C. Jacobs,
and R. Hofman. Efficient Java RMI for Parallel Programming. ACM Trans. on
Programming Languages and Systems, 23(6):747–775, 2001.
10.Y. Daniel Liang, 2012. Supplement for Introduction to Java Programming.
11. http://radar.oreilly.com/2011/07/7-java-projects.html, April 2016.
12. JONKERS, H. L., 2010 'A straightforward and flexible design method for complex
data base management systems', Information Storage and Retrieval, 9, 401-415 .
13. HSIAO, D. and HARARY, F., 2013 'A formal system for information retrieval from
files', Communications of the ACM, 13, 67-7 3.
14. BERGE, C., 2006 The Theory of Graphs and its Applications, Methuen, London.
15. ORE, 0., 2009. Graphs and their Uses, Random House, New York.
16. KNUTH, D. E., 2013. The Art of Computer Programming, Vol. 1, Fundamental
Algorithms, Addison-Wesley, Reading, Massachusetts.
17. http://www.dcs.gla.ac.uk/Keith/Chapter.4/Ch.4.html.
18. (http://agilemodeling.com/style/classDiagram.htm#sthash.vjLK63Ih.dpuf, April
2016).
19. http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-
relationships.pdf, April 2016
20. (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016)
18. (http://agilemodeling.com/style/classDiagram.htm#sthash.vjLK63Ih.dpuf, April
2016).
19. http://web.eecs.umich.edu/~aprakash/eecs282/lectures/07-lecture-
relationships.pdf, April 2016
20. (https://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial -
with-examples-and-best-practices.html, April 2016)
1 out of 24
Your All-in-One AI-Powered Toolkit for Academic Success.
+13062052269
info@desklib.com
Available 24*7 on WhatsApp / Email
Unlock your academic potential
© 2024 | Zucol Services PVT LTD | All rights reserved.