Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What is the chief advantage of the Java Virtual Machine? What is a class? How ar

ID: 3790616 • Letter: W

Question

What is the chief advantage of the Java Virtual Machine? What is a class? How are classes and objects relate? What is the difference between a primitive variable and a reference variable? What's the difference between Systen.out.print () and System.out.println()? Consider the following code. What will it output? int a = 5, b = 2; Systen.out.println (a/b); Systen.out.println((double)(a/b)); Systen.out.println (((double)a)/b); Consider the code in the previous question. Why does it give the output it does? What is the difference between a public and private method? Consider the following UML class diagram. Convert it into an equivalent Java class. (Do not worry about inclusions. You may omit function bodies, or leave them blank.) Why might we want to provide multiple construction? What is this? Why might we want to use it? What purpose to get () and set() methods serve? Why might we prefer them to making data member public? What does a toString() method do? What does the following code do? Why? int stop = 1; if(stop ==0); {System.out.println("This should never print!"); Generally speaking, when should we use for loops? What about while loops? What is the practical difference between a while loop and a do-while loop?

Explanation / Answer

Hi,
Please find the answers for the above questions:
  
I.Java virtual machine (JVM):

The Java Virtual Machine (JVM) is an environment that executes Java programs. Java programs are compiled into an intermediate language called bytecode, which is what the JVM executes. Any program compiled into bytecode can be executed on any platform that has a JVM installed on it.This makes Java software compatible with many different computing platforms.

Java virtual machine has been implemented for a given platform, any Java program (which, after compilation, is called bytecode) can run on that platform. A Java virtual machine can either interpret the bytecode one instruction at a time (mapping it to a real processor instruction) or the bytecode can be compiled further for the real processor using what is called a just-in-time compiler.

Chief advantages of JVM:

Platform Independence:
Java bytecode can be written once and then run on multiple platforms. Java bytecode does not need to be ported to a specific hardware environment because it runs in the Java Virtual Machine. Any application compiled into Java bytecode can be run on any computing platform that has a Java Virtual Machine.

Security:
Java was written with security in mind. The Java Virtual Machine has built-in security features that allow programmers to write highly secure Java programs. It also prevents malicious software from compromising the Operating System (OS) because it keeps Java applications from interacting with Operating System resources.

Performance:
Java programs that run on a Java Virtual Machine tend to perform slower than equivalent programs written in C++.
The system neutrality of bytecode acts as a disadvantage where performance is concerned. This is because code optimization relies heavily on system-specific features. Since Java bytecode is system-neutral, it cannot be optimized for a specific hardware set.

Correctness:
A program that performs, as expected, is said to be correct. Since a Java program relies on the Java Virtual Machine to execute it, the JVM must be free of errors for the program to operate correctly. This reliance on the Java Virtual Machine introduces a possible point of failure for the program. Luckily, the Java Virtual Machine software is produced with very high standards, and therefore it isn't likely to ship with any errors.
Regardless, a failure in the Java Virtual Machine is a possibility that should be considered.

II.Class:
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.

A class is a template for manufacturing objects. You declare a class by specifying the class keyword followed by a non-reserved identifier that names it. A pair of matching open and close brace characters ({ and }) follow and delimit the class's body.

For example:
public class Cube {

   int length;
   int breadth;
   int height;
   public int getVolume() {
       return (length * breadth * height);
   }
} is a class which has got methods,data members,access modifier etc.

III.Relation between a class and an object:

The terms ‘class’ and ‘object’ are definitely related to one another, but each term holds its own distinct meaning.
The term ‘class’ refers to the actual written piece of code which is used to define the behavior of any given class.
So, a class is a static piece of code that consists of attributes which don’t change during the execution of a program – like the method definitions within a class.

An object is an instance of a class:

The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. While objects are ‘living’ their properties may also be changed signficantly.

Objects have a lifespan but classes do not:
Every object has a lifespan associated with it – a cat or zebra can not live forever. And, the properties of those objects can change as well while they ‘live’; if we have a ‘size’ variable defined in the class that would of course change as the cat object grows bigger.

