interview deck 1 Flashcards

1
Q

What are the important differences between C++ and Java?

A
  1. Java is platform independent. C++ is not platform independent.
  2. Java & C++ are both NOT pure Object Oriented Languages. However, Java is more purer Object
    Oriented Language (except for primitive variables). In C++, one can write structural programs
    without using objects.
  3. C++ has pointers (access to internal memory). Java has no concept called pointers.
  4. In C++, programmer has to handle memory management. A programmer has to write code to
    remove an object from memory. In Java, JVM takes care of removing objects from memory
    using a process called Garbage Collection.
  5. C++ supports Multiple Inheritance. Java does not support Multiple Inheritance.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the role of a ClassLoader in Java?

A

A Java program is made up of a number of custom classes (written by programmers like us) and core
classes (which come pre-packaged with Java). When a program is executed, JVM needs to load the
content of all the needed classes. JVM uses a ClassLoader to find the classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are wrapper classes?

A

A brief description is provided below.
A primitive wrapper class in the Java programming language is one of eight classes provided in the
java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper
classes in Java are immutable.
Wrapper: Boolean, Byte, Character, Double, Float, Integer,Long, Short
Primitive: boolean, byte,char, double, float, int, long, short

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why do we need Wrapper Classes in Java?

A

A wrapper class wraps (encloses) around a data type and gives it an object appearance.
Reasons Why We Need Wrapper Classes
* null is a possible value
* use it in a Collection
* Methods that support Object creation from other types.. like String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the different ways of creating Wrapper Class Instances?

A

Two ways of creating Wrapper Class Instances are described below.
Using a Wrapper Class Constructor
Integer number = new Integer(55);//int
Integer number2 = new Integer(“55”);//String
Float number3 = new Float(55.0);//double argument
Float number4 = new Float(55.0f);//float argument
Float number5 = new Float(“55.0f”);//String
Java Interview Questions and Answers – www.in28Minutes.com 15
Character c1 = new Character(‘C’);//Only char constructor
//Character c2 = new Character(124);//COMPILER ERROR
Boolean b = new Boolean(true);
//”true” “True” “tRUe” - all String Values give True
//Anything else gives false
Boolean b1 = new Boolean(“true”);//value stored - true
Boolean b2 = new Boolean(“True”);//value stored - true
Boolean b3 = new Boolean(“False”);//value stored - false
Boolean b4 = new Boolean(“SomeString”);//value stored - false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Auto Boxing?

A

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and
their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is called unboxing.

Example 1
Integer nineC = 9;

Example 2
Integer ten = new Integer(10);
ten++; //allowed. Java does the hard work behind the screen for us

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is Implicit Casting?

A

Implicit Casting is done by the compiler.
Good examples of implicit casting are all the automatic widening
conversions i.e. storing smaller values in larger variable types.

int value = 100;
long number = value; //Implicit Casting
float f = 100; //Implicit Casting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Explicit Casting?

A

Explicit Casting is done through code. Good examples of explicit casting are the narrowing conversions.

Storing larger values into smaller variable types;
long number1 = 25678;
int number2 = (int)number1;//Explicit Casting
//int x = 35.35;//COMPILER ERROR
int x = (int)35.35;//Explicit Casting

Explicit casting would cause truncation of value if the
int bigValue = 280;
byte small = (byte) bigValue;
System.out.println(small);//output 24. Only 8 bits remain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Are all String’s immutable?

A

Value of a String Object once created cannot be modified. Any modification on a String object creates a
new String object.

String str3 = “value1”;
str3.concat(“value2”);

System.out.println(str3); //value1

Note that the value of str3 is not modified in the above example. The result should be assigned to a new reference variable (or the same variable can be reused).

All wrapper class instances are immutable too!
String concat = str3.concat(“value2”);
System.out.println(concat); //value1value2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the differences between String and StringBuffer?

A
  • Objects of type String are immutable. StringBuffer is used to represent values that can be
    modified.
  • In situations where values are modified a number to times, StringBuffer yields significant performance benefits.
  • Both String and StringBuffer are thread-safe.
  • StringBuffer is implemented by using synchronized keywords on all methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a Class?

A

A class is a Template. In above example, Class CricketScorer is the template for creating multiple
objects. A class defines state and behavior that an object can exhibit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is an Object?

A

An instance of a class. In the above example, we create an object using the new CricketScorer(). The
reference of the created object is stored in the scorer variable. We can create multiple objects of the same
class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the superclass of every class in Java?

A

Every class in Java is a subclass of the class Object. When we create a class we inherit all the methods
and properties of Object class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the hashCode method used for in Java?

A

Hashcodes are used in hashing to decide which group (or bucket) an object should be placed into. A
group of objects might share the same hashcode.
The implementation of hash code decides the effectiveness of hash. A good hashing function evenly
distributes objects into different groups (or buckets).

A good hashCode method should have the following properties
* If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode()

  • obj.hashCode() should return the same value when run multiple times, if the values of obj used in equals() have not changed.
  • If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Method Overloading?

A

A method having the same name as another method (in the same class or a sub-class) but having a different
parameters is called an Overloaded Method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Method Overriding?

A

Creating a Sub Class Method with the same signature as that of a method in SuperClass is called Method Overriding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Is Multiple Inheritance allowed in Java?

A

Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is an Interface?

A
  • An interface defines a contract for responsibilities (methods) of a class.
  • An interface is a contract: the guy writing the interface says, “hey, I accept things looking that way”
  • Interface represents common actions between Multiple Classes.
  • Example in Java api: Map interface, Collection interface.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you define an Interface?

A

An interface is declared by using the keyword interface. Look at the example below: Flyable is an
interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you implement an interface?

A

We can define a class implementing the interface by using the implements keyword. Let us look at a
couple of examples:
Example 1
Class Aeroplane implements Flyable and implements the abstract method fly().
public class Aeroplane implements Flyable{

@Override
public void fly() {
System.out.println(“Aeroplane is flying”);
}
}

Example 2

public class Bird implements Flyable{
@Override
public void fly() {
System.out.println(“Bird is flying”);
}
}

Variables in an interface are always public, static, final. Variables in an interface cannot be declared
private.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Can a class extend multiple interfaces?

A

A class can implement multiple interfaces. It should implement all the method declared in all Interfaces
being implemented.
An example of a class in the JDK that implements several interfaces is HashMap, which implements the
interfaces Serializable, Cloneable, and Map. By reading this list of interfaces, you can infer that an
instance of HashMap (regardless of the developer or company who implemented the class) can be
cloned, is serializable (which means that it can be converted into a byte stream; see the section
Serializable Objects), and has the functionality of a map.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an Abstract Class?

