[go: up one dir, main page]

0% found this document useful (0 votes)
6 views10 pages

CSE 1205 Theory

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

CSE 1205 Theory

Q1. Why is JAVA Platform Independent?


Java is platform independent because it compiles source code into an intermediate bytecode format,
which can run on any platform with a Java Virtual Machine (JVM). This means that once Java code is
compiled, it can be executed on any device or operating system that has a compatible JVM, without the
need for recompilation.

Q2. How is JAVA code compiled?


Java code is compiled using the Java compiler (javac), which translates the human-readable Java source
code into platform-independent bytecode. This bytecode is stored in .class files. When the Java program
is executed, the bytecode is interpreted or just-in-time (JIT) compiled by the Java Virtual Machine (JVM)
into machine code specific to the underlying hardware and operating system. This two-step process of
compilation and execution allows Java programs to be portable and run on any system with a
compatible JVM.

Q3. What is Type Casting?


Type casting in Java refers to the process of converting a value from one data type to another. This is
necessary when you want to assign a value of one data type to a variable of another data type, or when
you want to perform operations involving different data types.
There are two types of casting in Java:
Implicit Casting (Widening): This occurs when you convert a smaller data type to a larger data type. For
example, converting an int to a double. Implicit casting is done automatically by the compiler because it
doesn't result in data loss.
Explicit Casting (Narrowing): This occurs when you convert a larger data type to a smaller data type. For
example, converting a double to an int. Explicit casting requires the programmer to explicitly specify the
casting operation using parentheses and the target data type. It may result in data loss or truncation, so
the programmer needs to be cautious.

Q4. Why a programmer doesn't want to share executable code?


Sharing executable code may limit a programmer's ability to monetize their work through resale since
others can potentially redistribute or use it without proper authorization. This can significantly impact
the programmer's ability to generate revenue from their software. Therefore, protecting the executable
code can be crucial for preserving its commercial value.

Q4. Define “Instance Variable” & “Reference Variable”


Instance Variable: These are variables declared within a class but outside of any method, constructor, or
block. Each instance of the class (object) has its own copy of instance variables. They represent the state
of an object and can have different values for each object.
Reference Variable: These are variables that hold references (memory addresses) to objects in Java.
They do not directly store the object's data but rather point to where the object is stored in memory.
Reference variables can be assigned to different objects of compatible types, allowing for polymorphism
and dynamic behavior in Java programs.

Q5. What is a class in Java? what does it do?


A class in Java is a blueprint for creating objects. It defines the attributes and methods that objects of
that class will have. Essentially, a class encapsulates data for the object and provides methods to
manipulate that data. Classes facilitate code organization, reusability, and maintainability by allowing for
modular programming. They serve as templates for creating multiple instances (objects) with similar
characteristics and functionalities.

Q6.What is an access modifier? What does public and private do in JAVA?


Access modifiers are those which can be used to specify the visibility of a class and its members.
Public: Access modifier that allows members (variables, methods, and classes) to be accessed from any
other class.
Private: Access modifier that restricts members to be accessed only within the same class. They cannot
be accessed from outside the class.
Public allows broader access, while private restricts access, enhancing encapsulation and control over
class members. To access private members, we use other public methods known as getters and setters,

Q7. What are getters and setters?


Getter: A method that retrieves the value of a private variable. It typically has a name starting with "get"
followed by the name of the variable it retrieves. Getters are often used to access the state of an object
without directly exposing its internal representation.
Setter: A method that modifies the value of a private variable. It typically has a name starting with "set"
followed by the name of the variable it sets. Setters provide a way to update the state of an object while
maintaining control over how the state is modified, allowing for validation or additional logic to be
applied.

Q8. What is a Constructor? Explain the purpose of using constructors.


A constructor in Java is a special type of method that is automatically called when an instance (object)
of a class is created. It is used to initialize the state of an object by assigning initial values to its instance
variables or performing any necessary setup tasks. Constructors have the same name as the class they
belong to. Constructors do not have a return type, not even void. If a class does not explicitly define any
constructors, Java provides a default constructor with no arguments.
Constructors in Java are special methods used to initialize objects. They are called when an instance of a
class is created. The purpose of using constructors includes:
Initialization: They set initial values for object attributes and perform setup operations necessary for the
object.
Consistency: Ensures that an object starts its life in a consistent state by requiring necessary parameters
for initialization.
Overloading: Multiple constructors can be defined with different parameters to provide various ways of
initializing an object.

Q9. What is method overloading?


