Week 2: Java Intermediate (Answers)

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What are classes used for?

A class is a blueprint or a template for creating objects. A class defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a logical construct; an object has physical reality. Here's what a class is used for: Encapsulation: A class encapsulates data (attributes) and methods (functions) into a single unit. Each object of a class can have its own values for the class's attributes, so an object is an instance of a class. Abstraction: A class provides a simple interface to the outside world, hiding its internal details and only exposing functionality that's needed. This way, a class can change its internal implementation without affecting other parts of the code. Inheritance: Classes can inherit fields and methods from other classes. A class that inherits from another class is known as a subclass, and the class it inherits from is known as a superclass. This allows for code reusability and can also be used to add more features to a class without modifying it. Polymorphism: A class allows us to use a single interface to represent different types of actions. This helps increase the flexibility and inter-operating functionality of programs.

What is a constructor and how is it different from a method?

A constructor in Java is a special type of method that is used to initialize objects. It's called when an object of a class is created. Here are some key characteristics of constructors: 1) The constructor's name must be the same as the class name it belongs to. 2) A constructor doesn't have a return type, not even void. 3) Every class has a constructor. If we do not explicitly write one, Java will automatically provide a default constructor. Methods in Java perform certain actions and are named functions that belong to a class. They can have return types and can return a value.

What is the difference between an array and an ArrayList?

Array and ArrayList are both used to store elements, which can be either primitives or objects in case of an Array and only objects for an ArrayList. However, they have some significant differences: 1) Size: An Array is static, which means it has a fixed length. You can't change its size once it's created. On the other hand, an ArrayList is dynamic - it can grow and shrink at runtime as elements are added or removed. 2) Type Safety: Array is type-safe, i.e., it enforces type checking at compile-time. If you try to store the wrong type in an array, it will cause a compile-time error. ArrayList, on the other hand, did not provide type safety until Java 5 when generics were introduced. Before Java 5, you could store any type of objects in an ArrayList, but now you can specify the type of elements using generics. 3) Performance: Array is faster and uses less memory as it doesn't have the overhead of object methods associated with it, unlike ArrayList. 4) Flexibility: ArrayList, being part of the Java Collections Framework, has built-in methods for many common tasks, like adding an element at any position, replacing an element, etc. These operations are much more complex and require manual work with an Array.

Describe the difference between the stack and the heap.

Stack: * The stack is used for static memory allocation, and it is where local variables (variables declared within methods) get stored. * It's organized as a last-in, first-out structure (LIFO), so the most recently reserved block is always the next to be freed. This makes it simple to keep track of the stack, freeing blocks from the top of the stack is straightforward and efficient. * Each thread in a program has its own stack. * Accessing the stack is fast, and its size is set when a thread is created, but it can be exhausted - known as a stack overflow, which can crash a program. * If a function or a method calls another, the execution of all functions remains suspended until the very last function returns its value. Stack: * The heap is used for dynamic memory allocation, and is where objects are stored. * It's organized in a more complex manner, allowing it to allocate and deallocate blocks of memory in any order. * Unlike the stack, the heap is not automatically managed for you, so you have to handle memory deallocation yourself. However, in Java, the garbage collector helps manage this by automatically freeing up unused objects in the heap. * Accessing the heap is slightly slower because of its complex structure, but it's larger and less likely to be exhausted. * The heap is shared among all threads of a program.

What is the difference between a checked and an unchecked exception?

Checked Exceptions: These are exceptions that are checked at compile time. If a method throws a checked exception, it must either handle that exception using a try-catch block, or it must declare the exception, using the throws keyword, letting callers know about the exception. Checked exceptions extend the Exception class and are often used to indicate that a method might fail for reasons beyond the control of the method or caller, such as a file not being found for a file reader. IOException and ClassNotFoundException are examples of checked exceptions. Unchecked Exceptions: These are exceptions that are not checked at compile time, meaning the compiler doesn't require that they be caught or declared in a throws clause. They are often used to indicate programming errors, such as passing a null object or illegal arguments. Unchecked exceptions extend the RuntimeException class. NullPointerException and ArrayIndexOutOfBoundsException are examples of unchecked exceptions.

What is the role of garbage collection in Java?

Garbage Collection (GC) is one of the most important features of Java. Its role is to manage memory automatically by reclaiming memory occupied by objects that are no longer in use by the application. This means programmers don't have to worry about manually deallocating memory, which can be a source of various issues like memory leaks and dangling pointers, as seen in languages like C and C++. The garbage collector is generally run in the background, mostly invisible to the programmer. However, you can request that the JVM perform a garbage collection via System.gc(), but it's generally a bad idea to do so. Relying on it can lead to performance issues, and the call is not guaranteed to result in an immediate garbage collection.

What is a package and why would we use one?