A

An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may
be fully implemented, but is more usually partially implemented or not implemented at all, thereby
encapsulating common functionality for inherited classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When do you use an Abstract Class?

A

component, use an abstract class. Abstract classes allow you to partially implement your class.
* An example of an abstract class in the JDK is AbstractMap, which is part of the Collections
Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share
many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap
defines.
o example abstract method : public abstract Set> entrySet();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you define an abstract method?

A

An Abstract method does not contain a body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub-class.
//Abstract Class can contain 0 or more abstract methods
//Abstract method does not have a body

abstract void abstractMethod1();
abstract void abstractMethod2();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Compare Abstract Class vs Interface?

A

Syntactical Differences
* Methods and members of an abstract class can have any visibility. All methods of an interface
must be public.
* A concrete child class of an Abstract Class must define all the abstract methods. An Abstract
child class can have abstract methods. An interface extending another interface need not provide
default implementation for methods inherited from the parent interface.
* A child class can only extend a single class. An interface can extend multiple interfaces. A class
can implement multiple interfaces.
* A child class can define abstract methods with the same or less restrictive visibility, whereas a
class implementing an interface must define all interface methods as public

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is a Constructor?

A

Constructoris invoked whenever we create an instance(object) of a Class. We cannot create an object
without a constructor.
Constructor has the same name as the class and no return type. It can accept any number of parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a Default Constructor?

A

Default Constructor is the constructor that is provided by the compiler. It has no arguments. In the
example below, there are no Constructors defined in the Animal class. Compiler provides us with a
default constructor, which helps us create an instance of animal class.