Method overloading in Java refers to the ability to define multiple methods in a class with the same
name but different parameter lists. Methods must have the same name but different parameter types
or a different number of parameters. Overloading enables the creation of multiple methods with similar
functionality but different ways of accepting inputs. The compiler determines which overloaded method
to call based on the number and types of arguments passed to it at the time of invocation. Changing just
the return type doesn't overloads a method.

Q10. Define the "this" keyword.


The this keyword is a reference variable that refers to the current object within a class. It can be used to
access instance variables and methods of the current object, differentiate between instance variables
and parameters with the same name, and pass the current object as a parameter to other methods or
constructors.

Q11. What does "static" keyword do? Define static variables and static methods.
The static keyword is used to define class-level members (variables and methods) that are shared among
all instances of the class. It allows access to these members without needing to create an object of the
class.
Static Variables (Class Variables): When a variable is declared as static, only a single copy of that variable
is created and shared among all instances of the class. They are initialized only once, at the start of the
program execution, and can be accessed using the class name.
Static Methods: Similarly, when a method is declared as static, it belongs to the class rather than to
instances of the class. Static methods can be called directly using the class name, without the need to
create an object of the class. They cannot access instance variables directly (unless through an object
reference passed to them), but they can access other static members.

Q12. Why is the main method public and static?


Public Access: Declaring the main method as public allows it to be accessed from outside the class. This
is essential because the JVM needs to locate and execute the main method when launching the Java
program. Making it public ensures that it can be called by the JVM without any access restrictions.
Static: The main method is declared as static because it belongs to the class itself, rather than to any
particular instance of the class. This means that it can be called directly by the JVM without needing to
instantiate the class. Since the JVM doesn't create an object of the class to execute the main method,
making it static ensures that it can be accessed without an object context.

Q13. What does the "new" keyword do in JAVA?


The new keyword in Java performs two main tasks:
Memory Allocation: It allocates memory from the heap for a new object instance of the specified class.
Constructor Invocation: It initializes the new object by invoking the constructor of the class, setting up
the initial state of the object.

Q14. Describe constructor overloading in JAVA.


Constructor overloading in Java refers to defining multiple constructors within the same class, each
having a different parameter list. This allows the creation of objects in different ways, providing
flexibility based on the given inputs.
Same Name, Different Parameters: All constructors must have the same name as the class but differ in
the number or types of their parameters.
Flexibility: It allows for creating objects with different initial states depending on which constructor is
called.
Initialization: Each constructor can have different logic to initialize the object.

Q15. What does the "Final" Keyword do in JAVA?


In Java, the final keyword is used to declare constants, restrict inheritance, and prevent method
overriding. It can be applied to variables, methods, and classes with the following effects:
Final Variables: When a variable is declared as final, it means that its value cannot be changed once it is
initialized. This makes the variable a constant.
Final Methods: A method declared as final cannot be overridden by subclasses. This is useful when you
want to ensure that the implementation of a method remains unchanged in any subclass.
Final Classes: A class declared as final cannot be subclassed. This means no other class can extend a final
class.

Q16. Describe Inheritance in JAVA.


Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.
It is a form of software reuse in which a new class is created by absorbing an existing class’s members
and embellishing them with new or modified capabilities.

Q17. Describe Super class, Subclass in JAVA.


Super Class: The class whose properties and methods are inherited. Also called the parent class or base
class.
Sub Class: The class that inherits the properties and methods from the super class. Also called the child
class or derived class.
Subclasses inherit all public and protected members of the superclass. Private members are not
inherited but can be accessed through public or protected methods.

Q18. Describe the use of "extends" and "super" keyword in JAVA.


extends: The extends keyword is used to indicate that a class is inheriting from a superclass. When a
class extends another class, it inherits all non-private fields and methods from the superclass.'
super: The super keyword is used to refer to the superclass (parent class) of the current object. It can be
used to access superclass methods and fields, and to call the superclass constructor.

Q19. Describe Method Overriding in JAVA.


Method overriding in Java is a feature that allows a subclass to provide a specific implementation for a
method that is already defined in its superclass. The overridden method in the subclass should have the
same name, return type, and parameters as the method in the superclass.

Q20. Why cannot a private instance variable be accessed from a subclass?


A private instance variable cannot be accessed from a subclass because it is restricted to the class in
which it is declared. The private access modifier ensures that the variable is only accessible within its
own class, providing encapsulation and preventing external classes, including subclasses, from directly
accessing or modifying it.

