135 Practice Questions covering Objects, Classes, Encapsulation, Scope, Graphics, and Static Modifiers.
Dog, write the line of code
required to create a new instance of Dog and assign it to a variable named myPuppy.
Dog myPuppy = new Dog();drive(), fuelLevel,
color, honkHorn().drive(): FunctionalityfuelLevel: Statecolor: StatehonkHorn(): Functionalitythis refers to in
the whine method.
public class Dog {
private String name;
public void whine() {
System.out.println(this.name + " whines!");
}
}
name and any local variables that might have the same name.privateprivate, how can an external object
(like Main) read or modify its value? What types of methods do you need to write?Account.
balance.getBalance() that returns
the balance.deposit(int amount) that
adds to the balance.
public class Account {
private int balance;
public int getBalance() {
return this.balance;
}
public void deposit(int amount) {
this.balance += amount;
}
}
public void calculate() {
int x = 10;
if (x > 5) {
int y = 20;
}
System.out.println(x + y);
}
y is declared inside the if
block. It ceases to exist outside that block, so System.out.println(x + y) cannot
find y.JComponent and override which method?paintComponent(Graphics g)JFrame, what method must be called at the end to
actually make the window appear on the screen?frame.setVisible(true);static, how many copies of that
variable exist if you create 100 objects of that class?main method in Java always declared as
static?
public class Counter {
public static int count = 0;
public Counter() {
count++;
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(Counter.count);
}
}
count is static, it is shared.
Every time new Counter() is called, the constructor increments the shared
variable).Car, and you write
Car c1 = new Car(); and Car c2 = c1;, how many distinct
Car objects exist in memory?c2 = c1 simply copies the reference
(address), pointing both variables to the single object in memory.int) and an
object type (like String or Dog) regarding what is stored in the
variable.Lamp that has one instance
variable isOn (boolean). Include a constructor that sets isOn to
false initially.
public class Lamp {
boolean isOn;
public Lamp() {
this.isOn = false;
}
}
Greeter worldGreeter = new Greeter("World");, what
is worldGreeter technically called?null
(e.g., dog.bark() where dog is null), what specific error (exception)
occurs at runtime?NullPointerExceptionnewpublic int add(int a, int b), what does
the keyword int before the method name signify?void, can you still use the return
keyword inside it? If so, how?return; (with no value) to exit the method
early.isAdult for a Person class. It
should take no parameters and return true if the person's age (an instance
variable) is greater than or equal to 18, and false otherwise.
public boolean isAdult() {
if (this.age >= 18) { return true; }
else { return false; }
}
public void setName(String name), how do you assign the
parameter name to the instance variable name without naming conflict?
this.name = name;publicprivatepublic?numWheels is a private variable in the Car class,
write a standard "Setter" method signature and body to update it.
public void setNumWheels(int num) {
this.numWheels = num;
}
protected, who can access it? (Name two
groups).password. You want to allow external
code to change it, but only if the new password is longer than 5 characters. Write a setter
method that enforces this logic.
public void setPassword(String p) {
if (p.length() > 5) {
this.password = p;
}
}
private variable from
another class. (Hint: Think about getters).int score; as an instance variable,
what is its initial value?int score; inside a method (local
variable) and try to print it immediately, what happens?x is printed?
public class Test {
int x = 5;
public void print() {
int x = 10;
System.out.println(x);
}
}
x shadows the instance variable
x.String s;)
if it is an instance variable?nullpublic or
private) on a local variable inside a method?
public void check() {
if (true) {
String message = "Hello";
}
System.out.println(message); // Error here
}
public void check() {
String message = ""; // Initialize here
if (true) {
message = "Hello";
}
System.out.println(message);
}
Graphics g object to
Graphics2D g2 inside paintComponent?Graphics2D is a newer, more powerful class that extends
Graphics. Casting allows access to advanced drawing methods (like stroke width).
Graphics object named g.g.drawRect(10, 10, 50, 100);finalMathUtils with a method
public static int add(int a, int b), how do you call this method from
Main?new MathUtils().add(1, 2);MathUtils.add(1, 2);MathUtils.add(1, 2); (Called on the Class, not an
object).Math.PI or Color.RED) usually
declared as static?final) and is
the same for everyone, we only need one copy in memory (static), not a copy for
every single object.static final constants? (e.g.,
how would you write "max speed"?)MAX_SPEED).Dog has a static variable dogCount, and you
create 5 Dog objects, what happens if one object changes the value of
dogCount?int, double, boolean,
char, byte, short, long, float.
Book that takes two
parameters (String title, int pages) and assigns them to the
corresponding instance variables.
public Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
dog, DOG, Dog, or dog_class)?Dog).String s1 = "Java"; and String s2 = "Java";
(created literally), does s1 == s2 usually return true or false? Why is comparing
Strings with == dangerous?== compares memory
addresses. Literal strings are often pooled (same address), but if one was created with
new String(), == would fail. Always use .equals().Scanner or
JFrame) so you don't have to type its full package name every time?importpublic String getName(), what
type of data must the return statement provide?Stringvoid cannot have any
parameters.void means it returns nothing; it can still take
parameters.public void drive(int miles). Inside this method,
you want to decrease the fuel instance variable by 1 for every 10 miles driven.
Write the line of code to do this calculation.this.fuel -= (miles / 10);reset() that sets two instance variables,
score (int) to 0 and isActive (boolean) to false.
public void reset() {
this.score = 0;
this.isActive = false;
}
public void (int x)public void doSomething(int x)void public doSomething(x)public void doSomething(int x)Dog or
String) instead of a primitive?
public int getAge() {
int age = 20;
// Missing something here
}
int, but implies it finishes without returning one.private method in a class.private instead of
public? (Hint: Helper methods).private boolean isOpen, write a "Getter" method for
it. (Note: Boolean getters often follow a specific naming convention different from
get...).public boolean isOpen() { return this.isOpen; } (Convention
for booleans is often isVar instead of getVar).protected access allow unrelated classes in a
different package to access the member?Student class. You want to ensure the
gpa variable can never be set below 0.0 or above 4.0. Write a
setGpa(double val) method that only sets the value if it is valid.
public void setGpa(double val) {
if(val >= 0.0 && val <= 4.0) {
this.gpa = val;
}
}
public, it implies a "contract" that the variable
will always exist. Why does changing a public variable to private
later cause problems for other code?.name. If you make it private, all that external code breaks.temp?int x in
void foo(int x)) acts like a Local Variable.
1. public void test() {
2. int a = 10;
3. }
4. int b = a;
a is local to test(). It does not
exist at line 4.int x and a local variable
int x in a method, how do you specify that you want to use the instance
variable inside that method?this.xfor loop (e.g.,
for(int i=0; i<10; i++))?count after this code runs?
int count = 0;
if (count < 5) {
int temp = 5;
count = temp + 2;
}
Color class (e.g.,
Color.RED)?java.awtg.setColor(Color.BLUE), all shapes drawn previously will change to blue.
g.drawString to write "Hello" at
position (50, 50).g.drawString("Hello", 50, 50);static method (like main) directly access
a non-static instance variable (like name) without creating an object first?name you are talking about.Math class would you use to find the square
root of a number?Math.sqrt()public static final int MAX_USERS = 10;, can you write
MAX_USERS = 20; later in the code? Why?final (constant).JFrame, you generally import javax.______.
swing (javax.swing).count is a static variable, and you increment
it in the constructor of a class, what does count essentially track?Robot?class Robot { }public class Robot { }def Robot: public class Robot { }Rectangle that accepts
width and height. Inside the constructor, ensure that if the user
passes a negative value, the dimension is set to 0 instead.
public Rectangle(int w, int h) {
if (w < 0) w = 0;
if (h < 0) h = 0;
this.width = w;
this.height = h;
}
Dog d;) and
instantiating it (d = new Dog();)?Dog d) only
creates a space for a reference (label). Instantiation (new Dog()) actually creates
the object in memory.Cat, can you create an array of
Cat objects? (e.g., Cat[] cats = new Cat[5];).Cat[] cats = new Cat[5];, what is the value
of cats[0] immediately after creation (before you put any actual Cats into it)?
null. (The array exists, but the slots are empty).thisClassName.java?public double calculateTax(double price),
what is the return type?doublepublic void speak(String text). You want to call
another method log() inside it, passing the same text. Write the line of code to
call log.this.log(text); (or just log(text);).int, but you put return "Hello"; inside it.isEven that takes an integer n and
returns true if it is even, and false otherwise. (Hint: Use the modulo
operator %).
public boolean isEven(int n) {
return (n % 2 == 0);
}
void move(int x) and
void move(int x, int y), what is this feature called?
public void setSpeed(int s) {
this.speed = s;
if (s < 0) {
System.out.println("Error");
}
}
this.speed = s; happens
before the check. The invalid value is already set. The check should come first.privateBankAccount class. Why should the
balance variable be private instead of public? Give one
concrete scenario where public would be dangerous.myAccount.balance = -1000000;. Private ensures you can only change it via
withdraw() which checks for funds.Setter for a variable String name. The
requirement is: the name cannot be null and cannot be an empty string
"".
public void setName(String n) {
if (n != null && !n.equals("")) {
this.name = n;
}
}
Person has a private method updateAge(),
can the Main class call p.updateAge()?isReady?getIsReady()getReady()isReady()isReady() (Standard Java convention for boolean
getters).int i inside a for loop header, can you
access i after the loop finishes?
int x = 5;
public void mystery() {
int x = 10;
this.x = 20;
System.out.println(x);
}
x).total. You want to write a method
that adds a local variable amount to it. Write the line of code.this.total += amount;x in
f(int x)) is visible to other methods in the same class.
public void test() {
String s;
if (Math.random() > 0.5) { s = "High"; }
System.out.println(s); // Error: s might not be initialized
}
String s = ""; (or String s = null;) at
the top.java.awt.Graphics, in which direction does the
Y-axis increase?public static void main(String[] args)g.fillOval(0, 0, 50, 50);System.out.println valid code?System
is a class. out is a _____ variable inside that class).out is a public static member of the
System class).static variable can be accessed by class name,
e.g., Hero.powerLevel.MathHelper. You want a constant PI
equal to 3.14 that everyone can read but no one can change. How do you declare it?public static final double PI = 3.14;import java.util.*;import javax.swing.*;
import javax.swing.*;count is a static variable, and you increment it in the
constructor of a class, what does count essentially track?