Home » JAVA EXPERTS

JAVA EXPERTS

Short Questions on Defining Classes 2

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

1. Write a statement that creates and initializes a static variable named salesTax to 7.59.

2. Write a statement that creates a constant variable named TAX_RATE. The tax rate is 8.25%.

3. Write ONE Java statement that computes and displays the value of 25.

4. Write ONE Java statement that computes and displays a random number between 1 and 25.

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

5. Define boxing and unboxing.

6. Write a complete Java program that prompts the user for a number and prints back the integer as well as floating point values to the console.

7. Write a Java method that returns true if and only if a character is a digit or a letter. The method should display appropriate feedback to the console.

8. Explain in detail how main memory works.

9. How many bytes are contained within 16-bits, 32-bits, 64-bits?

10. When used with objects, what is the equality ( == ) operator really comparing?

11. Does an object created with a copy constructor reference the same memory location that the original object references? Explain.

12. Explain how a package is named in Java.

13. Create a Java class named Book with instance variables title, author, ISBN, and yearPublished. Include javadoc style comments to describe your interface. Such a class would normally have methods, but you are not required to supply any methods.

14. Add accessor and mutator methods to the Book class created in question #13.

15. Add a constructor and a copy constructor to the Book class created in question #13.

16. What is the purpose of Java’s wrapper classes?

17. Write a complete Java program that prompts the user for a phrase. The program converts and displays the phrase in uppercase letters.

18. Write a complete Java program using the StringTokenizer class that computes and displays the average of a list of grades read from the command line. Each grade should be entered on the same line separated by commas. Enter signifies the end of the input.

Practical Exercises on Defining Classes 2

Practical Exercise 1

Using your pizza code that you previously completed.  Create a PizzaOrder class that allows up to three pizzas to be saved in an order.  Each pizza saved should be a Pizza object (you have already written this).  In addition to appropriate instance variables and constructors, add the following methods:

· public void setNumPizzas(int numPizzas) – sets the number of pizzas in the order, numPizzas must be between 1 and 3.

· public void setPizza1(Pizza pizza1) – set pizza 1

· public void setPizza2(Pizza pizza2) – set pizza 2

· public void setPizza3(Pizza pizza3) – set pizza 3

· public double calcTotal() – returns the total cost of the order

Write a main method to test the class.  The setPizza2 and setPizza3 methods will be used only if there are two or three pizzas in the order, respectively.  Sample code illustrating the methods is shown below.  Note the first three lines are incomplete.  You must complete them on your own.

Pizza pizza1 = //code to create a large pizza, 1 cheese 1 ham

Pizza pizza2 = //code to create a medium pizza, 2 cheese, 2 pepperoni

PizzaOrder order = //Code to create an order

order.setNumPizzas(2); // 2 pizzas in the order

order.setPizza1(pizza1); //set first pizza

order.setPizza2(pizza2);//set second pizza

double total = order.calcTotal(); //should be 18+20 = 38

Practical Exercise 2

Extending your pizza program.  Extend your PizzaOrder class with the following methods and constructors

· public int getNumPizzas() – returns the number of pizzas in the order

· public Pizza getPizza1() – returns the first pizza int he order or null if not set

· public Pizza getPizza2() – returns the second pizza int he order or null if not set

· public Pizza getPizza3() – returns the third pizza int he order or null if not set

· A copy constructor that takes another pizzaOrder object and makes an independent copy of its pizzas.  This might be useful if using an old order as a starting point for a new order

Write a main method to test the new methods.  Changing the pizza in the new order should not change pizzas in the original order.  For example

Pizza pizza1 = //code to create a large pizza, 1 cheese 1 ham

Pizza pizza2 = //code to create a medium pizza, 2 cheese, 2 pepperoni

PizzaOrder order1 = //Code to create an order

order1.setNumPizzas(2); // 2 pizzas in the order

order1.setPizza1(pizza1); //set first pizza

order1.setPizza2(pizza2);//set second pizza

double total = order1.calcTotal(); //should be 18+20 = 38

PizzaOrder order2 = new PizzaOrder(order1) //copy constructor

orders2.getPizza1().setNumCheeseToppings(3); //change the toppings

double total = order2.calcTotal(); //should be 22+20 = 42

double origTotal = order1.calcTotal(); //should be 18+20 = 38

You will need to complete this code.

Short Questions on Arrays

1. Write a Java statement that declares and creates an array of Strings named Breeds. Your array  should be large enough to hold the names of 100 dog breeds.

2. Declare and create an integer array that will contain the numbers 1 through 100. Use a for loop to initialize the indexed variables.

3. What are three ways you can use the square brackets [ ] with an array name?

4. Given the following character array, char[] h = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’}; Write a Java statement that will create a new String object from the character array.

5. Write a Java method that takes an integer array as a formal parameter and returns the sum of integers contained within the array.

6. How are arrays tested to see if they contain the same contents?

