Repository navigation
Releases: Adnann07/java-notes
Release list
ques-solve-java
Starts from source: Firmgate
Move the gear shift into drive position
A car starts to move
Approach to the destination: AUST
Push on a brake pedal
The car is stopped
Starts from source: Firmgate
Move the gear shift into drive position
A car starts to move
Approach to the destination: AUST
Push on a brake pedal
The car is stopped
Starts from source: Firmgate
Move the gear shift into drive position
A car starts to move
Approach to the destination: AUST
Push on a brake pedal
The car is stopped
import java.util.Scanner;
// Custom exception for invalid names
class InvalidNameException extends Exception {
public InvalidNameException(String message) {
super(message);
}
}
// Custom exception for invalid email
class InvalidEmailException extends Exception {
public InvalidEmailException(String message) {
super(message);
}
}
// Custom exception for invalid mobile number
class InvalidMobileNumberException extends Exception {
public InvalidMobileNumberException(String message) {
super(message);
}
}
// Student class
class Student {
String firstName;
String lastName;
int age;
String email;
String mobile;
// Constructor
public Student(String firstName, String lastName, int age, String email, String mobile)
throws InvalidNameException, InvalidEmailException, InvalidMobileNumberException {
if (firstName.contains(" ") || lastName.contains(" ")) {
throw new InvalidNameException("First name or last name should not contain spaces.");
}
if (!email.endsWith("@aust.edu")) {
throw new InvalidEmailException("Email must end with '@aust.edu'.");
}
if (!mobile.startsWith("+8801")) {
throw new InvalidMobileNumberException("Mobile number must start with '+8801'.");
}
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
this.mobile = mobile;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Taking user input for student details
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine(); // consume the newline
System.out.print("Enter Email: ");
String email = scanner.nextLine();
System.out.print("Enter Mobile: ");
String mobile = scanner.nextLine();
// Create a Student object with the input data
Student student = new Student(firstName, lastName, age, email, mobile);
System.out.println("Student information successfully recorded!");
} catch (InvalidNameException | InvalidEmailException | InvalidMobileNumberException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}
'
// Base class Fan
abstract class Fan {
String brand;
int speed;
public Fan(String brand) {
this.brand = brand;
}
// Common method for setting speed
public void setSpeed(int speed) {
this.speed = speed;
System.out.println(brand + " fan speed set to " + speed);
}
// Abstract method to be overridden by subclasses
public abstract void displayFanType();
}
// CeilingFan class
class CeilingFan extends Fan {
public CeilingFan(String brand) {
super(brand);
}
@Override
public void displayFanType() {
System.out.println("This is a ceiling fan.");
}
}
// StandFan class
class StandFan extends Fan {
boolean hasOscillation;
public StandFan(String brand, boolean hasOscillation) {
super(brand);
this.hasOscillation = hasOscillation;
}
@Override
public void displayFanType() {
System.out.println("This is a stand fan with oscillation: " + hasOscillation);
}
}
// DeskFan class
class DeskFan extends Fan {
public DeskFan(String brand) {
super(brand);
}
@Override
public void displayFanType() {
System.out.println("This is a desk fan.");
}
}
// TowerFan class
class TowerFan extends Fan {
public TowerFan(String brand) {
super(brand);
}
@Override
public void displayFanType() {
System.out.println("This is a tower fan.");
}
}
// PedestalFan class
class PedestalFan extends StandFan {
public PedestalFan(String brand, boolean hasOscillation) {
super(brand, hasOscillation);
}
@Override
public void displayFanType() {
System.out.println("This is a pedestal fan.");
}
}
// Example usage
public class FanSystem {
public static void main(String[] args) {
Fan ceilingFan = new CeilingFan("XYZ");
ceilingFan.setSpeed(3);
ceilingFan.displayFanType();
Fan standFan = new StandFan("ABC", true);
standFan.setSpeed(2);
standFan.displayFanType();
}
}
Setter methods are not necessary if a class already has a constructor.
No, I disagree with the statement. Setter methods are still necessary even if a class has a constructor. A constructor initializes the object when it is created, but setter methods are useful for modifying object properties after instiation. This provides flexibility for changing values at runtime.
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Setter method
public void setAge(int age) {
this.age = age;
}
}
in the above example, the setAge() method can be used to modify the age of a Person object after it has been created, which is not possible with just a constructor.
Describe a scenario where the unreachable code error will happen while handling exceptions, how is it possible to solve?
An unreachable code error occurs when there is code that will never be executed such as code placed after a return, throw or within a try block when there is a finally block with a return.
public int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
return 0;
}
System.out.println("This code is unreachable"); // Unreachable code
}
in the above code, the statement after the try-catch block is unreachable because tehre is a return statement inside the catch block.
Solution: To solve this, ensure there is no code after a return or a similiar statement, or restructure the code so that it can be executed in all scenerios.
Describe a scenario where the join method is required to be used.
The join method is used when one thread needs to wait for the completion of another thread before proceeding.
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 is running");
});
Thread thread2 = new Thread(() -> {
try {
thread1.join(); // Ensure thread1 completes before running thread2
System.out.println("Thread 2 is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
How does encapsulation ensure the security of a class, explain with example?
Encapsulation ensures the security of a class by restricting direct access to its data and providing controlled ways to modify it using access modifiers(private, public etc)
public class BankAccount {
private double balance;
// Constructor
public BankAccount(double initialBalance) {
balance = initialBalance;
}
// Getter method
public double getBalance() {
return balance;
}
// Setter method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
in the BankAccount example, the balance variable is private, ensuring that it cannot be directly accessed or modified by external classes. Instead, the deposit method provides controlled access, allowing only valid deposits.
Consider the following piece of code and assume the student is a class having a proper constructors and Boolean equals(Object o) method that is overridden to compare the equalities of the values of two student objects.
Student s1 = new Student("Abdul Karim", "02-11-2003", "20200204003");
Student s2 = new Student(p1);
p1.equals(p2): This expression will evaluate to true if the equals() method is overridden in the Student class to compare the values of the fields of Student objects. It compares the content/ attributes of p1 and p2. Since s2 was initialized with s1, assuming equals() compares relevant fields correctly, p1.equals(p2) will return true.
p1==p2: This expression will evaluate to false because == compares references, not values. p1 and p2 are two different objects, even if they have the same content there fore their memory addresses are different, resulting in false.
// Base Phone class
abstract class Phone {
String callerName;
public Phone(String callerName) {
this.callerName = callerName;
}
abstract void receiveCall();
}
// Feature Phone class
class FeaturePhone extends Phone {
public FeaturePhone(String callerName) {
super(callerName);
}
@Override
void receiveCall() {
System.out.println("Receiving call from: " + callerName);
...
java-theory-notes-short-ver
Explain inheritance principles with a real life example:
Inheritance: It is the mechanism by which one class is allowed to inherit features of another class. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the members defined by the superclass and adds its own unique elements.
Describe the task of public, private and protected access modifiers with examples:
Public access modifier: When public access modifier is used, the classes, methods etc can be accessed from everywhere in the program.
public class A{
public void print()
{
System.out.println("Java");
}
}
public class B {
public static void main(String[] args){
A a=new A();
a.print;
}
}
private access modifier: When any class, method, variable etc is declared with private access modifier, it is accessible only inside that particular class unless getter-setter is used.
class A{
private void print()
{
System.out.println("Java");
}
}
these print() method is not accessible from any other class than A
Protected access modifier: When protected is used, only the subclass can access the data. Protected is pretty similar to private but used for inheritance purpose to let subclass access the data while other classes cannot.
class A{
protected void print()
{
System.out.println("Java");
}
}
class B extends A {
public static void main(String[] args){
B b=new B();
b.print();
}
}
Here, subclass B can access the method print() from it's superclass A as it is protected and B is A's subclass
Why main() method is declared as public and staticx2
Java specified several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessed from outside of that class, since the main() method is public in Java, JVM can easily access and execute it.
The main() method is declared static so that JVM can call it without creating an instance of the class containing the main() method. So that is why the main() method has to be static and public so that JVM can access and load the class into memory and call the main() method.
Describe a scenario in natural language that could exploit the concept of java interface? Write down java code for your described scenario
How a java program is platform independent
The meaning of platform independent is that the java compiled code(byte code) can run on all operating system.
In windows, if we compile a java code into byte code, and then compile the byte code in other operating system(Linux, mac), it will run and execute the code(.exe)
So, java is a platform independent language.
Why is it not possible to make an object of an abstract class
An abstract class is not complete. It is sort of a template or a structure. But objects are concrete. An abstract class can be extended and used before it can be used from other classes but it itself cannot initialize objects.
Why an exception handling approach is preferable than a if else if else approach
when the finally block is used? Provide a scenario in natural language for a proper explanation
A "finally" block is used after try-catch block. It executes no matter if an exception is handled or not.
public class demo {
public static void main(String[] args){
try{
int[] a=new a[]{1,2,3};
System.out.println(a[6]);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
finally{
System.out.println("program ended");
}
}
}
Describe the life cycle of a thread in javax3
Life cycle of thread in java is basically state transitions of a thread that starts from its birth and ends on its death.
When an instance of a thread is created and is executed by calling start() method of thread class, the thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnable state.
Explain with an example the purpose of join() method in a multi threading environment
The join() method in a multi threading environment waits for a thread to die. It causes the currently running threads to stop executing until the thread it joins with completes it tasks.
Describe the 3 basic principle of OOP with practical examples
The three principles of OOP:
1.Encapsulation: The process of binding data and code together is called encapsulation. It can be used as a protective shield that prevents the data from being accessed by code outside its shield.
-
Inheritance: It is a mechanism by which one class can inherit the features of another class.
-
Polymorphism: It is the mechanism that allows multiple method declaration. It allows method overloading and method overriding.
Explain the purpose of using constructors with examples:
A constructor is a special method of a class that initialize new objects or instances of the class. Without a constructor, we cannot create instances of the class and cannot initialize objects.
Why is a constructor important?Should a programmer use no argument constructor or a parametrized constructor or both? Provide proper arguments to support your opinion)x2
A constructor is a special method of a class that initialize new objects or instances of the class. Without a constructor, we cannot create instances of the class and cannot initialize objects.
A programmer should use both parameterless constructor and parametrized constructor. A parametrized constructor is written by the programmer but if we forget to use it then the compiler itself creates a default constructor with no arguments. Besides, if we do not assign a parametrized constructor we will not be able to create an instance object and so problems will arise.
Why is exception hierarchy important when dealing with multiple catch blocks? Support your opinion with an example
Describe a scenario (describe the scenario in natural language) where it is required to use synchronized methods in a multi threading environment. Provide arguments to justify the use of the synchronized method.
What are the uses of 'final' keyword
"Final" keyword is used to prevent a class from being inherited. If we use "Final" keyword before the name of the class, no other class can inherit that class. If we use final keyword before any variable, we cannot change/reassign the value of the variable. If we use the "Final" keyword before any method, we cannot override that method.
Explain the usage of final, finally and finalize
"Final" keyword is used to prevent a class from being inherited. If we use "Final" keyword before the name of the class, no other class can inherit that class. If we use final keyword before any variable, we cannot change/reassign the value of the variable. If we use the "Final" keyword before any method, we cannot override that method.
A "finally" block is used after try-catch block. It executes no matter if an exception is handled or not.It ensures that a section of code is always executed, even if an exception is thrown.
"finalize" is a method in java used to perform cleanup processing on an object before it is garbage collected.
Explain the concept of checked exceptions with a real life example
Exception that occurs at the compile time are called as compile time exception/checked exceptions. These cannot simply be ignored at the time of compilation and the programmer has to handle these exception.
public class demo {
public static void main(String[] args){
try{
int[] a=new a[]{1,2,3};
a[6]=7;
System.out.println(a[6]);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
Both abstract class and interface have abstract methods but it depends on different scenerios where to use abstract class or the interface, describe two different scenerios to justift the use of two different concepts
What are the uses of 'this' keyword
"This" keyword can be used inside any method to refer to the current object. Every object can access a reference to itself with "this". "This" keyword is used to resolve name-space collisions.
Describe method overriding with an example
Wat is polymorphism? what are the ways in which oop implements polymorphism
Polymorphism is a mechanism that is allows multiple method declaration. It allows method overloading and method overriding.
What are the differences between final and static variables? Apply the concepts to a scenario
Explain the purpose of using constructors with examples
A constructor is a special method of a class that is used to initialize object or instances of the class. Without constructors, we cannot create instances of the class and cannot initialize object.
Explain the join() method with an example
The join() method in a multithreading environment waits for a thread to die. It causes the currently running threads to stop executing until the thread it joins with completes its task.
When the finally block is used? Provide a scenario in natural language for a proper explanation
A "finally" block is used after try-catch block. It executes no matter if an exception is handled or not.
public class demo {
public static void main(String[] args){
try{
int[] a=new a[]{1,2,3};
System.out.println(a[6]);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
finally{
System.out.println("program ended");
}
}
}
Why an exception handling approach is preferable than a if-else approach
In case of exception...