public class Animal {
String name;
public static void main(String[] args) {
// Compiler provides this class with a default no-argument
//constructor.
// This allows us to create an instance of Animal class.
Animal animal = new Animal();
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Will this code compile?

class Animal {
String name;
public Animal() {
this.name = “Default Name”;
}
// This is called a one argument constructor.
public Animal(String name) {
this.name = name;
}

public static void main(String[] args) {
Animal animal = new Animal();
}
}

A

The answer is no. Since we provided a constructor, the compiler does not provide a default constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Is a super class constructor called even when there is no explicit call from a sub class constructor?

A

If a super class constructor is not explicitly called from a sub class constructor, super class (no argument)
constructor is automatically invoked (as first line) from a sub-class constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is Polymorphism?

A

Polymorphism is defined as “Same Code” giving “Different Behavior”. Let’s look at an example.

Let’s define an Animal class with a method shout.
public class Animal {
public String shout() {
return “Don’t Know!”;
}
}

Let’s create two new sub-classes of Animal overriding the existing shout method in Animal.

class Cat extends Animal {
public String shout() {
return “Meow Meow”;
}
}

class Dog extends Animal {
public String shout() {
return “BOW BOW”;
}

public void run(){
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is Coupling?

A

Coupling is a measure of how much a class is dependent on other classes. There should minimal
dependencies between classes. So, we should always aim for low coupling between classes.

32
Q

What is an Inner Class?

A

Inner Classes are classes which are declared inside other classes. Consider the following example:
class OuterClass {
public class InnerClass {
}
public static class StaticNestedClass {
}
}

33
Q

how is java platform independent?

A

Java is platform independent because it uses a virtual machine. The Java Virtual Machine (JVM) is a software program that interprets Java bytecode. Bytecode is a platform-independent intermediate language that is generated when Java source code is compiled.

When a Java program is run, the JVM first loads the bytecode into memory and then interprets it instruction by instruction. The JVM takes care of all the platform-specific details, such as memory management and thread scheduling. This allows Java programs to run on any platform that has a JVM installed.

Here is an example of how Java platform independence works:

  1. A Java program is written in Java source code.
  2. The Java source code is compiled into bytecode using the Java compiler.
  3. The bytecode can be run on any platform that has a JVM installed.
  4. When the bytecode is run, the JVM loads it into memory and interprets it instruction by instruction.
  5. The JVM takes care of all the platform-specific details, such as memory management and thread scheduling.

This means that a Java program can be written once and then run on any platform without having to be recompiled. This is known as Write Once, Run Anywhere (WORA).

Java platform independence is one of the key features that makes it such a popular programming language. It allows Java programs to be run on a wide variety of platforms, including desktop computers, laptops, servers, mobile devices, and embedded systems.

Here are some of the benefits of Java platform independence:

Portability: Java programs can be easily ported to new platforms without having to be recompiled. This makes it easier to develop and deploy cross-platform applications.

Scalability: Java programs can be scaled to run on a wide variety of hardware platforms, from small embedded devices to large mainframes.

Security: Java platform independence helps to improve security by isolating Java programs from the underlying operating system. This makes it more difficult for attackers to exploit vulnerabilities in the operating system to gain access to Java programs.

Overall, Java platform independence is a powerful feature that makes it a versatile and flexible programming language.

34
Q

WHAT IS THE DIFFERENCE BETWEEN CHECKED EXCEPTIONS AND UNCHECKED EXCEPTIONS

A

Checked exceptions and unchecked exceptions are two different types of exceptions in Java. Checked exceptions are those that the compiler forces the programmer to handle, while unchecked exceptions are those that the compiler does not force the programmer to handle.

Checked exceptions are typically used to indicate errors that are caused by the programmer, such as trying to read from a file that does not exist or trying to cast an object to a type that it is not. Unchecked exceptions are typically used to indicate errors that are caused by the runtime environment, such as an out-of-bounds exception or a null pointer exception.

Unchecked exceptions are important because they allow Java programs to be more efficient. By not forcing the programmer to handle unchecked exceptions, the compiler can avoid generating unnecessary code.

35
Q

what is an example of an unchecked exception in java

A

An example of an unchecked exception in Java is the NullPointerException. This exception is thrown when you try to access a null object reference. For example, the following code will throw a NullPointerException:

36
Q

what is an example of a checked exception in java

A

An example of a checked exception in Java is the IOException. This exception is thrown when an error occurs while performing an I/O operation, such as reading from or writing to a file. For example, the following code will throw an IOException if the file my_file.txt does not exist:

Java
File myFile = new File(“my_file.txt”);
FileReader reader = new FileReader(myFile);
Use code with caution. Learn more
This is because the FileReader constructor throws an IOException if the file does not exist.

Other examples of checked exceptions in Java include:

FileNotFoundException
ClassNotFoundException
InterruptedException
SQLException
ParseException
Checked exceptions are checked by the compiler, so you are required to handle them either by using a try-catch block or by declaring the exception using the throws keyword.

37
Q

There are several steps you can take to prepare an application to use the cloud:

A
  1. Identify the workloads that are suitable for the cloud: Start by identifying which parts of your application are suitable for running in the cloud. This might include workloads that are bursty, have unpredictable traffic patterns, or require a large number of resources.
  2. Refactor your application: Depending on the type of cloud you are using, you may need to refactor your application to make it more cloud-friendly. This might include breaking your application into smaller, independently deployable microservices, or redesigning your data model to be more scalable.
  3. Choose a cloud provider: There are many different cloud providers to choose from, each with its own strengths and weaknesses. Consider factors such as the types of services offered, the pricing model, and the level of support and documentation.
  4. Set up a development and test environment: Create a development and test environment that is similar to the production environment you will be using in the cloud. This will allow you to test and debug your application in a realistic setting before deploying it to the cloud.
  5. Set up monitoring and alerting: Set up monitoring and alerting to keep track of the performance and availability of your application in the cloud. This will allow you to quickly detect and resolve any issues that may arise.
  6. Create a deployment process: Establish a repeatable process for deploying your application to the cloud, including any necessary automated testing and rollback procedures. This will help ensure that deployments to the cloud are reliable and consistent.
38
Q

. Can you explain the Spring IoC container and how it works?

A

The Spring IoC container is the core of the Spring Framework. It is responsible for creating, configuring, and assembling objects, known as beans. The IoC container also manages the life cycle of these beans.

The IoC container works by reading a configuration file, which describes the beans that the container should create. The configuration file can be in XML or Java format.

Once the IoC container has read the configuration file, it creates an instance of each bean and configures it according to the instructions in the configuration file. The IoC container also resolves any dependencies between the beans.

Once all of the beans have been created and configured, the IoC container makes them available to the application code. The application code can then access the beans by name.

The Spring IoC container uses a variety of techniques to implement IoC, including:

Dependency injection: The IoC container injects the dependencies of a bean into the bean itself. This means that the bean does not need to know how to create or obtain its dependencies.
Bean scopes: The IoC container manages the scope of each bean. The scope of a bean determines how long the bean lives and how it is shared between different parts of the application.
Bean life cycle callbacks: The IoC container allows beans to register callbacks that are executed at different stages of the bean’s life cycle, such as when the bean is created, initialized, or destroyed.
The Spring IoC container provides a number of benefits, including:

Loose coupling: The IoC container helps to decouple the components of an application. This makes the application easier to maintain and test.
Testability: The IoC container makes it easier to test the components of an application in isolation.
Reusability: The IoC container allows beans to be reused in different parts of an application. This can reduce the amount of code that needs to be written and maintained.
Overall, the Spring IoC container is a powerful tool that can help to simplify the development and maintenance of Java applications.

Here is an example of how to use the Spring IoC container to create and inject a bean into another bean:

Java
// Create a bean definition for the MyBean class.
@Bean
public MyBean myBean() {
return new MyBean();
}

// Create a bean definition for the MyService class.
@Bean
public MyService myService(MyBean myBean) {
return new MyService(myBean);
}

39
Q

Can you explain the Spring IoC container and how it works?

A

The Spring IoC container is the core of the Spring Framework. It is responsible for creating, configuring, and assembling objects, known as beans. The IoC container also manages the life cycle of these beans.

The IoC container works by reading a configuration file, which describes the beans that the container should create. The configuration file can be in XML or Java format.

Once the IoC container has read the configuration file, it creates an instance of each bean and configures it according to the instructions in the configuration file. The IoC container also resolves any dependencies between the beans.

Once all of the beans have been created and configured, the IoC container makes them available to the application code. The application code can then access the beans by name.

The Spring IoC container uses a variety of techniques to implement IoC, including:

Dependency injection: The IoC container injects the dependencies of a bean into the bean itself. This means that the bean does not need to know how to create or obtain its dependencies.
Bean scopes: The IoC container manages the scope of each bean. The scope of a bean determines how long the bean lives and how it is shared between different parts of the application.
Bean life cycle callbacks: The IoC container allows beans to register callbacks that are executed at different stages of the bean’s life cycle, such as when the bean is created, initialized, or destroyed.
The Spring IoC container provides a number of benefits, including:

Loose coupling: The IoC container helps to decouple the components of an application. This makes the application easier to maintain and test.
Testability: The IoC container makes it easier to test the components of an application in isolation.
Reusability: The IoC container allows beans to be reused in different parts of an application. This can reduce the amount of code that needs to be written and maintained.
Overall, the Spring IoC container is a powerful tool that can help to simplify the development and maintenance of Java applications.

Here is an example of how to use the Spring IoC container to create and inject a bean into another bean:

40
Q

Can you explain the difference between @Controller and @RestController in Spring MVC?

A

The @Controller and @RestController annotations are both used to define controllers in Spring MVC. However, there is a key difference between the two annotations:

@Controller: This annotation is used to define controllers that return views.
@RestController: This annotation is used to define controllers that return JSON or other types of data directly.
In other words, @Controller controllers are typically used to render HTML pages, while @RestController controllers are typically used to develop REST APIs.

Here is an example of a @Controller class:

Java
@Controller
public class MyController {

@GetMapping(“/index”)
public String index() {
return “index”;
}
}
Use code with caution. Learn more
This controller will render the index.html view when the user visits the /index URL.

Here is an example of a @RestController class:

Java
@RestController
public class MyRestController {

@GetMapping(“/api/users”)
public List<User> getUsers() {
return userService.getAllUsers();
}
}
Use code with caution. Learn more
This controller will return a list of User objects in JSON format when the user visits the /api/users URL.</User>

In general, it is best to use the @RestController annotation for controllers that develop REST APIs. This is because the @RestController annotation automatically sets the @ResponseBody annotation on all methods, which tells Spring MVC to return the method’s return value directly in the HTTP response.

However, there are some cases where you may want to use the @Controller annotation. For example, you may want to use the @Controller annotation if you need to render a view that is not in JSON format, such as an HTML page or a PDF file.

Overall, the @Controller and @RestController annotations are both powerful tools that can be used to develop controllers in Spring MVC. The best annotation to use depends on the specific needs of your application.

41
Q
  1. How do you use AOP in a Spring application?
A

o use AOP in a Spring application, you can follow these steps:

Add the Spring AOP dependency to your pom.xml file.
XML

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.22</version>
</dependency>

Use code with caution. Learn more
Define an aspect.
An aspect is a class that contains the advice code that you want to execute at join points in your application. Aspects are annotated with the @Aspect annotation.

Here is an example of an aspect that logs the execution time of all methods in a class:

Java
@Aspect
public class ExecutionTimeAspect {

@Around(“@within(org.example.aop.LogExecutionTime)”)
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();

Object result = joinPoint.proceed();

long endTime = System.currentTimeMillis();

System.out.println(joinPoint.getSignature().getName() + ": " + (endTime - startTime) + "ms");

return result;   } } Use code with caution. Learn more Apply the aspect to your application. You can apply an aspect to your application by annotating a class or method with the @Aspect annotation. You can also use the @EnableAspectJAutoProxy annotation to enable Spring AOP auto-proxying.

Here is an example of how to apply the ExecutionTimeAspect aspect to all methods in the MyService class:

Java
@Service
@Aspect
public class MyService {

public void doSomething() {
// …
}
}
Use code with caution. Learn more
Use the aspect.
Once you have defined and applied an aspect, you can use it in your application by simply calling the methods that are advised by the aspect.

For example, to log the execution time of the doSomething() method in the MyService class, you would simply call the doSomething() method:

Java
MyService myService = new MyService();
myService.doSomething();
Use code with caution. Learn more
Spring AOP will automatically execute the logExecutionTime() advice before and after the doSomething() method is executed.

This is just a simple example of how to use AOP in a Spring application. AOP can be used to implement a variety of cross-cutting concerns, such as logging, transaction management, and security.

Here are some additional tips for using AOP in Spring applications:

Use the @AspectJAutoProxy annotation to enable Spring AOP auto-proxying. This will automatically create proxies for your beans that implement the @Aspect annotation.
Use pointcuts to target the specific join points where you want to execute your advice.
Use different types of advice to implement different types of cross-cutting concerns.
Be careful not to overuse AOP, as it can add complexity to your application.
Overall, AOP is a powerful tool that can help you to write better and more maintainable Spring applications.

Sources
github.com/minibeit/minibeit
github.com/Evgeny268/spring-aop-example

42
Q

Can you explain the difference between Spring Boot and the Spring framework?

A

Spring Boot is a framework that builds on top of the Spring framework to provide a faster and more efficient way to develop Spring applications. Spring Boot provides a number of features that make it easier to get started with Spring, including:

Automatic configuration: Spring Boot can automatically configure many common Spring features, such as data access, web servers, and messaging. This can save you a lot of time and effort when configuring your Spring application.
Starters: Spring Boot provides a number of starters, which are pre-configured dependencies that you can add to your project to get started with popular Spring features, such as Spring MVC, Spring Data JPA, and Spring Security.
Actuator: Spring Boot Actuator provides a number of endpoints that you can use to monitor and manage your Spring application.
Here is a table that summarizes the key differences between Spring Boot and the Spring framework:

Feature Spring Boot Spring Framework
Automatic configuration Yes No
Starters Yes No
Actuator Yes No
Learning curve Easier Steeper
Best suited for Rapid application development Enterprise applications

Overall, Spring Boot is a good choice for developing Spring applications, especially if you are new to Spring or if you want to get started quickly. Spring Boot is also a good choice for developing rapid application development (RAD) applications.

The Spring framework is a good choice for developing enterprise applications, as it provides a wide range of features and capabilities. However, the Spring framework can be more complex to learn and use than Spring Boot.

If you are not sure which framework to choose, I recommend starting with Spring Boot. Spring Boot is a good way to learn about the Spring framework and to develop Spring applications quickly and easily.

43
Q

Can you explain the difference between a @Component, @Repository, and @Service in Spring?

A

The @Component, @Repository, and @Service annotations are all used to define components in Spring. However, there is a subtle difference between the three annotations:

@Component: This annotation is used to define a general-purpose component.
@Repository: This annotation is used to define a component that interacts with data storage.
@Service: This annotation is used to define a component that provides business logic.
In other words, the @Component annotation is the most generic of the three annotations. It can be used to define any type of component, including repositories, services, and other types of components.

The @Repository and @Service annotations are more specialized. The @Repository annotation is used to define components that interact with data storage, such as databases and file systems. The @Service annotation is used to define components that provide business logic, such as processing data and validating input.

Here is an example of a @Component class:

Java
@Component
public class MyComponent {

public void doSomething() {
// …
}
}
Use code with caution. Learn more
This class is a general-purpose component that can be used for any purpose.

Here is an example of a @Repository class:

Java
@Repository
public class MyRepository {

public void save(MyEntity entity) {
// …
}

public MyEntity findById(Long id) {
// …
}
}
Use code with caution. Learn more
This class is a repository that interacts with the database to save and retrieve MyEntity objects.

Here is an example of a @Service class:

Java
@Service
public class MyService {

@Autowired
private MyRepository myRepository;

public void processMyEntity(MyEntity entity) {
// …
}
}
Use code with caution. Learn more
This class is a service that provides business logic for processing MyEntity objects.

In general, it is best to use the most specific annotation possible. For example, if you are defining a component that interacts with data storage, you should use the @Repository annotation. If you are defining a component that provides business logic, you should use the @Service annotation.

However, there are some cases where you may want to use the @Component annotation instead of the @Repository or @Service annotation. For example, you may want to use the @Component annotation if you are defining a component that does not fit neatly into either of the other two categories.

Overall, the @Component, @Repository, and @Service annotations are all powerful tools that can be used to define components in Spring. The best annotation to use depends on the specific needs of your application.

44
Q

How do you use the Spring Data JPA to create a repository?

A

To create a repository using Spring Data JPA, you can follow these steps:

Define a domain class that represents the data that you want to store.
Define a repository interface that extends the JpaRepository interface. The repository interface should specify the domain class and the ID type.
Annotate the repository interface with the @Repository annotation.
Spring Boot will automatically create a proxy implementation of the repository interface.
Here is an example of a domain class:

Java
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

public Customer() {
}

public Customer(Long id, String name) {
this.id = id;
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return “Customer{“ +
“id=” + id +
“, name=’” + name + ‘'’ +
‘}’;
}
}
Use code with caution. Learn more
Here is an example of a repository interface:

Java
public interface CustomerRepository extends JpaRepository<Customer, Long> {

}
Use code with caution. Learn more
Here is an example of how to use the repository interface:

Java
@Autowired
private CustomerRepository customerRepository;

public void doSomething() {
// Save a customer.
Customer customer = new Customer(“John Doe”);
customerRepository.save(customer);

// Find a customer by ID.
Customer foundCustomer = customerRepository.findById(1L).get();

// Delete a customer by ID.
customerRepository.deleteById(1L);

// Find all customers.
List<Customer> customers = customerRepository.findAll();
}
Use code with caution. Learn more
This is just a simple example of how to use Spring Data JPA to create a repository. Spring Data JPA provides a number of other features, such as support for sorting and filtering data, creating custom queries, and lazy loading.</Customer>

If you are developing Java applications, I encourage you to learn more about Spring Data JPA. It is a powerful tool that can help you to write better and more maintainable code for interacting with data.

45
Q

What is the difference between an interface and an abstract class?

A

1
Interfaces and abstract classes are both concepts in object-oriented programming that allow you to define a set of methods that must be implemented by any class that inherits from them. However, there are some key differences between the two:

Interfaces can only contain abstract methods (methods without a body). Abstract classes can contain abstract methods, but they can also contain concrete methods (methods with a body).
Interfaces cannot have any instance variables, while abstract classes can.
Interfaces can be multiple-inherited, while abstract classes can only be single-inherited.
In general, interfaces are used to define a set of behaviors that a class must implement, while abstract classes are used to provide a partial implementation of a class that can be extended by other classes.

Here is an example of an interface:

Java
public interface Animal {

void eat();

void sleep();
}
Use code with caution. Learn more
This interface defines two methods, eat() and sleep(), that any class that implements the interface must implement.

Here is an example of an abstract class:

Java
public abstract class Dog {

private String name;

public Dog(String name) {
this.name = name;
}

public String getName() {
return name;
}

public abstract void bark();
}
Use code with caution. Learn more
This abstract class defines one concrete method, getName(), and one abstract method, bark(). Any class that inherits from this abstract class must implement the bark() method.

Here is an example of a class that implements the Animal interface and inherits from the Dog abstract class:

Java
public class Poodle extends Dog implements Animal {

public Poodle(String name) {
super(name);
}

@Override
public void eat() {
System.out.println(“The poodle is eating.”);
}

@Override
public void sleep() {
System.out.println(“The poodle is sleeping.”);
}

@Override
public void bark() {
System.out.println(“The poodle barks: Woof!”);
}
}
Use code with caution. Learn more
This class implements all of the methods required by the Animal interface and the Dog abstract class.

I hope this explanation is helpful. Please let me know if you have any other questions.

46
Q

Can you override a private or static method in Java?

A

No, you cannot override a private or static method in Java.

Private methods are only accessible to the class in which they are defined. This means that they cannot be overridden by subclasses.
Static methods are bound to the class in which they are defined, not to instances of the class. This means that they cannot be overridden by subclasses.
If you try to override a private or static method, you will get a compile-time error.

Here is an example of a compile-time error that you will get if you try to override a private method:

Java
class Parent {
private void myPrivateMethod() {
System.out.println(“This is a private method.”);
}
}

class Child extends Parent {
@Override
public void myPrivateMethod() {
System.out.println(“This is an overridden private method.”);
}
}

47
Q

Can you explain the difference between a static and a non-static inner class in Java?

A

A static inner class is a class that is defined within another class and declared as static. This means that the inner class can be accessed without creating an instance of the outer class.

A non-static inner class, also known as an inner class, is a class that is defined within another class but is not declared as static. This means that the inner class can only be accessed from within the outer class.

Here is an example of a static inner class:

Java
public class OuterClass {

public static class StaticInnerClass {
public void doSomething() {
System.out.println(“This is a static inner class.”);
}
}

public void accessStaticInnerClass() {
OuterClass.StaticInnerClass staticInnerClass = new OuterClass.StaticInnerClass();
staticInnerClass.doSomething();
}
}
Use code with caution. Learn more
This code defines a static inner class called StaticInnerClass within the outer class OuterClass. The StaticInnerClass class can be accessed without creating an instance of the OuterClass class, as shown in the accessStaticInnerClass() method.

Here is an example of a non-static inner class:

Java
public class OuterClass {

public class InnerClass {
public void doSomething() {
System.out.println(“This is an inner class.”);
}
}

public void accessInnerClass() {
OuterClass outerClass = new OuterClass();
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
innerClass.doSomething();
}
}
Use code with caution. Learn more
This code defines a non-static inner class called InnerClass within the outer class OuterClass. The InnerClass class can only be accessed from within the OuterClass class, as shown in the accessInnerClass() method.

Static inner classes are typically used to logically group related utility classes or provide a convenient way of packaging-related functionality.

Non-static inner classes are typically used to implement inner functionality that is specific to the outer class.

For example, a static inner class could be used to implement a helper class that is used by the outer class, while a non-static inner class could be used to implement a listener class that is used to listen for events generated by the outer class.

48
Q

How do you implement a linked list in Java?

A

1
+

3

4

4
To implement a linked list in Java, you can follow these steps:

Create a node class. The node class should have two fields:

value: The data stored in the node.
next: A pointer to the next node in the linked list.
Create a linked list class. The linked list class should have a head pointer, which points to the first node in the linked list.

Implement methods to add, remove, and search for elements in the linked list.

Here is a simple implementation of a linked list in Java:

Java
public class LinkedList<T> {</T>

private Node head;

public void add(T value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}

public void remove(T value) {
if (head == null) {
return;
} else if (head.value.equals(value)) {
head = head.next;
} else {
Node current = head;
Node previous = null;
while (current != null && !current.value.equals(value)) {
previous = current;
current = current.next;
}
if (current != null) {
previous.next = current.next;
}
}
}

public T search(T value) {
Node current = head;
while (current != null) {
if (current.value.equals(value)) {
return current.value;
}
current = current.next;
}
return null;
}

private class Node {

private T value;
private Node next;

public Node(T value) {
  this.value = value;
  this.next = null;
}   } } Use code with caution. Learn more To use the linked list, you can simply create an instance of the LinkedList class and call the add(), remove(), and search() methods to add, remove, and search for elements in the linked list.

For example, the following code shows how to create a linked list of strings and add and remove elements from the list:

Java
LinkedList<String> myList = new LinkedList<>();</String>

myList.add(“Hello”);
myList.add(“World!”);

String removedElement = myList.remove(“Hello”);

System.out.println(removedElement); // Prints “Hello”
System.out.println(myList.search(“World!”)); // Prints “World!”
Use code with caution. Learn more
Linked lists are a powerful data structure that can be used to implement a variety of algorithms and data structures. I encourage you to learn more about linked lists if you are interested in algorithm design and data structures.

Sources
github.com/AlexKievDeveloper/basic_data_structures_implementation_java
github.com/PKpRedeemingTime/DojoAssignments
github.com/peaceglory/JavaRecollection
github.com/foiki/spbu-Homeworks

49
Q

What are the four pillars of object-oriented programming?

A

The four pillars of object-oriented programming are:

Abstraction: Abstraction is the process of hiding unnecessary details and showing only the essential information required to understand the system. It allows us to focus on the important aspects of a system and ignore the unimportant details.

Encapsulation: Encapsulation is the process of wrapping data and behavior together into a single unit called an object. It protects the data from unauthorized access and modification.

Inheritance: Inheritance is the ability of a class to inherit the properties and behavior of another class. It allows us to reuse code and create new classes without having to start from scratch.

Polymorphism: Polymorphism is the ability of an object to take on many forms. It allows us to write code that is more flexible and reusable.
These four pillars are the foundation of object-oriented programming and are used to develop modular, reusable, and maintainable code.

Here are some examples of the four pillars of object-oriented programming in Java:

Abstraction: The Animal class in Java abstracts away the details of specific animals and only exposes the essential information, such as the animal’s name and what it eats.

Encapsulation: The Customer class in Java encapsulates the customer’s data, such as their name, address, and phone number. This data can only be accessed and modified through the methods of the Customer class.

Inheritance: The Dog class in Java inherits from the Animal class. This means that the Dog class has all of the properties and behavior of the Animal class, plus any additional properties and behavior that it defines.

Polymorphism: The speak() method in the Animal class is polymorphic. This means that different animals can implement the speak() method in different ways. For example, a dog might bark, while a cat might meow.

Object-oriented programming is a powerful paradigm that can be used to develop a wide variety of software applications. By understanding the four pillars of object-oriented programming, you can write code that is more modular, reusable, and maintainable.

50
Q

What is the difference between a pass-by-value and a pass-by-reference?

A

Pass-by-value and pass-by-reference are two different ways of passing arguments to methods in programming languages.

Pass-by-value means that a copy of the argument is passed to the method. Any changes made to the argument inside the method will not be reflected in the original value of the argument outside the method.

Pass-by-reference means that a reference to the argument is passed to the method. Any changes made to the argument inside the method will be reflected in the original value of the argument outside the method.

Java uses pass-by-value for primitive data types (such as int, double, and boolean) and pass-by-reference for object types.

Here is an example of pass-by-value in Java:

Java
public class PassByValue {

public static void main(String[] args) {
int x = 10;
changeValue(x);
System.out.println(x); // Prints 10
}

private static void changeValue(int value) {
value = 20;
}
}
Use code with caution. Learn more
In this example, the value of the x variable is passed to the changeValue() method by value. This means that a copy of the value of x is passed to the method. The changeValue() method changes the value of the copy of x, but this does not affect the original value of x. Therefore, when the changeValue() method returns, the value of x is still 10.

Here is an example of pass-by-reference in Java:

Java
public class PassByReference {

public static void main(String[] args) {
Customer customer = new Customer(“John Doe”);
changeCustomer(customer);
System.out.println(customer.getName()); // Prints “Jane Doe”
}

private static void changeCustomer(Customer customer) {
customer.setName(“Jane Doe”);
}
}

class Customer {

private String name;

public Customer(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
Use code with caution. Learn more
In this example, the customer object is passed to the changeCustomer() method by reference. This means that a reference to the customer object is passed to the method. The changeCustomer() method changes the name of the customer object. This change is reflected in the original value of the customer object outside the method. Therefore, when the changeCustomer() method returns, the name of the customer object is now “Jane Doe”.

Pass-by-value and pass-by-reference are important concepts to understand when writing Java code. By understanding the difference between the two, you can write code that is more predictable and efficient.

51
Q

Does Java pass by reference or pass by value

A

Java passes by value for all primitive data types and pass by reference for all object types.

Pass-by-value means that a copy of the value is passed to the method. Any changes made to the argument inside the method will not be reflected in the original value of the argument outside the method.

Pass-by-reference means that a reference to the object is passed to the method. Any changes made to the object inside the method will be reflected in the original object outside the method.

52
Q

What is the difference between a map and a set?

A

A map and a set are both data structures that store collections of elements. However, there are some key differences between the two.

A map is a collection of key-value pairs. Each key-value pair consists of a unique key and a value. The key is used to identify the value, and the value is the data that is stored in the map.

A set is a collection of unique elements. Each element in a set must be unique, and the order of the elements in the set is not defined.

Here is an example of a map in Java:

Java
Map<String, Integer> map = new HashMap<>();
map.put(“John Doe”, 30);
map.put(“Jane Doe”, 25);

System.out.println(map.get(“John Doe”)); // Prints 30
System.out.println(map.get(“Jane Doe”)); // Prints 25
Use code with caution. Learn more
In this example, the map contains two key-value pairs: (“John Doe”, 30) and (“Jane Doe”, 25). The key of each key-value pair is a string, and the value of each key-value pair is an integer.

Here is an example of a set in Java:

Java
Set<String> set = new HashSet<>();
set.add("John Doe");
set.add("Jane Doe");</String>

System.out.println(set.contains(“John Doe”)); // Prints true
System.out.println(set.contains(“Jane Doe”)); // Prints true
Use code with caution. Learn more
In this example, the set contains two elements: “John Doe” and “Jane Doe”. The order of the elements in the set is not defined.

Here is a table that summarizes the key differences between maps and sets:

Feature Map Set
Stores Key-value pairs Unique elements
Order Keys are sorted Order of elements is not defined
Allows duplicates No No
Maps and sets are both useful data structures that can be used in a variety of applications. Maps can be used to store data in a key-value format, such as a lookup table or a database. Sets can be used to store unique elements, such as a list of unique users or a set of unique products.

Which data structure you use will depend on your specific needs. If you need to store data in a key-value format, then you should use a map. If you need to store unique elements, then you should use a set.

52
Q

What is Garbage Collection in java

A

Garbage collection in Java is a process that automatically manages the memory allocated to objects. When an object is no longer needed, the garbage collector reclaims the memory that was used by the object. This frees up memory so that it can be used by other objects.

Garbage collection is an important part of Java because it makes it easier to write code. Java programmers do not need to worry about manually managing memory or freeing up memory when objects are no longer needed.

The garbage collector works by tracking all of the objects in the Java Virtual Machine (JVM). When an object is no longer referenced by any other object, the garbage collector knows that the object is no longer needed and can be reclaimed.

The garbage collector runs periodically to reclaim unused memory. However, it is also possible to manually trigger the garbage collector by calling the System.gc() method.

Here are some things to keep in mind about garbage collection in Java:

Garbage collection is automatic, but it is not instantaneous. It may take some time for the garbage collector to reclaim unused memory.
The garbage collector is a complex algorithm, and it is not always possible to predict when it will run.
It is not possible to force the garbage collector to reclaim memory for a specific object.
It is generally not necessary to worry about garbage collection in Java. However, it is important to understand how it works so that you can write code that is efficient and uses memory responsibly.
Here are some tips for writing code that is efficient and uses memory responsibly:

Avoid creating unnecessary objects.
Close resources, such as files and database connections, when you are finished using them.
Avoid holding on to references to objects that are no longer needed.
If you are concerned about garbage collection performance, you can use a number of tools to monitor and profile the garbage collector. These tools can help you to identify any potential problems with garbage collection in your application.

53
Q

What is the difference between the JVM and the JRE, and the JDK?

A

The JVM, JRE, and JDK are all important parts of the Java platform. Here is a brief overview of each:

JVM (Java Virtual Machine): The JVM is a program that executes Java bytecode. It is responsible for loading and running Java bytecode, managing memory, and providing security features.

JRE (Java Runtime Environment): The JRE is a collection of software components that allows Java applications to run. It includes the JVM, as well as other libraries and tools that are needed to run Java applications.

JDK (Java Development Kit): The JDK is a complete development environment for Java. It includes the JRE, as well as tools for developing, compiling, and debugging Java applications.
Here is a table that summarizes the key differences between the JVM, JRE, and JDK:

Component Description
JVM The Java Virtual Machine is a program that executes Java bytecode.
JRE The Java Runtime Environment is a collection of software components that allows Java applications to run.
JDK The Java Development Kit is a complete development environment for Java.
Which component do you need?

If you just want to run Java applications, then you only need the JRE. If you want to develop Java applications, then you need the JDK.

How to install the JVM, JRE, and JDK

You can download the JVM, JRE, and JDK from the Oracle website. Once you have downloaded the installer, simply follow the instructions to install the software.

Conclusion

The JVM, JRE, and JDK are all important parts of the Java platform. The JVM is responsible for executing Java bytecode, the JRE allows Java applications to run, and the JDK is a complete development environment for Java.

Which component you need depends on your specific needs. If you just want to run Java applications, then you only need the JRE. If you want to develop Java applications, then you need the JDK.

53
Q

What is the difference between a static method and a non-static method?

A

A static method is a method that belongs to a class, not to an object of that class. It can be called without creating an instance of the class. A non-static method, also known as an instance method, belongs to an object of a class and can only be called after creating an instance of the class.

Here is an example of a static method in Java:

Java
public class MyClass {

public static int add(int a, int b) {
return a + b;
}
}
Use code with caution. Learn more
This method can be called without creating an instance of the MyClass class:

Java
int sum = MyClass.add(1, 2);
Use code with caution. Learn more
Here is an example of a non-static method in Java:

Java
public class MyClass {

public void print() {
System.out.println(“Hello, world!”);
}
}
Use code with caution. Learn more
This method can only be called after creating an instance of the MyClass class:

Java
MyClass myClass = new MyClass();
myClass.print();
Use code with caution. Learn more
Static methods are often used for utility methods that do not need to access or modify the state of an object. Non-static methods are often used for methods that need to access or modify the state of an object.

Here is a table that summarizes the key differences between static methods and non-static methods:

Feature Static method Non-static method
Called without creating an instance of the class Yes No
Accesses or modifies the state of an object No Yes
When to use static methods

You should use static methods when:

You need to provide a utility method that does not need to access or modify the state of an object.
You need to provide a global constant.
You need to provide a factory method that creates new instances of a class.
When to use non-static methods

You should use non-static methods when:

You need to access or modify the state of an object.
You need to provide a method that is specific to a particular class.
You need to provide a method that overrides a method in a superclass.

54
Q

what is the difference between .equals() vs. == in Java

A

The main difference between .equals() and == in Java is that .equals() compares the values of two objects, while == compares the references to two objects.

.equals() is a method that is defined in the Object class, and it can be overridden by subclasses. This means that you can customize how objects are compared for equality.

== is an operator that is defined in the Java language, and it cannot be overridden. It always compares the references to two objects.
In general, you should use .equals() to compare objects for equality, unless you have a specific reason to do otherwise. This is because .equals() is more flexible and allows you to customize how objects are compared.

Here are some examples of how .equals() and == differ:

55
Q

what is the difference between LinkedList vs ArrayList in Java

A

Both LinkedList and ArrayList are implementations of the List interface in Java. However, they have different underlying implementations, which results in different performance characteristics.

ArrayList uses an array to store its elements. This makes it very efficient for random access to elements in the list. However, it can be slow to insert and delete elements, because it may need to shift the entire array to accommodate the change.

LinkedList uses a linked list to store its elements. This makes it very efficient to insert and delete elements because it only needs to update the links between the nodes in the list. However, it can be slow for random access to elements in the list, because it needs to traverse the list from the beginning to find the desired element.

Here is a table that summarizes the key differences between LinkedList and ArrayList:

56
Q

can constructors be final in Java?

A

constructors cant be overridden so it is pointless to make them final

57
Q

can a constructor be abstract in Java?

A

abstract means that a method has no body and it should be implemented in a child class. But constructors are called implicitly when the new keyword is used. Therefore it needs a body

58
Q

what are the four main principles of Object Oriented Programming

A

The four main principles of Object Oriented Programming (OOP) are:

Abstraction: Abstraction is the process of hiding the internal implementation details of an object and exposing only its essential features to the outside world. This allows us to focus on the high-level functionality of an object without having to worry about how it works internally.

Encapsulation: Encapsulation is the process of bundling together the data and behavior of an object into a single unit. This makes it easier to manage and maintain our code, and it also helps to protect our data from being accidentally modified.

Inheritance: Inheritance allows us to create new classes that inherit the properties and behaviors of existing classes. This allows us to reuse code and to create more complex and sophisticated programs.

Polymorphism: Polymorphism is the ability of objects to take on different forms and behaviors depending on the context. This allows us to write more flexible and extensible code.

59
Q

what is Static vs non-static in Java?

A

a non-static method applies to an individual object and not the class itself
for example, given a cat object with two non-static fields name and age, each cat object can have separate unique age and name values and they don’t conflict with other instantiated objects
non-static methods can never be used without calling them on an object.

60
Q

explain the main method in Java
public static void main(String[] args)

A

a) public, the method needs to be callable from outside the class its written

b) static, a static method is a method that can be called on a class without needing an instance of the class to run against, and this is how the JRE is going to call it.

c) void, means to don’t return anything. void is the return type of the method

d) the method is called main because of convention.