Object versus class summary:
So, we can say that whereas a class is a general concept, an object is a very specific embodiment of that class, with a limited lifespan (like a lion, cat, or a zebra). Another way of thinking about the difference between a class and an object is that a class provides a template for something more specific that the programmer has to define, which he/she will do when creating an object of that class.

IV.Differences between primitive and reference variables in Java:

The main difference between primitive and reference type is that primitive type always has a value,
it can never be null but reference type can be null, which denotes the absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be 0, the default value of integral type in Java,
but a reference variable by default has a null value, which means no reference is assigned to it.

1.Default value and Null:
First difference between primitive and reference type is that former can never be null if no value is assigned they take their default value e.g. boolean variable will be initialized with false, byte, short, char,int and long will be initialized with zero, and float and double variables will be initialized with 0.0 value in Java.

2.The second difference is that primitive types stores values but reference type stores handle to object in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just a handle to object so that you can access them and make some change on object's state.

3.Assigning value using Assignment Variable (=):
When you assign a value to primitive data types, the primitive value is copied, but when you assign an object to reference type, the handle is copied. which means for reference type object is not copied only the handle is copied, i.e. the object is shared between two reference variable, known as aliases. An implication of this is modification done by one variable will affect to other.

Modification on one primitive variable doesn't affect the copy but it does in the case of the reference variable.
This sometimes creates confusion between programmer that Java is not passed by value for the reference type, which is not correct, Java is always passed by value, be it references or primitive variables.

4.When you compare primitive variables using equality (==) operator, their primitive values are compared but when you compare reference variable, their address is compared, which means two objects which are logically equal
e.g. two String object with same content may be seen as not equal.

Primitive variable are rightly compared using == operator, but when we compared two String object with same contents.You should always use equals() method to compare reference types.

5.Passing primitive and reference variable as method argument:
When you pass primitive values to a method the values are passed to the method, but when you pass reference variable, only the handle is copied. Which means for primitives, changing the formal parameter's value doesn't affect the actual parameter's value, while in case of reference types, changing the formal parameter's handle doesn't affect the actual parameter's address but changing the formal parameter's internal values does affect actual parameter's object, because they refer to the same object in memory.

6.Return value of a method:
When you return primitive types from a method then the primitive value is returned but when you return a reference type, again only handle to the is returned. This means a locally created object can survive even after method finishes its execution, if it was returned from a method or if it was stored in any member variable, why because object is always created in heap memory,while all primitive local variables are destroyed after method finishes execution.

7.Stack vs Heap:
Primitive variables are created in the stack while reference variable is created in heap space, which is managed by Garbage Collector.

8.Memory consumption or Size:
Primitive variables take less memory than reference variable because they don't need to maintain object metadata e.g. object header. An int primitive variable will take less memory than Integer object for storing same value e.g. 5.

Primitive variables are also copied when you assign them to another primitive variable and change on one variable will not affect other, but in the case of the reference variable, the handle is shared between multiple reference variable and any change into object's state will be visible to all reference variable.

Another key difference between primitive and reference variable to note is that former take less memory than later due to object metadata overhead e.g. memory require holding object header. An int primitive variable will always take less memory than Integer object for storing same value.

V.Difference between System.out.print() and System.out.println() in java:

The only difference between the print() and println() methods is that the println() statement positions the cursor onto the next line after printing the desired text while the print() method leaves the cursor on the same line. The difference is evident when we print text using more than a single statement. The following statements use the print() method.

System.out.print("Hello ");
System.out.print("World ");

The output of these statements would be:

Hello World

After printing the word 'Hello', the cursor remained on the same line. That is why 'World' was also displayed on the same line. If we use the println() statement, the output would be different.

System.out.println("Hello ");
System.out.println("World ");

The output would be

Hello
World

After printing the word 'Hello', the cursor moved to the next line. That is why the word 'World' was printed on a new line.