7. Explain what the main methods array parameter, args, is used for.

8. Write a Java method as well as any facilitator methods needed to perform a sort on an array of whole numbers in descending order.

9. Discuss how you could represent a table of related records using a multidimensional array.

10. Declare and create a multidimensional array to hold the first and last names of 10 people.

11. Declare and create a 10 x 10 multidimensional array of doubles.

12. Initialize the array created in number 11 above to -1.0.

13. Write a complete Java console application that prompts the user for a series of quiz scores. The user should type -1 to signify that the input of quiz scores is complete. Your program should then average the scores and display the result back to the user.

14. Write Java statements to create a collection of integers, and to initialize each element of the collection to -1 using a for each statement.

15. Create a Java method that will take any number of double arguments and return the smallest of the group.

16. Write a Java statement that creates an enumerated type called months that contains the twelve different months in a year.

17. Write a Java statement that prints the month July to the console window from the enumerated list crated in question above.

What is the output of the following code?

int[] numbers = new int[10];

for(int i=0; i < numbers.length; ++i)

numbers[i] = i * 2;

for(int i=0; i < numbers.length; ++i)

        System.out.print(numbers[i] + ” “);

System.out.println();

What is the output of the following code?

int[] numbers = new int[10];

for(int i=0; i < numbers.length; ++i)

numbers[i] = i * 2;

for(int i=0; i < numbers.length; ++i)

System.out.print(numbers[i] / 2 + ” “);

System.out.println();

Practical Exercises on Arrays

Practical Exercise 1

Write a program that reads numbers from the keybord into an array of type int[].  You may assume that there will be 50 or fewer entries in the array.   Your program sallows any number of numbers to be entered, up to 50.  The output is to be a two-column list.  The first column is a list of distinct array elements; the second column is the count of the number of occurences of each element.  The list should be sorted on entries in the first column, largest to smallest.

 

For the array

-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12

the output should be

N     Count

4     2

3     3

2     2

1     4

-1    1

-12  4

Practical Exercise 2

Write a program that will allow two users to play tic tac toe.  The program should ask for moves alternatively from player X and player O.  The program displays the game positions as follows:

1 2 3

4 5 6

7 8 9

The player enter their moves by entering the position number they wish to mark.  After each move, the program displays the changed board.  A saple board configuration is

X X  O

4  5  6

O 8  9

Bonus: See if you can identify when someone wins.

Short Questions on Inheritance

(To Be Done Before the Lecture)

1. Explain what a call to super() does in a constructor of a derived class.

2. Define a base class to represent a Clock. Your class should have instance variables for hours, minutes and seconds.

3. Define a derived class to represent an alarm clock. Use the Clock class, created in number 2 above, as your base class.

4. Create a test driver to test the functionality of your AlarmClock class created in number 3 above.

5. Explain how parent and child classes are related to base and derived classes.

6. Explain the difference between method overloading and method overriding.

7. What is an “is a” relationship? How does it apply to the world of objects?

8. What is a “has a” relationship?

9. What is encapsulation?

10. Explain the modifiers public, protected and private.

11. What is package access?

12. Write Java statements that compares Objects, O1 and O2, using the getClass() method.

13. What does the instanceof operator do?

14. What are the different ways in which you can check the class of an Object?

15. Create a class to represent a Rectangle. Your class should contain instance variables for length and width, as well as member method to calculate the area and perimeter.

16. Create a test driver to test the functionality of your Rectangle class created in the previous question.

Practical Exercises on Inheritance

(To Be Done In Practical With Partner)

Practical Exercise 1

(make sure you complete this one it is needed for later questions)

The following is some code for a video game.  There is an Alien class to represent a monster and an AlienPack class that represents a band of aliens and how much damage they can inflict:

 

class Alien {
     public static final int SNAKE_ALIEN = 0;
     public static final int OGRE_ALIEN = 1;
     public static final int MARSHMALLOW_MAN_ALIEN = 2;
     public int type; // stores one of three types above
     public int health; //0 = dead 100 = full strength
     public String name;
     public Alien (int type, int health, String name) {
          this.type = type;
          this.health = health;
          this.name = name;
     }
}
class AlienPack {
     private Alien[] aliens;

     public AlienPack(int numAliens) {
          aliens = new Alien[numAliens];
     }
     public void addAlien(Alien newAlien, int index) {
          aliens[index] = newAlien;
     }
     public Alien[] getAliens() {
          return aliens;
     }
}
public int calculateDamage() {
     int damage = 0;
     for (int i=0; i  <aliens.length;i++) {
	if (aliens[i].type == Alien.SNAKE_ALIEN) {
		damage += 10;//ooh damage from snake is 10
	} else if (aliens[i].type = Alien.OGRE_ALIEN) {
		damage += 6;//Ogres do only 6 damage
	} else if (aliens[i].type == Alien.MARSHMALLOW_MAN_ALIEN) {
		damage += 1; //barely tickled
	}
}
return damage;
}
}

