0% found this document useful (0 votes)
62 views9 pages

Java Core Concepts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views9 pages

Java Core Concepts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

JAVA Core Concepts:

What is JVM?
It is virtual machine which provides runtime environment to execute java
Byte code. The JVM doesn’t understand the Java code directly, that’s why
we need to compile the *.java files to obtain *.class files that contain
Bytecodes understandable by JVM.
What is JRE?
JRE is Java Runtime Environment which contains JVM along with Java
libraries and tools to develop the Java programs.
What is JDK?
JDK is Java Development Kit which is Superset of JRE ,which has Java
Virtual machine along with java libraries & tools. Apart from this it
contains java Compilers & debuggers.
JAVA main() Method:
The main() is the starting point for JVM to start execution of a Java program.
Without the main() method, JVM will not execute the program.
public static void main(String [] args);
“Public” access specifier is given to the main(), because JVM starts the execution
from the main() method. So, it is important that it should be visible. If it’s made
private, protected, or default, then it will not be visible to JVM.
“Static” keyword is used to create static methods. These are methods that can
be invoked without creating the objects.
Yes, Java’s main() method can be overloaded but JVM will only call the
orignal main method with str args[] , the JVM have the main() method
signature predefined , it always looks for the main() with string args[]
as the parameter. If doesn’t find it. It throws an error.
No, we cannot override main method of java because a static method cannot be
overridden.The static method in java is associated with class whereas the non-
static method is associated with an object. Static belongs to the class area, static
methods don’t need an object to be called. Static methods can be called directly
by using the classname.

Priority-wise Execution process of the program:


Static Block- Static Methods main() method object creation in
memory instance methods execution
Constructor: It is a block of code similar to the method which is invoked
when the class object is created. At the time of calling the constructor, memory
of the object is allocated. Every time an object is created using the new()
keyword, at least one constructor is called.
When an object is created with the new keyword, at least one constructor is
called. It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by default.
A constructor can have a access specifier(Public, private, etc),but there is no
return type of methods. A constructor cannot be final, abstract, static. Like
methods , a constructor can also be overloaded.
Static: “Static” keyword is basically used for memory management in java.
Variables, methods, block, nested class can be static
“Static” keyword can be used with variables, methods & block.
 Static variable is that variable whose memory is assigned only once & the variable
can be accessible to all the instances of the class. Hence it is also called class
variable.
 “Static” methods are those which can be invoked without creating objects of the
class. These are also called class methods and will be visible to all the instances of
the class. Static member can access static data members and also can change the
value of it. The static method can not use non static data member or call non-static
method directly.

This: “This “ is a reference variable which refers to the current object.


 This can be used to refer current class instance variable.
 This() can be used to invoke the current class constructor.
 This can be used to invoke current class method (implicitly).

OOPS: Object Oriented Programming is basically a methodology of


programming, which relies on the concept of classes & objects. In this style a
software program is structured into simple , and reusable pieces of code
blueprints (also known as classes) & which are used to create individual
instances of objects. These objects are reusable and can be reused across
programs.
Inheritance: If a child class acquires all the properties and behaviour of
another parent class. This is called inheritance. It enhances the reusability of
the code. It is used to achieve run-time polymorphism.
Polymorphism: It is an important concept of Object oriented programming.
In layman terms: If a particular task is performed in different ways, it is known
as polymorphism. This can be achieved in by method overloading and method
overriding. For example, in general there are various of communication, we
can communicate in Hind, English etc
a) Method Overloading: If in a class a method with same name but
different signatures (may be in different parameters). Then this is called
method overloading. It basically increases the readability of the
program. Overloading implements compile time polymorphism because
call to method is resolved during compile time.
b) Method Overriding: If in a subclass or the child class a same method
with same signature is used as in parent class . Then its method
overriding .It grants specific implementation of overridden method in
child class that is already declared in parent class. Overriding
implements run time polymorphism because call to method is resolved
during run time based on the type of the object.
Dynamic method dispatch: It is basically a mechanism which is used decide
which method should be called based on the type of object created .
Abstraction:
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.
Abstraction is important concept of OOPs. It means hiding the
implementation details but showing the functionality to the user.
In Java, we use abstract class(50%) and interface(100%) to achieve
abstraction.
o A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated. It can have constructors and static
methods also.
o An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods
declared in the interface. By interface, we can support the functionality of
multiple inheritance.
Encapsulation in Java refers to integrating data (variables) and code (methods) into a
single unit. In encapsulation, a class's variables are hidden from other classes and can only
be accessed by the methods of the class in which they are found
Advantages of Encapsulation:
 Data Hiding: it is a way of restricting the access of our data members by hiding
the implementation details. Encapsulation also provides a way for data hiding.
The user will have no idea about the inner implementation of the class. It will
not be visible to the user how the class is storing values in the variables. The
user will only know that we are passing the values to a setter method and
variables are getting initialized with that value.
 Increased Flexibility: We can make the variables of the class read-only or