VI.Program and its output:

public class Demo {

   public static void main(String[] args) {

       int a = 5, b = 2;

       System.out.println(a / b);

       System.out.println((double) (a / b));

       System.out.println(((double) a) / b);
   }

}
Output:
2
2.0
2.5

VII.Reason for the output:
The first line gives the answer as 2 because it being primitive data type int the decimal gets truncated and does't give any precision.The second line gives the answer as 2.0 as we have typecasted the whole result to double.The third line gives the answer as 2.5 because we have typecasted only the numerator but not the total fraction.

VIII.Difference between public and private method in java:

The main difference between public and private method is in regardance with accessibility limits.When we declare a method as public,it can be accessed by any class globally.But whereas when we declare the method as private its visibility gets hindered as it wont be available to other classes.This is the only difference that we can find in these methods.

IX.I am not sure of this answer but still please check it.

public class SpaceShip {

   int x;
   int y;
   double heading;
  
   public String flyTo(Coordinate dest){
      
       return dest;
   }
  
   public SpaceShip target(SpaceShip t){
       return t;
      
   }
  
   public void fireLaser(){
      
   }
}

X.Purpose of a Constructor:

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object.

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() { gear = 1; cadence = 10; speed = 0; }

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

XI.Reason for multiple Constructors:

We create multiple constructors for a single class because we may need any one of these to fulfill our requirements.
A class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need. When a Java class contains multiple constructors, we say that the constructor is overloaded (comes in multiple versions). This is what constructor overloading means, that a Java class contains multiple constructors.

Here is a Java constructor overloading example:

public class MyClass {

private int number = 0;

public MyClass() {
}

public MyClass(int theNumber) {
this.number = theNumber;
}
}
The Java class above contains two constructors. The first constructor is a no-arg constructor, meaning it takes no parameters (no arguments). The second constructor takes an int parameter. Inside the constructor body the int parameter value is assigned to a field, meaning the value of the parameter is copied into the field. The field is thus initialized to the given parameter value.

XII.this keyword:

Keyword 'THIS' in Java is a reference variable that refers to the current object.

The various usage of keyword Java 'THIS' in Java is as per the below,

Example:
public class Employee {

private String firstName = null;
private String lastName = null;
private int birthYear = 0;


public Employee(String firstName, String lastName, int birthYear ) {

this.firstName = firstName;
this.lastName = lastName;
this.birthYear = birthYear;
}
  
}

XIII.Use of getter and setter methods in Java:

The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.

You can have only a getter. Then the property is read only. This should actually be the most common case.
You can have only a setter, making the property configurable, but communicating that nothing else should depend on its value

You can have a setter that sets multiple fields together because they belong together conceptually. This doesn't adhere to the JavaBeans specification, so don't do it if you depend on frameworks or tools that expect JavaBeans. Otherwise, it's a useful option.All of these things are implementation details that are hidden behind the simple "getter and setter" interface. That's what encapsulation is about.

By making the methods public, we are allowing user to change them according to their requirements.

XIV.Use of toString():
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

XV.Output:

public class Demo {

   public static void main(String[] args) {

       int stop = 1;
       if (stop == 0) {
           System.out.println("this should never print!");
       }
      
   }

}
prints nothing.gets terminated.

XVI.When to use for loop and while loop:
As far as I know we use for loop for checking conditions and implemnting them.It executes a block of statements repeatedly until the specified condition returns false.Whereas we use enhanced for loop for iterating collection classes like arraylists etc and print the elements of it to console.

While loop:
A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

Syntax
The syntax of a while loop is

while(Boolean_expression) {
// Statements
}

XVII.Difference between while loop and do-while loop in java:

A do-while loop is an exit controlled loop which means that it exits at the end. A while loop is an entry controlled loop which means that the condition is tested at the beginning and as a consequence, the code inside the loop might not even be executed.

do {
<block>
} while (<condition>);
is equivalent to:

<block>
while (<condition>) {
<block>
};

Hope this helped you.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote