Core Java Flashcards
The wrapper classes
The wrapper classes are predefined classes in Java
used to wrap the primitive data types to introduce them as objects and vice versa
Byte, Short, Integer, Long, Character, Boolean, Float, Double
Data Structures in a collection framework can store only objects and not primitive data types
The primitive values are not objects and the developer needs to write many boilerplate codes to convert them to each other and using them in collections
What is polymorphism
The ability for some code structure in an OOP language to treated different structures at runtime
Polymorphism
Overloading is a part of compile time polymorphism
Overriding is a part of run time polymorphism.
ways we can create an object in java.
1- created using the new operator on the class calling one of its constructors. MyClass o = new MyClass();
2- We can invoke clone method on an object to create a duplicate object.
MyClass o = new MyClass();
MyClass b = (MyClass)o.clone();
3- We can create an object using the Java reflection API - Class.newInstance() if the class has a default constructor. MyClass o = MyClass.class.newInstance(); If the class has multiple constructors that take parameters, we can get the corresponding constructor using Class.getConstructor() method and invoke that to create a new object. MyClass o = MyClass.class.newInstance(); MyClass o = MyClass.class MyClass o = MyClass.class.newInstance(); MyClass o = MyClass.class.getConstructor(int.class) .newInstance(10);
4-If a state of that object is available in a serialized form, we can deserialize it to create a new object having the same state. ObjectInputStream is = new ObjectInputStream(anIStream); MyClass o = (MyClass) is.readObject();
Static binding or compilation time polymorphism (overloading)
Dynamic binding or runtime polymorphism (overriding)
Static polymorphism --time of compilation static polymorphism is achieved through method overloading static polymorphism decides which method needs to be invoked at the time of compilation and bind the method invocation with the call. // First addition function public static int add(int a, int b) { return a + b}; // Second addition function public static double add (double a, double b) { return a + b; }
// Driver code public static void main(String args[]) { // Here, the first addition // function is called System.out.println(add(2, 3));
// Here, the second addition // function is called System.out.println(add(2.0, 3.0)); } } -------------------------------------------------------------- Dynamic binding or runtime polymorphism Dynamic polymorphism is achieved through method overriding As we know, a parent class reference can point to a parent object as well as a child object. Now, if there is a method which exists in both the parent class and override on the child class so if we invoke the method from parent class reference, the compiler cannot decide which method to bind with the call.
If the reference is pointing to a parent object, then the method in the parent class will be invoked. parent p = new parent() If the pointed object is an instance of the Child class, then the child-class implementation is invoked. parent p = new child() // up casting
// object of type parent Parent a = new Parent();
// object of type Child Child c = new Child();
// obtain a reference of type Parent Parent ref; // null
// ref refers to an Parent object ref = a;
// calling Parent's version of m1() ref.m1();
// now ref refers to a Child object ref = c; //up casting
// calling Child's version of m1() ref.m1();
(i.e)
In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members.
StringBuffer and StringBuilder
StringBuffer is thread-safe which means it can be used as a shared object among multiple threads.
On the other hand,
StringBuilder is not thread-safe and should not be allowed to be modified by multiple threads without proper synchronization techniques.
That’s why StringBuilder is faster than StringBuffer
we prefer StringBuilder over StringBuffer when we need to build a String object local to a method or local to a particular thread,
Checked Exception vs Unchecked Exception
The exceptions which are checked during compile time are called checked exceptions.
When method throws checked exceptions, they must either be handled by the try-catch block or must declare the exception using the throws keyword. In case of violation, it will show a compile time error. It is a subclass of Exception class
Unchecked exceptions are the exceptions that are not checked during compile time. as (NullPointerException) If the code throws an unchecked exception and even if it is not handled, it will not generate a compile time error. This is dangerous as unchecked exceptions generally generate runtime errors. It is the subclass of RuntimeException class
Finally
A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn’t required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.
When we use abstract and Interface
Since the abstract class has concrete methods and abstract methods so if you have any requirements where a few sets of the functionalities common across all the subclasses and a few functionalities vary from subclasses
We use abstract class when the different implementations have most of the behaviors common and defined by the abstract class. So, abstract classes can be used to combine and share functionality,
An interface is preferred while exposing a public API to the client code and if a class can behave differently in different context. and if we don't have to inherrit default behavior
what do you understand by a Static member(variable)
Static methods and fields are shared between all the objects of a class and can be accessed from any of them
We declare a member(variable) as static if it doesn’t depend on any instance of the class, Static fields are initialized through a static block which is executed when a class is loaded by the class loader
ArrayList and LinkedList
ArrayList and LinkedList both represent a list of numbers
but differ in their internal implementation.
ArrayList
It gives constant time access to add and get an element,
but for deletion, it gives linear time complexity
as it needs to shift its elements to the left
LinkedList
It gives constant time access to add and delete an element,
but for get an element in linear time
use linked nodes internally for storing the elements.
HashMap and Hashtable
HashMap and Hashtable
- both store key-value pairs
- HashMap is fast than Hashtable
HashMap
- is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code.
- allows one Null key and multiple Null values.
- Multiple threads can operate
HashTable
- is synchronized. It is thread-safe and can be shared with many threads.
- doesn’t allow Null keys or values
- At a time only one thread is allowed to operate
public static void main(String args[])
It is the entry point of any Java Program
public: This is the access specifier/access modifier of the main method.
static: At the start of the runtime, the class is devoid of any object .
the main method needs to be static so that the Java Virtual Machine can set the class to the memory and call the main method.
void: It is the return type of the main method.
main: It is the name of the main method.
String args[] : The main method can accept a single argument which is of the String type.
Local Variable and Instance Variables
Local Variable is a variable declared in a method body or a constructor or a block
The scope of the local variables starts from its declaration and ends when the block or method body or the constructor ends
Instance Variables Each object can create its own copy of the instance variable and access it separately.
The scope of the instance variable is created and destroyed when the objects are created and destroyed respectively.
differences between abstract classes and interfaces
Abstract class and Interface both are used for abstraction which is hiding the background details and representing only the essential features. But there are major differences between abstract classes and interfaces.
Abstract
Can have instance variables of any kind
Can have any visibility: public, private or protected
Can have both abstract as well as non-abstract methods
Can have constructors
Can be extended by using keywords ‘extends’
A Java class can extend only one abstract class
Can provide complete code
Interfaces
Cannot have instance variables
variable must be( public static final)
Have either public visibility or no visibility
Only have abstract methods
Cannot have constructors
Can be implemented by using keyword ‘implements’
A Java class can implement multiple interfaces
Just provide the signature/prototype
Overloading and Overriding
In Method Overloading, the names of the methods in the same class are same but the arguments (type and/or number) are different.
In Method Overriding,
the names and arguments of the methods are same
but one of the methods is in the super class while the other is in the sub class.
Usage of Final keyword in Java
The final keyword is a non-access modifier in Java.
It can only be applied to a variable, method or a class. which makes them non-changeable
Class that are final cannot be extended.
Methods that are final cannot be used for method overriding in child class.
The final variables have constant value which are not changeable throughout the program.
This means they need to be initialized along with their declaration, otherwise they would be blank final variables, which can be later initialized only once.
If a final variable is used as a reference to an object, it cannot be used as a reference to another object.
Thread Life Cycle in Java
The 5 states in a thread life cycle are:
New When an instance of the thread class has been created but the start() method is not invoked, then the thread is in the new state.
Runnable
When the start() method has been invoked but the thread scheduler has not selected the thread for execution, then the thread is in the runnable state.
Running
If the thread scheduler has selected a thread and it is currently running, then it is in the running state.
Blocked (Non-runnable)
When a thread is not eligible to run but still alive, then it is in the blocked state.
Terminated (destroy)
When the run() method of a thread exits, then it is in the terminated state.
Java equals() method vs == operator
The equals() method and the == operator in Java are both used to find if two objects are equal.
equals() is a method,
== is an operator.
Also, equals() compares the object values
while == checks if the objects point to the same memory location.
What does “static” mean in public static void main(String args[])?
The static keyword acts as an access modifier. When the Java Virtual Machine calls out to the main method, it has no object to call to. Hence, we use static to permit its call from the class.
If we do not use static in public static void main(String args[]), then the compiler will give an error message.
Access Modifiers in Java
helps to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java:
Default – No keyword required
Private
Protected
Public
What type of parameter passing does Java support?
Pass by value
it means that when a method is called, a copy of the parameters is sent to the memory
When we are using the parameters inside the method or the block, the actual arguments aren’t used but the copy of those arguments (formal parameters) are worked with. There is no change in the actual parameters.
In Java, arguments are always passed by value irrespective of their original variable type. Each time a method is called, a copy is created in the stack memory and its version is passed to the method.
Pass by reference
it means that the changes in the parameters will be reflected in the original value .
This occurs because the method receives the memory address of the parameters.
How to make a class Singleton
Singleton class is a class which has only a single object. This means you can instantiate the class only once. When we declare the constructor of the class as private, it will limit the scope of the creation of the object If we return an instance of the object to a static method, we can handle the object creation inside the class itself.
private static Example obj; static { obj = new Example(); // creation of object in a static block } private Example() { } // declaring the constructor as private public static Example getObject() { return obj; }
Lambda Expression
A lambda expression is an instance of a functional interface
Used to override a function interface
The most important feature of Lambda Expressions is that
they execute in the context of their appearance
minimize coupling (minimize relation between classes) and increase cohesion (increase the relation between methods and properties in class )
Lambda is an anonymous and passed (mostly) to other functions as parameters
Comparable interface
It is inside the same class
A comparable interface is used to order the objects of the user-defined class.
contains only one method named compareTo (Object)
public int compareTo(Student st)
It provides a single sorting sequence only,
you can sort the elements on the basis of a single data member only
Java Generic (parameterized types)
Enable programmers to specify, with a single method declaration, a set of related methods, or Enable programmers to specify, with a single class declaration, a set of related types, respectively.
Generics are mostly used by collection like HashSet or HashMap.
Advantages of using generics
1- Java Generics helps the programmer to reuse the code for whatever type he/she wishes.
2 - Individual typecasting isn’t required. The programmer defines the initial type and then lets the code do its job.
Annotations
Is a form of syntactic metadata that can be added to Java code.
Classes, interfaces, methods, variables, parameters and Java packages may be annotated.
annotation can have elements like an attribute or parameter
@Entity(tableName = “vehicles”, primaryKey = “id”)
Threads
Threads allows a program to do multiple complicated tasks at the same time at the background
without interrupting the main program uesing the same program memory
2 ways to do the Threads
1 - by Extends Thread class –> run method
2 - by Inplement Runnable interface –>run method
————————————————————-
.start(); to actually begin thread execution after instantiation
.sleep();
.yeild()
.joine(); to wait for the thread to finish execution
.getId();
.setName();
.setPeriority(); from 1 to 10 —> 5, default
.currentThread();
interrupt(); to explicitly interrupt the thread
isAlive(); , is Interrupted, isDaemon() to test the state of the thread
JUnit
JUnit 5 is most widely used testing framework for java applications
JUnit Jupiter
It includes new programming and extension models for writing tests.
It has all new junit annotations and TestEngine implementation to run tests written with these annotations.
Comparator interface It is outside the class in another class
It is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences
from another class Implements Comparator
public class ComparStusent implements Comparator
Serialization and Deserialization
Is a mechanism of writing the state of an object into a byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization
where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent,
it means you can serialize an object on one platform and deserialize it on a different platform.
For Serializing is writing the state of an object into a byte-stream.
Write to file.txt
1- FileOutputStream fss = new FileOutputStream(“MyBook.txt”);
2- ObjectOutputStream ooss = new ObjectOutputStream(inpt);
3- ooss.writeObject(serial);
4- ooss.close();
For Deserialization is writing the state of a byte-stream into an object
Read from file.txt
1- FileInputStream fiss = new FileInputStream(“MyBook.txt”);
2- ObjectInputStream oiss = new ObjectInputStream(oupt);
3- Serialization seriall = (Serialization) oiss.readObject();
4- oiss.close();
i.e - We must have to implement the Serializable interface for serializing the object.
Logging API
is an API that provides the ability to trace out the errors of the applications.
When an application generates
1- the logging call,
2- the Logger records the event in the LogRecord.
3- The appenders format that logRecord by using the formatter or layouts.
4- it sends to the corresponding handlers or appenders. (console or file)
Need for Logging
It provides the complete tracing information of the application.
It records the critical failure if any occur in an application.
Maven
Maven is a powerful project management tool that is based on
POM (project object model).
It is used for projects build, dependency and documentation.
What it does?
It makes a project easy to build
It provides uniform build process (maven project can be shared by all the maven projects)
It provides project information (log document, cross referenced sources, mailing list, dependency list, unit test reports etc.)
It is easy to migrate for new features of Maven
File I/O
To Write on file FileWriter inp = new FileWriter("sample.txt"); inp.write(s); inp.flush(); To read From File FileReader outp= new FileReader("sample.txt"); char [] data = new char[100]; outp.read(data); String s = new String(data); System.out.println(s);
What are the main concepts of OOPs in Java?
Inheritance (IS-A): is a process where one class can reuse the properties of another class. 1. Parent class (Super or Base class) 2. Child class (Subclass or Derived class
Encapsulation:
is a mechanism of wrapping up the data and code together as a single unit.
Abstraction:
is the process of hiding certain details and showing only essential information to the user.
1. Abstract Classes (0-100% of abstraction can be achieved)
2. Interfaces (100% of abstraction can be achieved)
Polymorphism:
means “many forms”, it occurs when we have many classes that are related to each other by inheritance.
There are two types of polymorphism:
1 Compile time polymorphism (is method overloading ) static binding
2 Run time polymorphism (is using inheritance and interface) dynamic binding
What is sealed?
Class cannot be inherited
What is virtual?
Identifier a method in a parent class that can be overidded in a child class
What is loop Statement
Execute a statement or block of statements repeatedly until a condition is meet
What do you mean by an interface in Java?
Is a blueprint of a class or it is a collection of abstract methods and static constants.
is a group of related methods with empty bodies each method is public and no constructor
What is a constructor overloading in Java?
is a technique of adding any number of constructors to a class each having a different parameter list.
What is Object Oriented Programming?
Braking the normal procedural code into structures called object
so we can creating relationship between these objects
Is a programming model where the programs are organized around objects rather than logic and functions
better use in large and complex codes which easy to updated or maintained.
What is an object in Java and how is it created?
An object is an instance of a class in memory and is created using the ‘new’ keyword
Define a Java Class
blueprint contains variables and methods to describe the behavior of an object and use to instantiate object.
Differentiate between the constructors and methods in Java?
Methods
- Used to represent the behavior of an object
- Must have a return type
- Needs to be invoked explicitly
- No default method is provided by the compiler
- Method name may or may not be same as class name
Constructors
- Used to initialize the state of an object
- Do not have any return type
- Is invoked implicitly
- A default constructor is provided by the compiler if the class has none
- Constructor name must always be the same as the class name
What are constructors in Java?
constructor is a block of code which is used to initialize instance variables
There are two types of constructors:
Default Constructor:
- assign the default value to the objects.
- no argument constructors
- created by default in case you no other constructor is defined by the user.
Its main purpose is to initialize the instance variables with the default values
Parameterized Constructor:
constructor which is capable of initializing the instance variables with the provided values
Its main purpose is to initialize the instance variables with the provided values
What is the Exceptions?
An event that occurs during the execution of a program that damage the normal flow of instructions