The code is not very object oriented and does not support information hiding in the Alien class.  Rewrite the code so that inheritance is used to represent the different types of aliens instead for the “type” parameter.  This should result in deletion of “type” parameter.  Also rewrite the Alien class to hide the instance variables and create a getDamage method for each derived class that returns the amount of damage the alien inflicts.  Finally, rewrite the calculateDamage method to use getDamage and write a main method that tests the code.

Practical Exercise 2

Give the definition of a class named Doctor whose objects are records for a clinic’s doctors.  This class will be a derived class of the class SalariedEmployee given in Display 7.5 from the textbook.  A doctor record has the doctors speciality (eg GP, Surgeon etc.. as a String) and office visit fee (as a double).  Be sure your class has a reasonable complement of constructors, accessor and mutator methods and suitably defined equals and toString methods.  Write a program to test all your methods.

Short Questions on Polymorphism

· Explain the difference between early and late binding.

· What is polymorphism and how does it relate to late binding?

· What are the advantages of polymorphism?

· Write a decision statement to determine if an object should be downcast.

· Describe the limitations of the copy constructor.

· What is an abstract method?

· What is wrong with the following method definition? public abstract void doSomething(int count)

· Why should the instanceOf operator be used in conjunction with downcasting?

· Draw an inheritance hierarchy to represent a shoe object. The base class should have derived classes of Dress Shoes, Tennis Shoes and Boots.

· Implement the base class in the shoe hierarchy in number 8 above.

· Derive a class named Dress Shoes from the base class created in number 9 above.

· Derive a class named Tennis Shoes from the base class created in number 9 above.

· Derive a class named Boots from the base class created in number 9 above.

· Override the clone method inherited in the Dress Shoes class created in number 10 above.

· Override the clone method inherited in the Tennis Shoes class created in number 11 above.

· Override the clone method inherited in the Boots class created in number 12 above.

Practical Exercises on Polymorphism

Practical Exercise 1

The goal for this exercise is to create a simple 2D predator-prey simulation.  In this simulation, the prey is ants, and the predators are doodlebugs.  These critters live in a world composed of a 20×20 grid of cells.  Only one critter may occupy a cell at a time.  The grid is enclosed, so a critter is not allowed to move off the edges of the grid.   Time is simulated in time steps.  Each critter performs some action every time step.

 

The ants behave according to the following rules:

· Move.  Every time step, randomly try to move in one of the directions.  If the selected direction is blocked the ant remains where it is.

· Breed.  If an ant survives for three time steps,  Then at the end of the third time step (ie after moving) the ant will breed.  This is simulated by creating a new ant in an adjacent cell that is empty.  If there is no empty cell available, no breeding occurs.   Once an offspring is produced no more breeding will occur for 3 time steps.

The doodlebugs behave according to the following model:

· Move.  If any adjacent cell has an ant the doodlebug and stay where it is.  Otherwise it will move like the ant.

· Breed.  After 8 moves it will spawn a baby in the same way as an ant.

· Starve.  If after three moves the doodlebug has not consumed an ant it will die and be removed from the board.

 

During one turn.  All the doodlebugs should be moved before the ants.

 

Write a program to implement this simulation and draw the world using ASCII characters of “o” for an ant and “X” for a doodlebug.  Create a class called Organism that encapsulates basic data common to both ants and doodlebugs.

 

This class should have an overridden method named move that is defined in the derived classes of Ant and Doodlebug.  You may need additional data structures to keep track of which critters have moved.

 

Initialise the world with 5 doodlebugs and 100 ants.  After each time step, prompt the user to press enter to move to the next time step.  You should see a cyclical pattern between the population of predators and prey, although random perturbations may lead to the elimination of one or both species

Place your order
(550 words)

Approximate price: $22

Calculate the price of your order

550 words
We'll send you the first draft for approval by September 11, 2018 at 10:52 AM
Total price:
$26
The price is based on these factors:
Academic level
Number of pages
Urgency
Basic features
  • Free title page and bibliography
  • Unlimited revisions
  • Plagiarism-free guarantee
  • Money-back guarantee
  • 24/7 support
On-demand options
  • Writer’s samples
  • Part-by-part delivery
  • Overnight delivery
  • Copies of used sources
  • Expert Proofreading
Paper format
  • 275 words per page
  • 12 pt Arial/Times New Roman
  • Double line spacing
  • Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Our guarantees

Delivering a high-quality product at a reasonable price is not enough anymore.
That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

Money-back guarantee

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read more

Zero-plagiarism guarantee

Each paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read more

Free-revision policy

Thanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read more

Privacy policy

Your email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read more

Fair-cooperation guarantee

By sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more
Live Chat+1 763 309 4299EmailWhatsApp

We Can Handle your Online Class from as low as$100 per week