write-only depending on our requirement. If we wish to make the variables
read-only then we have to omit the setter methods like setName(), setAge(),
etc. from the above program or if we wish to make the variables write-only
then we have to omit the get methods like getName(), getAge(), etc. from the
above program

String: String is an object in java which represents the sequence of characters.


String class in java implements Comparable , Serialization & Char Sequence
interfaces.
Why String class is immutable in java: String class is designed as immutable in
java because of various reasons:
1. String in java has a concept of String pool constant. Whenever a string
object is created , its created in the string pool constant. So ,first JVM
checks if that object is already exists in the pool . If it is already exists , it
will return the reference of the object ,and if not, it will create the new
object . If string wouldn’t be immutable ,changing the string with one
reference will lead to the wrong value for the other references.
So , in it efficiently manages the memory allocation & hence enhances the
performance.
2. Since, the String is immutable automatically makes the String thread
safe since they won't be changed when accessed from multiple threads.
Same instance of string can be shared among multiple threads.
3. As we know string class is used to store important information like
username ,password & connection file path etc. So if it had been a
mutable class ,there may be a possibility that by any chance string values
gets changed. Then there will be some sort of security threat.
String Methods:
S.substring(int startIndex): It extracts the substring from the given string with
starting index(inclusive).
S= “SachinTendulkar”
S.substring(6) \\ Output: Tendulkar
S.substring(int startIndex, int endIndex): It extracts the substring from the
given string with starting index(inclusive) and ending index (Exclusive)
S.substring(0,6) \\ Output: Sachin
S.split(“regex expression”): it is used to extract a substring from a sentence. It
accepts regex expression as arguments. Return type is Array of strings.
trim(): eliminates the whitespaces before & after the String.
startsWith(“”) & endsWith(“”) Methods: checks whether the String Starts &
ends with the letters passed as arguments. Return type is Boolean.
charAt(int x): charAt() method returns a character at specified
index.
length(): length() method returns length of the specified String.
valueOf():It accepts int, float ,double, char as an argument & convert them to
the string. It is an static method of string class.
int n = 10;
String s = String.valueOf(n);
Syso(s+10) // Output : 1010
S.replace(“old char”,” new char”): This method replaces all the occurrence
sequences of the first string with the second string.

1. String s1="Java is a programming language. Java is a platform”;


2. String replaceString=s1.replace("Java","Kava");//replaces all occurre
nces of "Java" to "Kava"

S.replaceAll(“Regex ex”, charSequence )


An example to remove all the occurrences of white spaces:
1. String s1="My name is Khan. My name is Bob. My name is Sonoo.";
2. String replaceString=s1.replaceAll("\\s","");

The replaceAll() method can also be used to insert spaces between characters.
1. String regex = ""; // adding a white space before and after every ch
aracter of the input string.
2. str = str.replaceAll(regex, " ");

Even the null regular expression is also not accepted by the replaceAll() method
as the NullPointerException is raised:
1. String regex = null; // regular expression is null
2. str = str.replaceAll(regex, " ");
StringIndexOutOfBoundsException is thrown when any one of the
following conditions is met.
o if the start index is negative value
o end index is lower than starting index.
o Either starting or ending index is greater than the total number of
characters present in the string.

S.equals(Object obj): String class actually overrides the equals() method of


Object class.

Conversion of String to Integer v/s Integer to String:


Conversion of integer to string using “String.valueOf(int x)”
For converting string to integer value. int x = Integer.parseInt(“string”),
Otherwise using Integer x = Integer.valueOf() returns integer type of object.

Conversion of String formatted date to Date format:


String str = “21/12/1997”;
String str2 =”21-12-1997”;
SimpleDateFormat format1 = new SimpleDateFormat(“dd/MM/yyyy”);
SimpleDateFormat format2 = new SimpleDateFormat(“dd-MM-yyyy”);
Date date = format1.parse(str);
Date date2 = format1.parse(str2);

JAVA Collections:
Java collections refer to a collection\group of individual objects that are
represented as a single unit. You can perform all operations such as searching,
sorting, insertion, manipulation, deletion, etc., on Java collections just like you
do it on data.
Iterator interface : Iterator is an interface that iterates the elements. It is used
to traverse the list and modify the elements.
1. public boolean hasNext() – This method returns true if the
iterator has more elements.
2. public object next() – It returns the element and moves the cursor
pointer to the next element.
3. public void remove() – This method removes the last elements
returned by the iterator.

ArrayList: ArrayList is used to store elements but uses dynamic arrays . It is