e) String[] args is just the arguments passed into the method.

61
Q

why are there no pointers in java

A

In Java there are references and no pointers. These references point to objects in memory But there is no direct access to these memory locations

62
Q

What is the purpose of the “super” keyword in Java

A

The “super” keyword is used in the methods or constructor of a child class. It refers to the immediate parent class of an object. Super allows us to call a method of parent class from a child class

63
Q

what is the purpose of a static method in java

A

Java provides the feature of static methods to define behavior at a class level. We do not need to create an object of a class to call a static method

64
Q

what is the purpose of a static block

A

a static block in a class is useful for defining static variables.

65
Q

Can you execute a Java program without a main method?

A

no, from Java 7 onwards you need a main method

66
Q

what is the difference between method overloading and method overriding in Java?

A

Method overloading and method overriding are two different concepts in Java.

Method overloading is when two or more methods in the same class have the same name, but different parameters. This allows us to write multiple methods that perform the same basic operation, but on different types of data.

Method overriding is when a subclass defines a method with the same name and signature as a method in its superclass. This allows us to customize the behavior of a method for a specific subclass.

Here is an example of method overloading:

Java
public class MyClass {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {
return a + b;
}
}
Use code with caution. Learn more
The add() method is overloaded because there are two methods with the same name, but different parameters. One method takes two integers as input and returns an integer, while the other method takes two doubles as input and returns a double.

