Java - Claude Flashcards
What is an object in Java?
An instance of a class that has state (fields/attributes) and behavior (methods).
// Person class class Person { // State (fields) String name; int age; // Behavior (methods) void speak() { System.out.println(name + " says hello!"); } } // Creating a Person object Person john = new Person(); // john is an object
What is the relationship between a class and an object?
A class is a blueprint or template, while an object is a concrete instance created from that class.
// Dog class - the blueprint class Dog { String breed; int age; } // Dog objects - instances of the blueprint Dog fido = new Dog(); // First instance Dog rex = new Dog(); // Second instance Dog spot = new Dog(); // Third instance
How do you create an object in Java?
Using the new
keyword followed by a call to a constructor.
// Creating objects different ways: Student s1 = new Student(); // No-arg constructor Student s2 = new Student("Alice", 20); // Parameterized constructor ArrayList<String> list = new ArrayList<>(); // Using generics String[] names = new String[10]; // Array creation
What happens when a Java object is created?
Memory is allocated, the constructor is called, and a reference to the object is returned.
// Memory allocation and initialization Car myCar = new Car("Toyota"); // Memory allocated, constructor runs myCar = null; // Object becomes eligible for garbage collection myCar = new Car("Honda"); // New memory allocated, different object created
What are instance variables in Java?
Variables defined in a class that represent the state or attributes of an object.
class BankAccount { // These are instance variables private String accountNumber; private double balance; private String owner; // Constructor and methods }
What is the difference between instance variables and local variables?
Instance variables belong to an object and exist for the lifetime of the object, while local variables exist only within the method or block where they are declared.
class Rectangle { // Instance variables - exist for lifetime of the object private double width; private double height; public double calculateArea() { // Local variable - exists only inside this method double area = width * height; return area; } }
What are default values for instance variables in Java?
Numeric types: 0, boolean: false, char: ‘\u0000’, reference types: null
class DefaultValues { // These will have default values if not initialized int number; // Default: 0 boolean flag; // Default: false char character; // Default: '\u0000' (null character) String text; // Default: null double decimal; // Default: 0.0 public void printDefaults() { System.out.println("number: " + number); System.out.println("flag: " + flag); System.out.println("character: " + (int)character); System.out.println("text: " + text); System.out.println("decimal: " + decimal); } }
How do you access an object’s fields?
Using dot notation: objectName.fieldName
class Book { String title; String author; } public class Main { public static void main(String[] args) { Book myBook = new Book(); // Accessing fields with dot notation myBook.title = "Java Programming"; myBook.author = "John Smith"; // Reading field values System.out.println("Title: " + myBook.title); System.out.println("Author: " + myBook.author); } }
How do you define a method in a Java class?
[access_modifier] [return_type] methodName([parameters]) { [method body] }
class Calculator { // Method with public access, returns int, has two parameters public int add(int a, int b) { return a + b; } // Method with private access, returns void (nothing), no parameters private void resetMemory() { System.out.println("Memory reset"); } // Method with default access, returns double, one parameter double square(double num) { return num * num; } }
How do you call a method on an object?
Using dot notation: objectName.methodName(arguments)
class EmailService { public void sendEmail(String recipient, String subject, String body) { System.out.println("Email sent to " + recipient); } } public class Main { public static void main(String[] args) { EmailService emailer = new EmailService(); // Calling the method emailer.sendEmail("friend@example.com", "Hello", "How are you?"); } }
What is method overloading?
Defining multiple methods in the same class with the same name but different parameter lists.
class MathUtils { // Overloaded methods - same name, different parameters public int multiply(int a, int b) { return a * b; } public double multiply(double a, double b) { return a * b; } public int multiply(int a, int b, int c) { return a * b * c; } } public class Main { public static void main(String[] args) { MathUtils math = new MathUtils(); // Java calls the right method based on arguments System.out.println(math.multiply(5, 3)); // Calls first method System.out.println(math.multiply(2.5, 3.0)); // Calls second method System.out.println(math.multiply(2, 3, 4)); // Calls third method } }
What is the this
keyword used for?
To refer to the current object, often used to distinguish between instance variables and method parameters with the same name.
class Person { private String name; private int age; // Constructor using this to refer to instance variables public Person(String name, int age) { this.name = name; // this.name refers to instance variable this.age = age; // this.age refers to instance variable } // Method using this to call another method in the same class public void introduce() { System.out.println("Hi, I'm " + this.name); this.celebrateBirthday(); // Calling another method with this } private void celebrateBirthday() { this.age++; System.out.println("Happy birthday! Now I'm " + this.age); } }
What is a constructor in Java?
A special method that is called when an object is created, used to initialize the object’s state.
class Student { private String name; private int id; // Constructor - same name as class, no return type public Student(String name, int id) { this.name = name; this.id = id; System.out.println("Student object created"); } public void display() { System.out.println("Student: " + name + ", ID: " + id); } } public class Main { public static void main(String[] args) { // Constructor is called here Student alice = new Student("Alice", 12345); alice.display(); } }
What are the properties of a constructor?
Same name as the class, no return type, can be overloaded, can use this()
to call another constructor.
class Employee { private String name; private int id; private double salary; // Constructor 1 - all fields public Employee(String name, int id, double salary) { this.name = name; this.id = id; this.salary = salary; } // Constructor 2 - calls Constructor 1 with default salary public Employee(String name, int id) { this(name, id, 50000.0); // Calls the first constructor } // Constructor 3 - calls Constructor 2 with default id public Employee(String name) { this(name, 1000); // Calls the second constructor } }
What is a default constructor?
A no-argument constructor provided by Java if no constructor is defined in a class.
// Class with no explicit constructors class SimpleClass { private int data; // Java provides this constructor implicitly if none is defined: // public SimpleClass() { // // No initialization code // } public void setData(int data) { this.data = data; } } public class Main { public static void main(String[] args) { // Uses the default constructor SimpleClass obj = new SimpleClass(); obj.setData(100); } }
What happens if you define a constructor with parameters but don’t define a no-arg constructor?
Java will not provide a default constructor, and objects must be created using the parameterized constructor.
class Product { private String name; private double price; // Only a parameterized constructor is defined public Product(String name, double price) { this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { // This works - using the defined constructor Product p1 = new Product("Laptop", 999.99); // This would cause a compilation error - no default constructor exists // Product p2 = new Product(); // Error! } }
What is an object reference in Java?
A variable that stores the memory address of an object, not the object itself.
public class ReferenceDemo { public static void main(String[] args) { // student1 is a reference to a Student object Student student1 = new Student("Bob", 101); // student2 is another reference variable Student student2; // Both references now point to the same object student2 = student1; } }
What happens when you assign one object reference to another?
Both references point to the same object; changing the object through one reference affects what the other reference sees.
class Counter { public int count = 0; public void increment() { count++; } } public class Main { public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = c1; // c2 now references the same object as c1 c1.increment(); // Increments count to 1 System.out.println("c1 count: " + c1.count); // Outputs: 1 System.out.println("c2 count: " + c2.count); // Also outputs: 1 c2.increment(); // Increments count to 2 System.out.println("c1 count: " + c1.count); // Outputs: 2 System.out.println("c2 count: " + c2.count); // Also outputs: 2 } }
What is the value of an uninitialized object reference?
null
public class NullReferenceDemo { public static void main(String[] args) { // Declared but not initialized - default value is null String message; // Explicitly set to null Integer number = null; // This would cause a NullPointerException // System.out.println(number.intValue()); // Safe way to check before using if (number != null) { System.out.println(number.intValue()); } } }
How do you check if an object reference is null?
Using the equality operator: if (objectName == null) {...}
public class NullCheckDemo { public static void main(String[] args) { String text = null; // Checking for null before using the object if (text == null) { System.out.println("The reference is null"); } else { System.out.println("Length: " + text.length()); } // Another example with Objects.isNull from Java 8+ import java.util.Objects; if (Objects.isNull(text)) { System.out.println("The reference is null (checked with Objects.isNull)"); } } }
How is memory allocated for objects in Java?
Objects are created on the heap using the new
keyword.
public class MemoryDemo { public static void main(String[] args) { // Local variable 'age' is created on the stack int age = 30; // Object is created on the heap, reference 'person' on stack Person person = new Person("John"); // When method ends, 'age' and 'person' reference are removed from stack // but the Person object remains on the heap until garbage collected } public static void createObjects() { // These objects are created on the heap for (int i = 0; i < 1000; i++) { Person temp = new Person("Person" + i); // 'temp' goes out of scope after each iteration // making the Person object eligible for garbage collection } // At this point, all 1000 Person objects are eligible for garbage collection } }
What is garbage collection in Java?
The automatic process of reclaiming memory occupied by objects that are no longer referenced.
public class GarbageCollectionDemo { public static void main(String[] args) { // Create objects String s1 = new String("Hello"); String s2 = new String("World"); // Reassign references s1 = s2; // Original "Hello" string is now eligible for garbage collection // Explicitly request garbage collection (though JVM may not comply immediately) System.gc(); // Create many objects to potentially trigger garbage collection for (int i = 0; i < 10000; i++) { new Object(); } } }
When is an object eligible for garbage collection?
When there are no more references to it, or all references are out of scope.
public class GarbageEligibilityDemo { public static void main(String[] args) { // Case 1: Reassigning a reference StringBuilder sb = new StringBuilder("Original text"); sb = new StringBuilder("New text"); // Original StringBuilder is now eligible // Case 2: Nullifying a reference Integer num = new Integer(100); num = null; // Integer object is now eligible // Case 3: Object reference goes // ... } }
What makes an object eligible for garbage collection?
An object is eligible for garbage collection when there are no more references to it, or all references are out of scope.
What happens when a reference is reassigned?
The original object is now eligible for garbage collection.
What happens when a reference is nullified?
The object that the reference pointed to is now eligible for garbage collection.
What occurs when an object reference goes out of scope?
The object created in the method is now eligible for garbage collection.
What is an example of an island of isolation?
When two objects reference each other but are set to null, both objects become eligible for garbage collection.
What is the purpose of the finalize()
method?
To perform cleanup operations before an object is garbage collected, though its use is discouraged in modern Java.
What happens if a resource is not properly closed?
A warning is issued during garbage collection if the resource was not closed properly.