like an array but there is no Size limit. The ArrayList in Java can have the
duplicate elements also. It implements the List interface so we can use all the
methods of the List interface here. The ArrayList maintains the insertion order
internally.
Unlike arrays, arraylists can automatically adjust their capacity when we add or
remove elements from them. Hence, arraylists are also known as dynamic arrays.
Manipulation of with Arraylist is slow because it internally uses Array.If any
element is removed from the array, all the other elements are shifted in the
memory

LinkedList: LinkedList uses doubly linked list internally to store the elements.
Manipulation of linkedList is faster in case of Linkedlist because it internally
uses doubly linked lists , so after removal of some element no shifting is
required in the memory.

HashMap:
Java HashMap class implements the Map interface which allows us to store
key and value pair, where keys should be unique. If you try to insert the
duplicate key, it will replace the element of the corresponding key. It is easy to
perform operations using the key index like updation, deletion, etc.

o Java HashMap contains only unique keys.


o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.

TreeMap:
It stores the elements in key-value pairs in sorted order. It can not contain null
key but can have multiple null values. It doesn’t contain duplicate elements.

Exceptions:
Exception is basically an event which disrupts the normal execution of the
program. So it is very important to handle the exceptions.
The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:
Checked Exception: The exceptions that occurs at the compile time
are checked Exception. ForExample: IOException, SQLException,
ClassNotFoundException etc.
Unchecked Exception: The exceptions that occur at the runtime ,not
checked at the compile time . ForExample: ArithematicException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.

Common questions

Powered by AI

Polymorphism allows a single function or method to operate in multiple ways based on the input, thus enhancing flexibility and maintainability in software design. In Java, polymorphism can be achieved via method overloading (compile-time polymorphism) and method overriding (runtime polymorphism). Method overloading allows multiple methods in the same class with the same name but different signatures, increasing program readability, while method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass, supporting dynamic method dispatch .

Static methods belong to the class rather than any instance, allowing them to be called without object creation. They can access other static methods and data but not instance methods or data. Instance methods depend on a specific object instance and can access and modify instance variables. The static approach benefits memory management by not requiring instances, useful for utility or helper methods, whereas instance methods are essential for behavior relying on individual object state .

The main() method serves as the entry point for Java applications where the JVM begins program execution. Its signature is public static void main(String[] args), where 'public' allows visibility to the JVM, and 'static' avoids the need for object creation. Overriding the main() method is not possible since it is static, and static methods are class-level, not instance-level, thus cannot be overridden. Any overloaded versions of main() are not invoked by the JVM .

Exception handling in Java ensures that runtime errors, which disrupt normal program flow, are managed and resolved. Checked exceptions are those checked at compile time, mandating either catching or declaring them with a throws keyword (e.g., IOException), ensuring that developers anticipate and recover from potential failures. Unchecked exceptions, like NullPointerException, arise from runtime errors not typically declared or caught during compilation. This distinction impacts how developers write robust code, with checked exceptions promoting preemptive error management .

The Java Virtual Machine (JVM) provides the runtime environment necessary to execute Java bytecode. Java files are compiled into bytecode, which is contained in .class files, because the JVM does not understand Java code directly. Thus, it is crucial for translating human-readable Java code into a format that the machine can understand and execute .

Encapsulation integrates code and data into a single unit, hiding the internal state of objects from the outside world. This ensures data hiding, meaning object data can only be modified through trusted methods, preventing unauthorized or accidental changes. Encapsulation enhances flexibility by allowing changes in the internal mechanisms without affecting external code and increases security by controlling access to the internal states .

Interfaces in Java are used to achieve full abstraction, as they can declare methods without actual implementations, obligating implementing classes to provide specific functionality. This approach enables multiple inheritance simulations and defines a clear contract for behavior, which enhances flexibility and modularity in software architecture, promoting separation of concerns and reducing coupling by ensuring that classes can interchange without requiring changes to implementations .

Inheritance allows a child class to acquire properties and behaviors from a parent class, thereby promoting code reusability by reusing existing code. Abstract classes provide a template with some implementation, enabling more common functionality across subclasses, while interfaces define a contract for behavior without providing specific implementation. This combination allows Java to facilitate multiple inheritance through interfaces and detailed class hierarchies with abstract classes, supporting extensive reusability and component-based design .

The immutability of the String class in Java contributes significantly to memory management and thread safety. Strings are stored in the constant string pool, where, if a string already exists, the reference is reused instead of creating a new object. This efficient memory allocation prevents changes to a shared string from affecting references, enhancing performance. Additionally, immutability makes strings inherently thread-safe since their state cannot change, making them safe to use across multiple threads without synchronization .

The "this" keyword refers to the current object's instance within methods or constructors, often used to distinguish between class attributes and parameters of constructors or methods with the same name. It can also invoke the current class's constructor using "this()". The "super" keyword, in contrast, refers to the immediate parent class object, allowing access to superclass methods and constructors. When inheriting, "super" can be used to call the parent class's constructor or overridden methods .

You might also like