Here is an example of method overriding:

Java
public class Animal {
public void makeSound() {
System.out.println(“Animal sound”);
}
}

public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println(“Woof!”);
}
}
Use code with caution. Learn more
The makeSound() method is overridden in the Dog class. This means that when a Dog object calls the makeSound() method, it will call the overridden method in the Dog class, instead of the makeSound() method in the Animal class.

Key differences between method overloading and method overriding:

Feature Method overloading Method overriding
Occurs in Same class Different classes
Parameters Must be different Must be the same
Return type Can be the same or different Must be the same or
covariant

Access modifiers Can be the same or different Can be the same or
more restrictive
When to use method overloading and method overriding:

Method overloading: Use method overloading to write multiple methods that perform the same basic operation, but on different types of data. This can make your code more readable and maintainable.

Method overriding: Use method overriding to customize the behavior of a method for a specific subclass. This is a key feature of OOP that allows us to write more flexible and extensible code.

67
Q

Can you override a static method in Java

A

No, Java does not allow overriding a static method.

68
Q

It it allowed to mark a method abstract without marking the class abstract.

A

No, The java specification says that if at least one method is abstract then the class is abstract

69
Q

what are modifiers in java?

A

Modifiers in Java are keywords that can be used to change the behavior of classes, methods, and variables. There are two main types of modifiers: access modifiers and non-access modifiers.