Q21. Describe Dynamic Method Dispatch (DMD) in JAVA.


Dynamic Method Dispatch is a key feature in Java that enables runtime polymorphism. It is the
mechanism by which the correct version of an overridden method is called at runtime, based on the
object being referred to by a superclass reference variable. It is actually done when an overridden
method is called through a superclass reference.

Q22. Define abstract classes and methods in JAVA.


In Java, abstract classes and methods are used to achieve abstraction, a fundamental concept in object-
oriented programming that allows you to define a blueprint for classes while hiding the implementation
details. Abstract classes cannot be instantiated on their own and may contain abstract methods,
concrete methods, or both. Abstract methods lack implementation and must be overridden by
subclasses or declared abstract themselves.

Q23. Describe interface in JAVA.


In Java, an interface is a blueprint of a class that defines a set of method signatures but does not provide
the implementation. Interfaces allow for achieving abstraction and defining a contract that classes must
adhere to. Classes can implement one or multiple interfaces, thereby enforcing a common behavior
across different classes. Interfaces are declared using the interface keyword and can contain constant
variables and abstract methods. They are used to achieve multiple inheritance, allowing a class to inherit
from multiple interfaces.

Q24. What is the use of "implements" keyword in JAVA?


In Java, the implements keyword is used to indicate that a class is implementing an interface. When a
class implements an interface, it promises to provide concrete implementations for all the abstract
methods declared in that interface. A class can implement multiple interfaces, separating them with
commas. If an interface extends another interface, a class implementing the child interface must also
provide implementations for the abstract methods inherited from both interfaces.

Q25. Describe runtime error in JAVA.


A runtime error in Java, also known as an exception, occurs during the execution of a program when
something unexpected happens that disrupts the normal flow of the program. These errors are not
detected by the compiler during compilation but occur during runtime when the program is being
executed. Runtime errors can lead to abnormal program termination if they are not handled properly.

Q26. What is the difference between abstract class and interface?


An abstract class is used to provide a common base with both abstract and concrete methods. On the
other hand, an interface is used to define a contract that classes must follow, containing only abstract
methods.
An abstract class can contain both abstract and concrete methods but an interface can only contain
abstract methods.
An abstract class can have instance variables with various access modifiers but an interface can only
have public static final constants.
An abstract class can have constructor but interfaces cannot.
A class can extend only one abstract class but it can implement several interfaces.
An interface cannot provide any code at all, much less default code. An abstract class can provide
complete code, default code, abstract methods that have to be overridden.

Q27. What are the uses of interface?


Interfaces are useful for the following:
■ Capturing similarities between unrelated classes without artificially forcing a class relationship.
■ Declaring methods that one or more classes are expected to implement.

Q28. Define exception handling in Java.


A java exception is an object that describes an exceptional condition that occurred in a piece of code.
Exception handling in Java is a mechanism to handle runtime errors, ensuring the normal flow of the
program. When an error occurs during execution, an exception object is created, which contains
information about the error.
Q29. Keywords in Java exception handling.
Exception handling is managed by five keyword
■ try: Program statement that you want to monitor for exception are contained within a try block.
■ catch: Your code can catch the exception and handle it.
■ throw: Use to throw an exception manually.
■ throws: A method may throw an exception must be specified by a throws clause.
■ finally: Any code that must be executed before a method return is put in a finally block.

Q30. Exception in thread main java.lang. ArithmeticException: / by zero Exc0.main(Exc0.java:4)".


What information can you extract from the statement?
The error message "Exception in thread "main" java.lang.ArithmeticException: / by zero
Exc0.main(Exc0.java:4)" provides several important details about the exception that occurred during the
execution of a Java program. Here's a breakdown of the information:
1. Exception in thread "main"
This indicates that the exception occurred in the main thread of the program, which is the thread that
starts the execution of every Java application. The main thread is responsible for running the main
method.
2. java.lang.ArithmeticException
This is the type of exception that occurred. Specifically, it is an ArithmeticException, which is an
unchecked exception. This kind of exception is thrown when an illegal arithmetic operation is
performed, such as division by zero.
3. / by zero
This is the detailed message that provides more information about the cause of the exception. In this
case, the message indicates that the error occurred due to an attempt to divide a number by zero, which
is not allowed in arithmetic operations.
4. Exc0.main(Exc0.java:4)
This part indicates the location of the exception in the code. Specifically:
Exc0: The name of the class where the exception occurred (Exc0 in this case).
main: The name of the method where the exception was thrown (in this case, the main method).
Exc0.java:4: This specifies the exact file and line number where the exception occurred, indicating that
the error is in the file Exc0.java on line 4.