In Java, a package is a namespace that organizes a set of related classes and interfaces. Conceptually, you can think of packages as being similar to different folders on your computer. Just like you use folders to organize your files, you use packages to organize your classes and interfaces. Here are some reasons why we use packages in Java: 1) Organization: Packages help in organizing your code. By keeping related classes and interfaces together in a package, it becomes easier to locate and use them. 2) Avoiding Name Conflicts: Packages can help avoid name conflicts. Two classes in two different packages can have the same name without causing a naming conflict. 3) Access Control: Packages can be used to control access to classes, interfaces, and members (methods & variables). Some members of a class/interface may be accessible only within the same package, providing a level of encapsulation. 4) Easier Maintenance and Distribution: Packages make it easier to manage and distribute your code. For larger applications, managing code becomes more feasible when it's organized into packages. Furthermore, when distributing your code (as a library, for example), packages help in bundling the classes in a structured manner.

What is the difference between an Error and an Exception?

In Java, both Error and Exception are subclasses of Throwable, but they each represent different kinds of issues that can arise when your program is running. Error: An Error represents serious problems that a reasonable application should not try to catch. Most often these are external to your application, and beyond your control. They are conditions that occur at runtime and are generally irrecoverable. They can even halt the Java Virtual Machine (JVM) execution. Some common examples of Error are OutOfMemoryError and StackOverflowError. Exception: An Exception is an issue that occurs during the execution of a program. Exceptions are conditions that are possible to catch and handle in the code, so your program can recover and continue or at least provide a graceful termination. Exceptions are divided into two categories: 1) Checked Exceptions: These exceptions must be either declared in the method's throws clause or caught inside the method body. They extend the Exception class, but not the RuntimeException class. IOException is an example of a checked exception. 2) Unchecked Exceptions: These are not required to be caught or declared in a method's throws clause. They extend the RuntimeException class, and the compiler does not check at compile-time to see whether these exceptions are handled or declared. NullPointerException and ArithmeticException are examples of unchecked exceptions.

If you received text input from the user, how would you go about comparing it to a value, like "yes" or "no"?

In Java, you can use the equals() or equalsIgnoreCase() method of the String class to compare strings.

How would you handle an exception?

In Java, you handle exceptions using try, catch, and finally blocks: try: The try block contains the code that might throw an exception. If an exception or error occurs inside the try block, it's thrown, and the flow of control stops and moves to the first catch block. catch: The catch block is used to handle the exception. It must be declared immediately after the try block and can't exist without it. The catch block is like a method that takes an exception type as an argument. This block of code is executed if the exception caught is of the catch block's type or a subtype of it. finally: The finally block always executes, whether an exception was thrown or not, and whether or not it was caught. It's used for cleanup code, such as closing resources like database connections or file streams

Describe what an object is.

In the context of object-oriented programming (OOP), an object is an instance of a class. When a class is defined, no memory is allocated but when it is instantiated (i.e., an object is created) memory is allocated. An object is a real-world entity that has a state and behavior. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects correspond to things found in the real world. For example, a bicycle is an object in real life. It has states (like color, brand, model, gear, speed) and behaviors (like changing gears, applying brakes). In Java, for example, you might have a class called Bicycle, and you could have an object called myBicycle that's an instance of the Bicycle class.

What is the difference between calling an instance method and a static method?

Instance Methods: Instance methods are associated with an object (an instance of the class). They can access instance variables and other instance methods directly. To call an instance method, you need to create an instance (object) of the class first. Static Methods: Static methods are associated with the class itself, not with any specific instance. They can only directly access other static methods and static variables, they cannot directly access instance variables or instance methods. You don't need to create an instance of the class to call a static method; you can call it on the class itself.

What is the difference between using an instance variable and a static variable?

Instance Variables: These are non-static variables that are declared in a class but outside of a method, constructor, or any block. Each instance (or object) of the class has its own copy of the instance variable. Changes made to the instance variable using one object will not affect the instance variable of another object. Static Variables: These are variables declared with the static keyword within a class but outside a method, constructor, or a block. Unlike instance variables, there is only one copy of a static variable, and it is shared among all instances (or objects) of the class. Therefore, if changes are made to the static variable, it affects all objects of the class.

If I define a variable within a method, how can I access its value outside of the method?

To access a value that's calculated within one method from another method or part of your code, here are a few potential solutions: 1) Return the value: This is the most common way. When you calculate a value in a method, you often return it as the result. 2) Store the value in an instance variable: If you're working within a class and multiple methods need to share a variable, you can use an instance variable.


संबंधित स्टडी सेट्स

Prostate Gland and Seminal Vesicles

View Set

idk anymore i just want to go to sleep

View Set

Level 3 - Review and Remember 1: Numbers Quiz

View Set

Endocrine system PrepU Pathophysiology

View Set

Exam two part two: Acid Base Balance

View Set