Access modifiers control the visibility of classes, methods, and variables. The three access modifiers in Java are:

public: Public classes, methods, and variables are accessible anywhere in the program.

protected: Protected classes, methods, and variables are accessible to classes in the same package and to subclasses in other packages.

private: Private classes, methods, and variables are only accessible to the class in which they are defined.

Non-access modifiers provide other functionality, such as static and final. Some of the most common non-access modifiers are:

static: Static classes, methods, and variables belong to the class itself, rather than to any particular instance of the class.

final: Final classes, methods, and variables cannot be changed once they are initialized.

abstract: Abstract classes and methods cannot be instantiated directly. They must be subclassed and the subclass must implement the abstract methods.

Modifiers can be used in combination to achieve a variety of effects. For example, you can declare a method as public static final to make it accessible to all classes in the program and to prevent it from being changed.

Here are some examples of how modifiers are used in Java:

Java
// Public class
public class MyClass {

// Protected method
protected void myMethod() {
// …
}

// Private variable
private int myField;

// Static method
public static void main(String[] args) {
// …
}

// Final class
public final class MyInnerClass {
// …
}
}
Use code with caution. Learn more
Modifiers are a powerful feature of Java that can be used to improve the readability, maintainability, and security of your code.

70
Q

can an abstract method be final in Java?