Q31. Explain the concept of checked exceptions.


Checked exceptions are exceptions that are checked at compile time by the Java compiler. These
exceptions must be either caught using a try-catch block or declared in the method signature using the
throws keyword. If a method might throw a checked exception, the programmer is required to handle it
properly or the program will not compile.
Q32. Difference between checked and unchecked exception.

Aspect Checked exception Unchecked exception

Checked at compile Yes No


time
Compiler Must be handled or declared with No need to handle or declare
Enforcement throws
Handling Required to be handled in code Optional
Requirement
Common Subclasses IOException, SQLException, NullPointerException,
ClassNotFoundException ArithmeticException,
ArrayIndexOutOfBoundsException
When it Occurs Situations that are typically Programming errors, typically
recoverable unrecoverable

Q33. Why an exception handling approach is preferable then a if-else if-else approach?
Why Exception Handling is Preferable:

1. Separation of Logic:
o Exception handling separates error-handling code from business logic, improving
code readability and maintainability.
2. Readability & Simplicity:
o Exception handling avoids deeply nested if-else chains, keeping the code clean
and easier to understand.
3. Scalability:
o It scales better with complex applications, allowing easy management of multiple
error types without cluttering the main logic.
4. Consistency:
o Exception handling provides a consistent mechanism across the application,
reducing inconsistency compared to scattered if-else blocks.
5. Unexpected Errors:
o Exceptions can handle rare and unforeseen errors more effectively, whereas if-
else is limited to predefined conditions.
6. Recovery:
o Exception handling allows for better recovery mechanisms, such as retrying an
operation or fallback logic.
7. Performance:
o Exception handling is better suited for handling rare errors, while too many if-else
checks can introduce performance overhead.
Q34. When the finally block is used? Provide a scenario in natural language for a proper explanation.
The finally block in Java is used to execute code regardless of whether an exception occurs or not. It's
typically used for resource cleanup like closing files, database connections, or releasing system
resources.
Scenario:
Imagine you're writing a program that reads data from a file. Even if an error occurs while reading the
file (e.g., the file doesn't exist), you still need to close the file or release resources to prevent resource
leaks. The finally block ensures this cleanup happens even if an exception is thrown during file reading.
Key Points:
1. Executes after try and catch, whether an exception is handled or not.
2. Commonly used for cleanup operations (closing files, connections, etc.).
3. Guarantees resource release even if exceptions occur.

Q35. Explain the ways in which a thread can arrive to "Ready" state in its lifecycle.
A thread can enter the "Ready" (Runnable) state in several ways:
1. After calling start() on a new thread.
2. Returning from a blocked or waiting state, such as after a lock is released or a wait condition is
satisfied.
3. When a thread's sleep time is over or after calling notify() on a waiting thread.

Q36. Which are the two ways that a thread can be created in Java? Why one approach is preferable to
the other one?
Two Ways to Create a Thread in Java:
1) Extending the Thread class:

2) Implementing the Runnable interface:


Why Runnable is preferable:
Extending Thread restricts inheritance since Java supports single inheritance.
Implementing Runnable allows the class to extend other classes, promoting better flexibility and design.

Q37. Describe the life cycle of a thread in java.


1.Born: The thread is created.
Transition: The start method is called to move the thread to the next state.
2.Ready: The thread is ready to run and waiting for CPU allocation.
Transitions:
•A thread dispatch assigns a processor, moving the thread to the Running state.
•It can also transition back from Running to Ready if a quantum expiration occurs, or the thread yields.
3.Running: The thread is actively executing its code.
Transitions:
•It can move to the Blocked state if it issues an I/O request or enters a synchronized statement.
•If it calls sleep, it goes to the Sleeping state.
•It can be interrupted or placed in a wait state, moving to the Waiting state.
•After completion, it transitions to the Dead state.
4.Waiting: The thread is waiting for a condition to be met.
Transitions: It goes back to Ready when it is notified (notify, notifyAll), or if a timeout expires or it gets
interrupted.
5. leeping: The thread is paused for a specified time.
Transition: It returns to the Ready state once the sleep interval expires or if interrupted.
6. Blocked: The thread is blocked, waiting for I/O completion or acquiring a lock.
Transition: It returns to Ready once the I/O completes or it acquires the lock.
7. Dead: The thread has completed execution (returns from its run method), and this is the final state.

You might also like