JSL Complete Guide
JSL Complete Guide
COMPLETE
COURSE
GUIDE
JAVA ESSENTIALS: A COMPLETE GUIDE
FOR ASPIRING SOFTWAEE ENGINEERS
EXPLORE JAVA HIGH-LEVEL INFORMATION, CORE SYLLABUS, INTERVIEW
ESSENTIALS,MCQ’S,CODING QUESTIONS,HANDY CHEAT SHEET
START LEARNING
TODAY
FLM JSL Complete Guide:
When we are learning any programming language like why we choose this
language,Whatever you had chosen, self understanding is very important.This is the
Complete Guide for those who are ready to learn Java.
We always pick any course or something we want to learn based on some suggestions from
friends,seniors or colleagues…Suggestions are good but we can’t blindly follow and take
anything. It's better to have a good self understanding about anything we are going through.
The question is why only java and why not other languages
To get better understanding, we are going through a detailed guide about why to learn
Java.
Memory management in C: It is difficult because there we have to deal with the concepts of
Pointers.Pointers involve an extra level of indirection, as they store the memory address of a
variable rather than its value.you need to manage memory allocation and deallocation
manually. Forgetting to free allocated memory can lead to memory leaks.
Platform Independence: In C/C++, Code needs to be changed and recompiled for different
computers.
Error Handling:In C/C++ Handling errors can make your code complicated.
1
Object-Oriented Programming (OOP): C++ supports OOP, but C does not, and C++ can
get complex with more advanced OOP features.
These are some of the major drawbacks in C,C++,How Java overcame all these drawbacks
and became an evergreen programming language we will discuss.
All the drawbacks discussed above are some of the most important Features of Java.Let's
talk about Java Features.
Suppose,In C you written a simple helloworld program(helloworld.c) and then you compiled
the program,it generates an .exe file,means this executable file directly converts your source
code into machine understandable code(means 0’s and 1’s) you thought yes,then what is the
problem here? Let me tell you,This .exe file is platform dependent. One means if you’d
written this program in a windows system,and you want to run this in another OS like mac or
unix it won’t support.
In Java,when you compile a java program,the java compiler doesn’t convert this source
code into machine code rather it generates a bytecode(.class file) which is platform
independent and you can run this in any operating system.
Encapsulation: It's like packing a lunch box. You put everything you need inside, and you
have a specific way to open it. This keeps your food safe and organised. In Java,
encapsulation keeps data secure and organised, making it easier to understand and
maintain the code.
2
Inheritance: Think of it as a family tree. You inherit traits from your parents, just like classes
in Java can inherit properties from other classes. This allows for code reuse, making it faster
to develop new features without reinventing the wheel.
Polymorphism: Imagine a TV remote. You press the same power button to turn on different
TVs. Similarly, in Java, you can use the same method in different ways depending on the
object it's applied to. This flexibility makes Java versatile and adaptable to changing needs.
Abstraction: It's like using a smartphone. You don't need to know how it works internally to
use its features. Abstraction in Java allows you to focus on what the code does, not how it
does it, making it easier to work with complex systems.
In java,when you are defining any value we have to compulsory mention its datatype,In
python the concept of data types is not there.But java is strongly typed language we have to
mention which type of data we are dealing with,otherwise it will lead to runtime exceptions.
In java we write any code in classes and for that we will create objects,this objects will be
stored in memory.unused objects must be handled definitely for effective memory
management,For this we have garbage collector in java,this garbage collector automatically
handles unused/unreferenced objects and deletes them from the memory.
Java is MultiThreaded
Multithreading in Java allows a program to do multiple tasks at the same time, like listening
to music while typing a document. It helps make programs more efficient by using the
computer's resources wisely. Java provides built-in features to create and manage threads
easily, making it simple to add multitasking to your programs.
Java supports Backward compatibility,meaning Java has been there from 1996,the code
which was written in earlier Java versions,is supported till to the latest versions.
So,now we have an idea why we are learning java,what are its core features and how it
overcame the drawbacks of C/C++.Next,Before we step into learning java it’s better to know
the syllabus and what we are learning in each module.
3
Core Java Syllabus Breakdown
Java Fundamentals
1.Introduction to Java
A. First Program in Java
B. Variables
C. Data Types
D. Operators
2.Control Flow Statements
A. If-else
B. Switch-Case
C. For loop & For Each Loop
D. While loop do-while loop
E. Continue statement
F. Break statement
3.Arrays
4.Strings
5.Methods
Variable in Java is a data container that stores the data values during Java program
execution. Every variable is assigned a data type, which designates the type and quantity of
values it can hold. Variable is a memory location name of the data. The Java variables have
mainly three types: Local, Instance and Static.
Conditionals
4
● do-while loop: Similar to the while loop, but the code block is executed at least once
before the condition is tested.
● continue statement: Used to skip the current iteration of a loop and proceed to the
next iteration.
● break statement: Used to exit a loop or switch statement before it has completed all
its iterations.
● for loop: Used to execute a block of code a specific number of times.
Arrays
OOPS Concepts
● Class
● Interfaces
● Object
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
Exception Handling
Exception Handling in Java is one of the effective means to handle the runtime errors so that
the regular flow of the application can be preserved. Java Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
There are three types of exceptions -
5
MultiThreading
A thread in Java is the direction or path that is taken while a program is being executed.
Generally, all the programs have at least one thread, known as the main thread, that is
provided by the JVM or Java Virtual Machine at the starting of the program’s execution
Collection Framework
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects. Java Collections can achieve all the operations that you perform on
data such as searching, sorting, insertion, manipulation, and deletion.
Garbage Collection
Java garbage collection is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory dedicated to the program.
These are the most important concepts in core java.If you are going to learn advanced
concepts like Java Frameworks you should be clear and confident in these core concepts.
Next,We will look into the most important interview questions which are asked in many java
Interviews.
6
100 Most Important Interview Questions with Answers
Q1. What is the difference between JDK and JRE?
● JDK stands for Java Development Kit and is a full-featured software development kit
for Java, including the JRE (Java Runtime Environment), an interpreter/loader (Java),
a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other
tools needed for Java development.
● JRE stands for Java Runtime Environment and provides the libraries, Java Virtual
Machine (JVM), and other components to run applications and applets written in
Java.
Q2. Why do people say that Java is a 'write once and run anywhere' language?
● This phrase is used because Java is designed to be portable, meaning that Java
code can run on any device that has a compatible JVM, without the need for
recompilation. This is achieved through the use of bytecode, which is compiled from
Java code and can be interpreted on any platform by the JVM.
Q3. Do you think 'main' used for the main method is a keyword in Java?
● No, 'main' is not a keyword in Java. It's an identifier chosen by convention as the
name of the method that the JVM looks for as the starting point of the program.
Q4. Can we write the main method as public void static instead of public static void?
● No, the main method must be declared as 'public static void'. This is the signature the
JVM expects as the entry point of the application. The 'void' keyword indicates that
the main method does not return any value.
Q5. In Java, if we do not specify any value for local variables, then what will be the
default value of the local variables?
● Local variables in Java do not have a default value. If you try to use a local variable
without initializing it, the compiler will give you an error, forcing you to initialise it
before you can use it.
7
● Encapsulation is the mechanism of restricting access to some of the object's
components, which means that the internal representation of an object can't
be seen from outside of the objects' definition. Access to this data is typically
through a public interface.
● Abstraction means dealing with the level of complexity by hiding unnecessary
details from the user. This can be achieved using abstract classes and
interfaces.
● Inheritance is the process where one class acquires the properties and
behaviours of another class.
● Polymorphism allows objects to be treated as instances of their parent class
rather than their actual class. The specific implementation that gets executed
is determined at runtime.
Q7. In Java, what is the default value of an object reference defined as an instance
variable in an Object?
● A constructor in Java is needed to create new objects and initialize them with default
or specific values. It’s called when an instance of a class is created and is used to set
up the initial state of the object.
● Constructors do not return values and do not have a return type, not even void. They
are only used for initializing new objects.
● The this keyword in Java is a reference to the current object, the one that is being
used to call the method or constructor. It is used to differentiate between class
attributes and parameters with the same name, or to pass the current instance to
another method or constructor.
8
● The Object class is the root of the class hierarchy in Java. Every class has Object as
a superclass, all objects, including arrays, implement the methods of this class.
● Java does not support multiple inheritance to avoid the complexity and ambiguity
caused by it, such as the "diamond problem," where a class inherits the same
method from multiple superclasses. However, Java allows multiple inheritance of
types, which can be achieved by implementing multiple interfaces.
● The super keyword in Java is used to refer to the immediate parent class of the
current class. It can be used to call the superclass's methods and constructors.
● A static variable is shared among all instances of a class; it belongs to the class
rather than a particular object. This means that only one instance of a static field
exists regardless of how many times the class has been instantiated. Static variables
are often used to store common properties of all objects (for instance, a company
name that's the same for all employees).
Q16. What happens when the static modifier is not mentioned in the signature of the
main method?
● If the static modifier is omitted from the main method signature, the JVM will not be
able to invoke the main method without creating an instance of the class, which goes
against the Java specification for program entry points. The program will compile, but
the JVM will throw an error when it attempts to run the application, saying that it
cannot find the main method with the correct signature.
9
Q19. What kinds of argument variations are allowed in Method Overloading?
● Yes, the main method can be overloaded with different parameter lists. However, the
JVM will always call the original main method with a single string array as an
argument. Other overloaded main methods can be called like any other method with
overloading.
● Method overriding in Java is done by creating a method in the subclass with the
same name, return type, and parameters as a method in its superclass. The
@Override annotation, while not required, can be used to explicitly declare an
overriding method.
● Static methods cannot be overridden in the way that instance methods can be
because they are not dispatched on the instance of a class, but rather the class itself.
However, a static method can be hidden by another static method in a subclass,
which is sometimes referred to as method hiding rather than overriding.
● An abstract class in Java is a class that cannot be instantiated on its own and is
declared with the abstract keyword. It can contain abstract methods—methods
without an implementation—as well as implemented methods. It's used as a base
class for other classes that are expected to implement the abstract methods.
Q25. Is it allowed to mark a method abstract without marking the class abstract?
● No, if a class contains an abstract method, then the class itself must also be declared
as abstract. You cannot have an abstract method in a non-abstract class.
10
Q26. Is it allowed to mark a method abstract as well as final?
● No, a method cannot be both abstract and final. An abstract method is one that is
declared without an implementation (without braces, and followed by a semicolon),
meaning it must be overridden in a subclass. A final method cannot be overridden by
subclasses, so the two modifiers are mutually exclusive.
● No, you cannot instantiate an abstract class directly. However, you can instantiate an
anonymous class that extends the abstract class, or you can instantiate a subclass
that provides implementations for the abstract class’s abstract methods.
● Yes, starting with Java 8, you can define static methods in interfaces which can be
called independently of any object. These are not abstract methods and must provide
a body.
Q32. What is the difference between an abstract class and an interface in Java?
● An abstract class can have instance methods that implement a default behavior.
Interfaces can only declare methods (until Java 8, after which they can also have
default and static methods). A class can inherit from just one abstract class, but it can
implement multiple interfaces.
11
Q33. Does Java allow us to use private and protected modifiers for variables in
interfaces?
● Before Java 9, variables in interfaces are implicitly public, static, and final. Since Java
9, you can have private methods, which means you can encapsulate common code
between default methods, but you cannot have private or protected variables.
Q34. How can you change the value of a final variable in Java?
● Once a final variable has been assigned a value, it cannot be changed. If the final
variable is a reference, this means the reference cannot change, but the object it
points to can be modified if it is mutable.
● Yes, a class can be marked final. A final class cannot be subclassed, which is useful
when creating an immutable class or securing a class against modification.
● Inheritance can be prohibited by marking a class as final, which means no class can
extend it.
● Yes, you can declare the main method as final. This will prevent any subclass from
hiding the main method, though it's generally not a concern since the main method is
static and often resides in a final class or a class that is not intended to be
subclassed.
Q39. Can you import the same package or class twice in your class?
● Yes, you can technically import the same package or class more than once, but it has
no effect. The Java compiler is smart enough to ignore duplicate imports.
12
Q40. What is serialization?
● The transient keyword in Java is used to indicate that a field should not be serialized.
When an object is serialized, transient fields are skipped and not included in the
serialized representation.
● The finalize() method is called by the garbage collector before an object is destroyed.
It can be used to perform any cleanup operations such as releasing resources (like
closing files or database connections) before the object is garbage collected.
Q45. What is the meaning of Immutable in the context of the String class in Java?
● In Java, an immutable object is one that cannot be modified after it is created. The
String class is an example of an immutable class. Once a String object is created, its
value cannot be changed. Any method that seems to modify a String actually creates
a new String object.
Q46. How many ways are there in Java to create a String object?
Q47. What is the basic difference between a String and StringBuffer object?
13
● The main difference is that String objects are immutable, while StringBuffer objects
are mutable. This means that StringBuffer objects can be modified after they are
created, which is useful for scenarios where you need to make frequent modifications
to a string of characters.
Q49. In Java, what are the differences between Checked and Unchecked Exceptions?
Q50. What is the base class for Error and Exception classes in Java?
● The base class for both Error and Exception classes in Java is the Throwable class.
● A finally block in Java is a block that is used to execute important code such as
closing resources (e.g., files, database connections) regardless of whether an
exception is thrown or caught. It is always executed after the try and catch blocks,
even if an unexpected exception occurs.
● Yes, a finally block can be used without a catch block. In such cases, the finally block
will be executed after the try block completes. However, if an exception is thrown in
the try block and not caught, it will still propagate after the finally block is executed.
● No, it's not mandatory to have a catch block after a try block. You can have either a
catch block, a finally block, or both after a try block. However, if you don't handle an
14
exception with a catch block, you should at least provide a finally block to clean up
resources.
● A finally block will not be executed if the JVM exits unexpectedly (e.g., System.exit()
is called) or if a fatal error occurs that causes the process to abort.
● throw is a keyword used to explicitly throw an exception from a method or any block
of code.
● throws is a keyword used in the method signature to declare that the method might
throw one or more exceptions.
Q56. What is the difference between Collection and Collections Framework in Java?
● The Collection is an interface in Java that represents a group of objects known as its
elements.
● The Collections Framework is a set of classes and interfaces that implement
commonly reusable collection data structures and algorithms, which includes
interfaces like List, Set, and Map, and classes like ArrayList, LinkedList, HashSet,
and HashMap.
● The root interface of the Collection hierarchy in Java is the Collection interface itself.
It is at the top of the collection hierarchy and is extended by other collection
interfaces like List, Set, and Queue.
● You can convert a List to a Set in Java by passing the list as an argument to the
constructor of a Set implementation, like HashSet. For example:
Q59. What are the differences between the two data structures: a Vector and an
ArrayList?
Both Vector and ArrayList are implementations of the List interface. The main differences
are:
● Vector is synchronized, meaning it is thread-safe, while ArrayList is not
synchronized and is not thread-safe.
● Vector has a legacy design and is considered slower than ArrayList because
of its synchronized methods.
15
● ArrayList is generally preferred over Vector for non-threaded applications due
to its better performance.
● LinkedList is better than ArrayList when you need faster insertion and deletion
operations, as these operations are generally O(1) in LinkedList and O(n) in
ArrayList. LinkedList is also better when you need to frequently add or remove
elements from the beginning or middle of the list.
Q61. What are the differences between a List and Set collection in Java?
List:
● Allows duplicate elements.
● Maintains the order of insertion.
● Examples: ArrayList, LinkedList.
Set:
● Does not allow duplicate elements.
● Does not guarantee the order of elements (except in some implementations
like LinkedHashSet).
● Examples: HashSet, TreeSet, LinkedHashSet.
Q62. What are the differences between a HashSet and TreeSet collection in Java?
HashSet:
● Uses a hash table for storage.
● Does not maintain any order of elements.
● Offers constant time performance for basic operations (add, remove,
contains) under ideal conditions.
TreeSet:
● Uses a red-black tree for storage.
● Maintains a sorted order of elements.
● Offers logarithmic time performance for basic operations.
Q63. In Java, how will you decide when to use a List, Set, or a Map collection?
● List: Use when you need an ordered collection that allows duplicates.
● Set: Use when you need a collection that does not allow duplicates and order is not
important (or use LinkedHashSet if insertion order matters).
● Map: Use when you need to store key-value pairs and want fast retrieval based on
keys.
Q64. What are the differences between a HashMap and a Hashtable in Java?
HashMap:
● Not synchronised (not thread-safe).
● Allows one null key and multiple null values.
16
● Iterators are fail-fast.
Hashtable:
● Synchronized (thread-safe).
● Does not allow null keys or null values.
● Enumerations are not fail-fast.
● The hashCode() method in Java returns an integer hash code for an object, which is
used in hashing-based collections like HashMap, HashSet, and Hashtable to bucket
objects. The method is designed to distribute objects evenly across the buckets for
efficient retrieval.
Q67. How will you copy elements from a Source List to another list?
You can use the addAll method to copy elements from one list to another. For example:
Iterator:
● Can be used with any collection.
● Supports forward iteration only.
● Provides methods hasNext(), next(), and remove().
ListIterator:
● Can be used with lists only.
● Supports both forward and backward iteration.
● Provides additional methods like hasPrevious(), previous(), nextIndex(),
previousIndex(), add(), and set().
17
Q70. How will you reverse a List in Java?
You can use the Collections.reverse() method to reverse a list in Java. For example:
Q71. What are the main differences between HashMap and ConcurrentHashMap in
Java?
HashMap:
● Not thread-safe.
● Allows one null key and multiple null values.
● Iterators are fail-fast.
ConcurrentHashMap:
● Thread-safe without locking the entire map.
● Does not allow null keys or null values.
● Provides better concurrency by partitioning the map.
Q72. Why does the Map interface not extend the Collection interface in Java?
● The Map interface does not extend the Collection interface because it represents a
mapping of keys to values, which is a different data structure compared to collections
that store individual elements. Maps have unique keys, and each key maps to a
single value, which is a different concept compared to collections like lists and sets.
You can make a collection class read-only by using the unmodifiable wrappers provided by
the Collections class. For example:
18
Q75. When is UnsupportedOperationException thrown in Java?
Q76. Let's say there is a Customer class. We add objects of the Customer class to an
ArrayList. How can we sort the Customer objects in ArrayList by using customer
firstName attribute of the Customer class?
You can sort the Customer objects in the ArrayList by using the Collections.sort() method
with a custom comparator that compares the firstName attribute of the Customer class. For
example:
● A HashMap in Java works by using a hash table. When you put a key-value pair into
the map, the key's hash code is used to determine where to store the entry in the
underlying array. If two keys have the same hash code or different hash codes that
result in the same index after hashing, a collision occurs, and the entries are stored
in a linked list or tree at that index. When retrieving a value, the same hash code is
used to find the correct index and then the list or tree is searched for the entry with
the matching key.
Q79. What are the three different priorities that can be set on a Thread in Java?
The three different priorities that can be set on a thread in Java are:
● Thread.MIN_PRIORITY (value 1)
● Thread.NORM_PRIORITY (value 5)
● Thread.MAX_PRIORITY (value 10)
19
Q80. Is it possible to call run() method instead of start() on a thread in Java?
● Yes, it is possible to call the run() method directly instead of start() on a thread in
Java. However, doing so will not create a new thread of execution; instead, the run()
method will be executed in the current thread, just like any other method call.
● No, once a thread has been started, it cannot be started again. If you attempt to start
a thread that has already been started, a java.lang.IllegalThreadStateException will
be thrown.
● Yes, in Java, it is possible to lock an object for exclusive use by a thread using the
synchronized keyword. When a thread enters a synchronized method or block, it
acquires the lock on the specified object, and no other thread can enter a
synchronized method or block on the same object until the lock is released.
● A HashMap in Java works by using a hash table. When you put a key-value pair into
the map, the key's hash code is used to determine where to store the entry in the
underlying array. If two keys have the same hash code or different hash codes that
result in the same index after hashing, a collision occurs, and the entries are stored
in a linked list or tree at that index. When retrieving a value, the same hash code is
used to find the correct index and then the list or tree is searched for the entry with
the matching key.
20
Q86. What is the difference between final, finally, and finalize in Java?
final: A keyword that can be applied to variables, methods, and classes. A final variable
cannot be reassigned, a final method cannot be overridden, and a final class cannot be
subclassed.
finally: A block that is used to execute important code such as closing resources, regardless
of whether an exception is thrown or caught. It is always executed after the try and catch
blocks.
finalize: A method that is called by the garbage collector before an object is destroyed. It is
used to perform any cleanup operations such as releasing resources.
● The volatile keyword is used to indicate that a variable's value will be modified by
different threads. It ensures that the value of the variable is always read from and
written to main memory, providing visibility of changes to all threads.
Q89. Can you explain the difference between shallow copy and deep copy in Java?
● Shallow copy: Creates a new object that is a copy of the original object, but the fields
are not copied; instead, both objects share the same field references.
● Deep copy: Creates a new object that is a copy of the original object, and all fields of
the original object are also copied, so the new object is completely independent of
the original.
21
Q92. What are the differences between a Checked Exception and an Unchecked
Exception in Java?
Q93. Can you explain the concept of autoboxing and unboxing in Java?
● The super keyword is used to refer to the immediate parent class of the current class.
It can be used to call the superclass's methods and constructors.
A Singleton pattern ensures that a class has only one instance and provides a global point of
access to it. It can be implemented by:
● Making the constructor private.
● Creating a private static instance of the class.
● Providing a public static method that returns the instance.
Q96. What is the difference between an abstract class and an interface in Java?
● An abstract class can have instance methods that implement a default behavior,
whereas interfaces can only declare methods (until Java 8, after which they can also
have default and static methods). A class can inherit from only one abstract class but
can implement multiple interfaces.
22
Q98. What are the benefits of using Generics in Java?
Q99. Can you explain the concept of the Java Memory Model?
● The Java Memory Model (JMM) defines how threads interact with memory in a Java
application. It ensures visibility of changes to variables between threads and
establishes rules for reordering of instructions to ensure consistent and predictable
behaviour in concurrent programs.
● The transient keyword is used to indicate that a field should not be serialized when
an object is converted to a byte stream. This is useful for fields that contain sensitive
information or are derived from other fields and do not need to be persisted.
These Are the most important and asked interview questions in java,After learning concepts
come here and check whether you are good at answering this questions!!!
23
Explanation:
Explanation:
24
Q3. Find the number of occurrences of a character in a String?
Explanation:
Q4. How to find out if the given two strings are anagrams or not?
Explanation:
25
chesukuntam,anni characters second strings lo kuda unte aa two
strings anevi anagrams antamu.For that,ekkada two strings str1 and
str2 unnay,to strings ni toCharArray() function tho character
array la convert chesukuntam,Convert ayyaka Arrays.sort() ane
function tho sort chestham,Ee sort function alphabetical order lo
sort chesthundhi.Then Arrays.equals method tho both arrays ni
compare chestham rendu equal aythe true return avthundhi so
anagram avthundhi.
Q5. How do you calculate the number of vowels and consonants in a String?
Explanation:
26
Q6. How do you get the matching elements in an integer array?
Explanation:
Explanation:
27
Q8. How would you swap two numbers without using a third variable?
Explanation:
Initial values:
a = 5
b = 10
First step (a = a + b):
a is assigned the sum of a and b, so a becomes 15 (a = 5
+ 10).
Second step (b = a - b):
b is assigned the difference between the new a and b, so
b becomes 5 (b = 15 - 10).
Third step (a = a - b):
a is assigned the difference between the new a and the
new b, so a becomes 10 (a = 15 - 5).
After these steps, the values of a and b are successfully swapped,
with a being 10 and b being 5
28
Explanation:
Explanation:
Iteration 1: i = 1, factorial = 1 * 1 = 1
Iteration 2: i = 2, factorial = 1 * 2 = 2
Iteration 3: i = 3, factorial = 2 * 3 = 6
Iteration 4: i = 4, factorial = 6 * 4 = 24
Iteration 5: i = 5, factorial = 24 * 5 = 120
After these iterations, the final value of factorial is 120, which
is the factorial of 5.
29
Q11. How would you find the second largest number in an array?
Explanation:
Sorting the array (Bubble Sort):
● In the first iteration of the outer loop (i = 0), the
inner loop compares adjacent elements and swaps them if
they are in the wrong order. After this iteration, the
largest element 5 bubbles up to the last position.
● In the second iteration (i = 1), the inner loop stops
one element before the last (since the last element is
already sorted), and the second largest element 4
bubbles up to the second last position.
● This process continues until the entire array is sorted
in ascending order. After sorting, the array becomes {1,
2, 3, 4, 5}.
Finding the second largest number:
● After sorting, the largest number is at the last
position (arr.length - 1), which is 5 in this case.
● The second largest number is the one before the largest,
at the second last position (arr.length - 2). In this
example, it's 4.
Output:
● The program prints "Second largest number: 4", which is
the second largest number in the original array.
30
Q12. How do you remove all occurrences of a given character from the input string?
Explanation:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
31
}
class Overload {
void demo(int a) {
System.out.println("a: " + a);
}
class Override {
void eat() {
System.out.println("Animal is eating");
}
}
32
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
System.out.println(n + " is prime: " + isPrime);
}
}
Explanation:
Explanation:
Initial Check: Modhataga, manam check chesthunnam n 1 ki
equal or chinnadi aithe, appudu n prime number kaadu ani, so
isPrime ni false ga set chestham.
33
Prime Check: If n 1 kanna peddadi aithe, we use a for loop to
check for divisors. We only need to check n yoka square root
varaku,because if n ki oka divisor n yoka square root kanna
peddadi unte, it must also have a divisor n yoka square root
kanna chinnadi untundi. Ee loop lo, if manam okka number i ni
kanugonnam, which divides n evenly (n % i == 0), appudu n
prime number kaadu, so isPrime ni false ga set chestham and
loop nundi break chestham.
Output: Finally, manam print chestham whether n is a prime
number based on isPrime yoka value.
Ee example lo, 29 is a prime number, so output will be "29 is
prime: true".
Explanation:
34
Q18. How do you implement a binary search in Java?
Explanation:
In this program, we are implementing a binary search algorithm to
find a given key in a sorted array arr.
Initialization: We start with two pointers, low set to 0 (the
first index of the array) and high set to arr.length - 1 (the
last index of the array).
Binary Search Loop:
● The loop continues as long as low is less than or equal
to high.
● We calculate the middle index mid as the average of low
and high.
● If the element at mid is equal to the key, we have found
the key, and we return the index mid.
● If the element at mid is less than the key, it means the
key must be in the right half of the array, so we set
low to mid + 1.
35
●
If the element at mid is greater than the key, it means
the key must be in the left half of the array, so we set
high to mid - 1.
Result:
● If the loop ends and we haven't returned an index, it
means the key is not in the array, so we return -1.
● In the main method, we call binarySearch with an array
and a key. If the result is not -1, we print the index
where the element is found; otherwise, we print "Element
not found".
In this example, the key 3 is found at index 2 in the array {1, 2,
3, 4, 5}.
import java.util.*;
Explanation:
36
based on their values. This comparator compares the values of
Map.Entry objects, allowing us to sort the list in ascending order
of values. Finally, we iterate over the sorted list and print each
entry's key and value, effectively displaying the HashMap sorted
by its values. This program showcases how to sort a HashMap by its
values using a List and a custom comparator in Java.
Q20. Can you prove that a String object in Java is immutable programmatically?
Explanation:
37
Q21. How do you illustrate a try-catch example in Java?
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
}
import java.util.*;
38
System.out.println("Array without duplicates: " +
Arrays.toString(uniqueArr));
}
}
Explanation:
we remove duplicate elements from an array. We start by
initializing an array arr with duplicate elements. Then, we create
a LinkedHashSet called set, which preserves the order of elements
and does not allow duplicates. We iterate through each element of
the array using a for-each loop and add them to the set. Since set
does not allow duplicates, only unique elements will be added.
Next, we create a new array uniqueArr with the size of the set. We
then iterate through the set and copy each element to the
uniqueArr. Finally, we print the uniqueArr, which contains the
array without any duplicate elements.
Q24. How do you swap the first and last elements of an array in Java?
39
After swapping the elements, we print the modified array to show
the result.
These are some of the important and commonly asked programming questions in many
entry level interviews.You can write these programs in your own logic also.
Next,we will see some Quiz questions to check our understanding of Core concepts.
40
50 Core java Quiz Questions
Q1. Which part of the JVM is responsible for loading class files?
A) Method Area
B) Heap Space
C) Class Loader
D) Call Stack
A) Stack Memory
B) Heap Memory
C) Method Area
D) Native Method Stack
Q3. What does JIT compiler stand for and what is its role in the JVM?
A) _myVariable
B) $myVariable
C) 2myVariable
D) myVariable2
Answer: C) 2myVariable
41
Explanation: Identifiers cannot start with a digit.
A) null
B) 0
C) Depends on the type
D) Not assigned a default value
Q6. Which operator is used to compare two values for equality in Java?
A) =
B) ==
C) ===
D) !=
Answer: B) ==
Explanation: The == operator is used for comparison to check if two values are
equal.
A) 2
B) 3
C) 1
D) 11
Answer: A) 2
Explanation: The % operator returns the remainder of division. Thus, 11 % 3 is 2.
int a = 10;
if(a < 20) {
System.out.println("Less than 20");
} else {
System.out.println("20 or more");
}
A) Less than 20
B) 20 or more
C) 10
D) No output
Answer: A) Less than 20
42
Explanation: Since a is less than 20, the if block will execute.
Q9. Which loop construct will execute the body of the loop at least once even if the
condition is false initially?
A) for
B) while
C) do-while
D) foreach
Answer: C) do-while
Explanation: The do-while loop executes its body at least once before checking the
condition.
A) 0 1 2 3
B) 0 1 2
C) 0 1 2 3 4
D) 1 2 3
Answer: B) 0 1 2
Explanation: The loop will terminate when i becomes 3 due to the break statement.
43
Q12. What will the following code snippet print?
int i = 0;
while(i < 3) {
System.out.println("Hello");
i++;
}
Q13. Which of the following is not a valid for loop declaration in Java?
int x = 10;
int y = 20;
if(x > y) {
System.out.println("X is greater");
} else if(x < y) {
System.out.println("Y is greater");
} else {
System.out.println("X and Y are equal");
}
A) X is greater
B) Y is greater
C) X and Y are equal
D) No output
Answer: B) Y is greater
Explanation: The condition x < y is true, so "Y is greater" will be printed.
44
Q15. Which of the following loops will not compile in Java?
A) do { System.out.println("Hello"); } while(false);
B) while(false) { System.out.println("Hello"); }
C) for(;false;) { System.out.println("Hello"); }
D) All of the above will compile
int a = 10;
int b = ++a + a++;
System.out.println(b);
A) 21
B) 22
C) 23
D) 24
Answer: B) 22
Explanation: ++a increments a to 11 before addition, and a++ increments a to 12
after addition.
45
Q19. Which keyword is used to declare a constant in Java?
A) const
B) final
C) static
D) immutable
Answer: B) final
Explanation: The final keyword is used to declare constants in Java.
int x = 5;
int y = x++;
int z = ++x;
System.out.println(y + " " + z);
A) 5 7
B) 6 7
C) 5 6
D) 6 6
Answer: A) 5 7
Explanation: y gets the value of x before incrementing, and z gets the value of x after
incrementing twice.
A) To create objects
B) To initialize objects
C) To return values
D) To define methods
46
Q23. In Java, which keyword is used to inherit from a superclass?
A) extends
B) implements
C) super
D) this
Answer: A) extends
Explanation: The extends keyword is used for inheritance in Java.
class Animal {
String sound() { return "Animal sound"; }
}
A) Animal sound
B) Bark
C) Compilation Error
D) Runtime Error
Answer: B) Bark
Explanation: This is an example of method overriding. The sound method of the Dog
class overrides the sound method of the Animal class.
Q25. Which of the following is true about the super keyword in Java?
47
Q26. What is polymorphism in Java?
Answer: B) A method with the same name but different parameters in the same class
Explanation: Method overloading is a feature that allows a class to have more than
one method with the same name but different parameters.
Answer: A) Hiding the implementation details and showing only the functionality
Explanation: Abstraction is a concept of hiding the internal implementation and
showing only the necessary features of an object.
A) abstract
B) final
C) static
D) private
Answer: A) abstract
Explanation: The abstract keyword is used to create abstract classes and methods,
which are used to achieve abstraction in Java.
48
Q30. What is the purpose of a try-catch block in Java?
A) NullPointerException
B) ArrayIndexOutOfBoundsException
C) IOException
D) ArithmeticException
Answer: C) IOException
Explanation: Checked exceptions are exceptions that are checked at compile-time,
and IOException is an example of a checked exception.
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
A) true
B) false
C) Compilation Error
D) Runtime Error
Answer: B) false
Explanation: The == operator compares references, not values. s1 and s2 refer to
different objects.
Q33. Which of the following methods is used to find the length of a string in Java?
A) length()
B) size()
C) getSize()
D) getLength()
Answer: A) length()
Explanation: The length() method is used to find the length of a string in Java.
49
Q34. Which interface represents a group of objects in Java as a single unit?
A) Array
B) List
C) Set
D) Map
Answer: B) List
Explanation: The List interface represents a group of objects as a single unit in an
ordered collection.
A) run()
B) start()
C) execute()
D) begin()
Answer: B) start()
Explanation: The start() method is used to start a newly created thread. It causes the
thread to begin execution and the JVM calls the run() method of this thread.
50
Q38. What is the purpose of the synchronized keyword in Java?
Answer: C) To ensure that only one thread can access a resource at a time
Explanation: The synchronized keyword is used to control the access of multiple
threads to any shared resource and to prevent thread interference.
Answer: C) The thread will pause its execution for a specified period.
Explanation: The sleep() method is used to pause the execution of the current thread
for a specified period of milliseconds.
Q40. Which of the following is true about the wait() and notify() methods in Java?
51
Q42. How does the Comparator interface differ from the Comparable interface in
Java?
A) Comparator is used for natural ordering, while Comparable is used for custom
ordering.
B) Comparable is used for natural ordering, while Comparator is used for custom
ordering.
C) Comparator can compare any two objects, while Comparable can only compare
strings.
D) Comparable can compare any two objects, while Comparator can only compare
numbers.
Answer: B) Comparable is used for natural ordering, while Comparator is used for
custom ordering.
Explanation: The Comparable interface is used for natural ordering of objects (e.g.,
alphabetical order for strings), while the Comparator interface is used to define
custom orderings.
Answer: C) A short block of code that takes parameters and returns a value
Explanation: Lambda expressions are used to provide a clear and concise way to
represent one method interface using an expression. They are especially useful in
collections filtering and mapping.
A) Runnable
B) Comparator
C) Both A and B
D) None of the above
Answer: C) Both A and B
52
Explanation: Both Runnable and Comparator are functional interfaces in Java 8. A
functional interface is an interface that contains only one abstract method.
Q48. Which method reference can be used as an alternative to the lambda expression
(s) -> System.out.println(s)?
A) System.out::println
B) System.out.println
C) System::println
D) println::System.out
Answer: A) System.out::println
Explanation: Method references provide a way to refer to methods by their names.
System.out::println is a method reference that is equivalent to the lambda expression
(s) -> System.out.println(s).
A) To provide a container object that may or may not contain a non-null value
B) To create optional method parameters
C) To mark methods as optional in interfaces
D) To handle optional configuration settings
53
Answer: A) To provide a container object that may or may not contain a non-null
value
Explanation: The Optional class is a way of representing optional values in Java. It is
used to avoid NullPointerException and to write more readable code by avoiding
excessive null checks.
Q50. What feature was introduced in Java 8 to support parallel array processing?
A) Stream API
B) Lambda Expressions
C) ParallelSort
D) ForkJoin Framework
And,let's see some of the Coding Problems asked in different mnc’s and let's try to solve
them in java.
Example :
Input :
200 -> Value of V
540 -> Value of W
Output :
TW =130 FW=70
Explanation:
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels
Constraints :
● 2<=W
● W%2=0
● V<W
Print “INVALID INPUT” , if inputs did not meet the constraints.
54
The input format for testing
The candidate has to write the code to accept two positive numbers separated by a new line.
● First Input line – Accept value of V.
● Second Input line- Accept value for W.
The output format for testing
● Written program code should generate two outputs, each separated by a single
space character(see the example)
● Additional messages in the output will result in the failure of test case
Solution in Java
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int w=sc.nextInt();
float res=((4*v)-w)/2;
if(w>=2 && (w%2==0) && v<w)
System.out.println("TW= "+(int)(res)+" FW=
"+(int)(v-res));
else
System.out.println("INVALID INPUT");
}
}
Explanation:
55
manufacture 130 two-wheelers and 70 four-wheelers to meet the
given conditions.
2)Problem Statement – Given a string S(input consisting) of ‘*’ and ‘#’. The length of the
string is variable. The task is to find the minimum number of ‘*’ or ‘#’ to make it a valid string.
The string is considered valid if the number of ‘*’ and ‘#’ are equal. The ‘*’ and ‘#’ can be at
any position in the string.(TCS NQT-2023)
Note : The output will be a positive or negative integer based on number of ‘*’ and ‘#’ in the
input string.
● (*>#): positive integer
● (#>*): negative integer
● (#=*): 0
Example 1:
Input 1:
● ###*** -> Value of S
Output :
● 0 → number of * and # are equal
Solution:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String str="Hello";
int count1=0,count2=0;
for(int i=0;i< str.length();i++)
{
if(str.charAt(i)=='*')
count1++;##
else if(str.charAt(i)=='#')
count2++;
}
System.out.println(count1-count2);
}
}
Explanation:
56
We start by initializing two variables, count1 and count2, to keep
track of the number of '' and '#' in the string, respectively. We
then iterate through each character in the string. If the character
is '', we increment count1. If the character is '#', we increment
count2.
Your birthday is coming soon and one of your friends, Alex, is thinking about a gift for you.
He knows that you really like integer arrays with interesting properties.
He selected two numbers, N and K and decided to write down on paper all integer arrays of
length K (in form a[1], a[2], …, a[K]), where every number a[i] is in range from 1 to N, and,
moreover, a[i+1] is divisible by a[i] (where 1 < i <= K), and give you this paper as a birthday
present.
Alex is very patient, so he managed to do this. Now you’re wondering, how many different
arrays are written down on this paper?
The first line contains an integer, n, denoting the maximum possible value in the arrays.
The next line contains an integer, k, denoting the length of the arrays.
2
2 The required length is 1, so there are only two possible arrays: [1] and [2].
1
2 All possible arrays are [1, 1], [1, 2], [2, 2]. [2, 1] is invalid because 1 is not
3
2 divisible by 2.
57
3
5 All possible arrays are [1, 1], [1, 2], [1, 3], [2, 2], [3, 3].
2
Solution:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int k, n;
n = sc.nextInt();
k = sc.nextInt();
System.out.println(countt(n, k));
}
58
Explanation:
That’s is the complete guide for Learning Java.If you prepare the concepts and practice
them well,Then you are on your way to become a good software engineer.Along with java
learn database management(sql)and LINUX,You are good to go!!!.
59
THE JAVA LANGUAGE CHEAT SHEET IF STATEMENTS: CLASS/OBJECT TYPES:
Primitive Types: if( boolean_value ) { STATEMENTS } INSTANTIATION:
INTEGER: byte(8bit),short(16bit),int(32bit), else if( bool ) { STATEMENTS } public class Ball {//only 1 public per file
long(64bit),DECIM:float(32bit),double(64bit) else if( ..etc ) { STATEMENTS } //STATIC FIELDS/METHODS
,OTHER: boolean(1bit), char (Unicode) else { STATEMENTS } private static int numBalls = 0;
HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L //curly brackets optional if one line public static int getNumBalls() {
CHAR EXAMPLES: ‘a’,’\n’,’\t’,’\’’,’\\’,’\”’ LOOPS: return numBalls;
while( bool ) { STATEMENTS } }
Primitive Operators public static final int BALLRADIUS = 5;
Assignment Operator: = (ex: int a=5,b=3; ) for(INIT;BOOL;UPDATE) { STATEMENTS }
Binary Operators (two arguments): + - * / % //1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2
do{ STATEMENTS }while( bool ); //INSTANCE FIELDS
Unary Operators: + - ++ -- private int x, y, vx, vy;
Boolean Not Operator (Unary): ! //do loops run at least once before checking
break; //ends enclosing loop (exit loop) public boolean randomPos = false;
Boolean Binary: == != > >= < <=
Boolean Binary Only: && || continue; //jumps to bottom of loop
ARRAYS: //CONSTRUCTORS
Bitwise Operators: ~ & ^ | << >> >>> public Ball(int x, int y, int vx, int vy)
Ternary Operator: bool?valtrue:valfalse; int[] x = new int[10]; //ten zeros
{
Casting, Conversion int[][] x = new int[5][5]; //5 by 5 matrix
this.x = x;
int x = (int)5.5; //works for numeric types int[] x = {1,2,3,4};
this.y = y;
int x = Integer.parseInt(“123”); x.length; //int expression length of array
this.vx = vx;
float y = Float.parseFloat(“1.5”); int[][] x = {{1,2},{3,4,5}}; //ragged array
this.vy = vy;
int x = Integer.parseInt(“7A”,16); //fromHex String[] y = new String[10]; //10 nulls
numBalls++;
String hex = Integer.toString(99,16);//toHex //Note that object types are null by default
}
//Previous lines work w/ binary, other bases Ball() {
//loop through array:
java.util.Scanner, input, output for(int i=0;i<arrayname.length;i++) {
x = Math.random()*100;
Scanner sc = new Scanner(System.in); y = Math.random()*200;
//use arrayname[i];
int i = sc.nextInt(); //stops at whitespace randomPos = true;
}
String line = sc.nextLine(); //whole line }
System.out.println(“bla”); //stdout //for-each loop through array
System.err.print(“bla”); //stderr,no newline //INSTANCE METHODS
int[] x = {10,20,30,40};
java.lang.Number types public int getX(){ return x; }
for(int v : x) {
Integer x = 5; double y = x.doubleValue(); public int getY(){ return y; }
//v cycles between 10,20,30,40
double y = (double)x.intValue(); public int getVX(){ return vx; }
}
//Many other methods for Long, Double, etc public int getVY(){ return vy; }
public void move(){ x+=vx; y+=vy; }
java.lang.String Methods //Loop through ragged arrays:
public boolean touching(Ball other) {
//Operator +, e.g. “fat”+”cat” -> “fatcat” for(int i=0;i<x.length;i++)
float dx = x-other.x;
boolean equals(String other); for(int j=0;j<x[i].length;j++) {
float dy = y-other.y;
int length(); //CODE HERE
float rr = BALLRADIUS;
char charAt(int i); }
return Math.sqrt(dx*dx+dy*dy)<rr;
String substring(int i, int j); //j not incl }
boolean contains(String sub); //Note, multi-dim arrays can have nulls
boolean startsWith(String pre); //in many places, especially object arrays:
}
boolean endsWith(String post); Integer[][] x = {{1,2},{3,null},null};
int indexOf(String p); //-1 if not found FUNCTIONS / METHODS: //Example Usage:
int indexOf(String p, int i); //start at i Static Declarations: public static void main(String[] args) {
int compareTo(String t); public static int functionname( … ) Ball x = new Ball(5,10,2,2);
//“a”.compareTo(“b”) -> -1 private static double functionname( … ) Ball y = new Ball();
String replaceAll(String str, String find); static void functionname( … ) List<Ball> balls = new ArrayList<Ball>();
String[] split(String delim); Instance Declarations: balls.add(x); balls.add(y);
StringBuffer, StringBuilder public void functionname( … ) for(Ball b : balls) {
StringBuffer is synchronized StringBuilder private int functionname( … ) for(Ball o : balls) {
(Use StringBuilder unless multithreaded) Arguments, Return Statement: if(b != o) { //compares references
Use the .apend( xyz ) methods to concat int myfunc(int arg0, String arg1) { boolean touch = b.touching(o);
toString() converts back to String return 5; //type matches int myfunc }
java.lang.Math } }
Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM) //Non-void methods must return before ending }
,Math.log(NUM),Math.max(A,B),Math.min(C,D), //Recursive functions should have an if }
Math.pow(A,B),Math.round(A),Math.random() //statement base-case that returns at once