A

No. It will be a contrary statement. to mark a method abstract as well as final.

An abstract method has to be overridden by a child and a final method cannot be overridden therefore a method can be either final or abstract but not both.

71
Q

Can you instantiate and abstract class in java

A

NO.

72
Q

Can you have default and/or static methods in an interface in Java

A

yes, after java 8. you can have static and default methods in an interface

73
Q

What is the difference between and interface and an abstract class in Java?

A

Interfaces and abstract classes are two ways to achieve abstraction in Java. However, there are some key differences between the two:

Interfaces define a set of methods that a class must implement but do not provide any implementation for those methods.

Abstract classes can define a set of methods that subclasses must implement, but can also provide default implementations for those methods.

Another key difference is that a class can only extend one abstract class, but it can implement multiple interfaces. This makes interfaces more flexible and reusable.

Here is an example of an interface:

Java
public interface Animal {
void makeSound();
}
Use code with caution. Learn more
This interface defines a single method, makeSound(). Any class that implements the Animal interface must provide an implementation for the makeSound() method.

Here is an example of an abstract class:

Java
public abstract class Animal {
public void makeSound() {
System.out.println(“Generic animal sound”);
}
}
Use code with caution. Learn more
This abstract class provides a default implementation for the makeSound() method. Subclasses of the Animal class can override the makeSound() method to provide their own custom implementation.

