Java: Classes and Objects UPDATED ACTUAL Exam Questions
and CORRECT Answers
Declaring a method - class Myclass{
static void sayHello(){
//sayHello is the method
System.out.println("Hello World!")
}
public static void main (String [ ] args) {
sayHello();
sayHello();
sayHello();
}
}
/* output:
Hello World!
Hello World!
Hello World!
*/
code reuse - You can write a method once, and use it multiple times, without having to rewrite
the code each time
Return value syntax - class MyClass {
, static int sum(int val1, int val2) {
return val1 + val2;
}
public static void main(String[ ] args) {
int x = sum(2, 5);
System.out.println(x);
}
}
//output 7
*Note: The return is saying to add val 1 and val 2 (parameters), as you can see in the next
function starting with public, there is a variable with x and the sum has (2,5) those two will be
added due to the method prior
Public - The class is accessible by any other class.
Package - A group of similar types of classes
Default - A variable or method declared with no access control modifier is available to any other
class in the same package.
Protected - Same as default, with the addition that subclasses can access protected methods and
variables of the superclass (learn more about subclasses and superclass later)
Private - Accessible only within the declared class itself
and CORRECT Answers
Declaring a method - class Myclass{
static void sayHello(){
//sayHello is the method
System.out.println("Hello World!")
}
public static void main (String [ ] args) {
sayHello();
sayHello();
sayHello();
}
}
/* output:
Hello World!
Hello World!
Hello World!
*/
code reuse - You can write a method once, and use it multiple times, without having to rewrite
the code each time
Return value syntax - class MyClass {
, static int sum(int val1, int val2) {
return val1 + val2;
}
public static void main(String[ ] args) {
int x = sum(2, 5);
System.out.println(x);
}
}
//output 7
*Note: The return is saying to add val 1 and val 2 (parameters), as you can see in the next
function starting with public, there is a variable with x and the sum has (2,5) those two will be
added due to the method prior
Public - The class is accessible by any other class.
Package - A group of similar types of classes
Default - A variable or method declared with no access control modifier is available to any other
class in the same package.
Protected - Same as default, with the addition that subclasses can access protected methods and
variables of the superclass (learn more about subclasses and superclass later)
Private - Accessible only within the declared class itself