Here is an example of a class that implements the Animal interface:

Java
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println(“Woof!”);
}
}
Use code with caution. Learn more
The Dog class implements the Animal interface by providing an implementation for the makeSound() method.

Here is an example of a class that extends the Animal abstract class:

Java
public class Lion extends Animal {
@Override
public void makeSound() {
System.out.println(“Roar!”);
}
}
Use code with caution. Learn more
The Lion class extends the Animal abstract class. It overrides the makeSound() method to provide its own custom implementation.

When to use interfaces and abstract classes:

Use interfaces to define a common set of methods that multiple classes must implement. Interfaces are useful for creating loose couplings between classes.
Use abstract classes to provide a common implementation for a set of methods, but allow subclasses to override those methods to provide their own custom implementations. Abstract classes are useful for creating hierarchies of classes.
In general, interfaces are more flexible and reusable than abstract classes. However, abstract classes can be useful for providing a common implementation for a set of methods.

1) An abstract class can have implemented methods. An interface has only abstract methods From Java 8 onwards, interfaces can have static/default methods in implemented form.

2) An abstract class can have instance variables. Interfaces cannot have instance variables. It can only have constants.

3) An Abstract class can have a constructor. An Interface can not have a constructor.

4) A class can extend only one abstract class. A class can implement more than one interface.

74
Q
A