0% found this document useful (0 votes)
38 views15 pages

Questions

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

Questions

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

Java – 50 Questions with Answers

1. What is Java?
Answer: Java is a platform-independent, object-oriented programming language.
2. What is JVM?
Answer: Java Virtual Machine runs Java bytecode on any device.
3. What is JRE?
Answer: Java Runtime Environment contains JVM and libraries to run Java
programs.
4. What is JDK?
Answer: Java Development Kit contains JRE + development tools (compiler,
debugger).
5. What are the main features of Java?
Answer: Object-oriented, platform independent, robust, secure, multithreaded.
6. What is a class in Java?
Answer: A blueprint to create objects.
7. What is an object?
Answer: An instance of a class.
8. What is a method?
Answer: A function defined inside a class.
9. What is the main method?
Answer: public static void main(String[] args) is the program entry point.
10. What is the difference between == and .equals() in Java?
Answer: == compares references, .equals() compares values.
11. What are primitive data types in Java?
Answer: byte, short, int, long, float, double, char, boolean.
12. What is a constructor?
Answer: A method to initialize an object, with same name as class.
13. What is method overloading?
Answer: Multiple methods with same name but different parameters.
14. What is method overriding?
Answer: Subclass provides its own version of a parent class method.
15. What is a static variable?
Answer: Variable shared among all instances of the class.
16. What is a static method?
Answer: Method that belongs to the class, not an instance.
17. What is the difference between final, finally, and finalize?
Answer:
o final: Used to declare constants or prevent inheritance.
o finally: Block executed after try-catch.
o finalize(): Called by garbage collector before object destruction.
18. What is inheritance?
Answer: One class acquires properties of another.
19. What is encapsulation?
Answer: Hiding data using private variables and providing public getters/setters.
20. What is polymorphism?
Answer: Ability to take multiple forms (overloading and overriding).
21. What is abstraction?
Answer: Hiding complex implementation details.
22. What is an interface?
Answer: A contract with abstract methods a class must implement.
23. What is the difference between an abstract class and an interface?
Answer: Abstract classes can have concrete methods; interfaces have abstract
methods (before Java 8).
24. How do you create a thread in Java?
Answer: Extend Thread class or implement Runnable interface.
25. What is synchronization?
Answer: Control access to shared resources by multiple threads.
26. What is exception handling?
Answer: Using try-catch blocks to handle runtime errors.
27. What is the difference between checked and unchecked exceptions?
Answer:
o Checked exceptions are checked at compile time.
o Unchecked exceptions occur at runtime.
28. What is garbage collection?
Answer: Automatic memory management by JVM to remove unused objects.
29. What is the difference between String, StringBuilder, and StringBuffer?
Answer:
o String is immutable.
o StringBuilder is mutable and not synchronized.
o StringBuffer is mutable and synchronized.
30. What is the use of the super keyword?
Answer: Refers to parent class members.
31. What is an array?
Answer: A container that holds fixed number of values of same type.
32. How do you create an array in Java?
Answer: int[] arr = new int[10];
33. What is the difference between ArrayList and LinkedList?
Answer:
o ArrayList uses dynamic array; fast access.
o LinkedList uses doubly linked list; faster insert/delete.
34. What is autoboxing and unboxing?
Answer: Automatic conversion between primitive types and their wrapper classes.
35. What are wrapper classes?
Answer: Classes that wrap primitive types into objects (e.g., Integer, Double).
36. What is the purpose of transient keyword?
Answer: Prevents serialization of a variable.
37. What is serialization?
Answer: Converting an object into a byte stream for storage or transmission.
38. What is the instanceof keyword?
Answer: Checks if an object is an instance of a specific class/interface.
39. What is a package in Java?
Answer: Namespace to organize classes and interfaces.
40. How do you handle file I/O in Java?
Answer: Using classes like FileReader, BufferedReader, FileWriter, BufferedWriter.
41. What is JDBC?
Answer: Java Database Connectivity API to connect Java with databases.
42. What is the difference between HashMap and Hashtable?
Answer:
o HashMap is not synchronized and allows null keys.
o Hashtable is synchronized and does not allow null keys.
43. What is a lambda expression?
Answer: Short block of code which takes parameters and returns a value.
44. What is Stream API?
Answer: Used for processing sequences of elements in a functional style.
45. What is the default value of instance variables?
Answer: Numeric types: 0, boolean: false, objects: null.
46. What is the difference between stack and heap memory?
Answer:
o Stack stores local variables and method calls.
o Heap stores objects.
47. What is the volatile keyword?
Answer: Ensures visibility of changes to variables across threads.
48. What is a nested class?
Answer: A class declared inside another class.
49. What is the difference between StringBuilder and StringBuffer?
Answer: StringBuffer is thread-safe (synchronized), StringBuilder is not.
50. How to create a read-only class in Java?
Answer: Make class and fields final, provide only getters, no setters.

Object-Oriented Programming (OOP) – 50


Questions & Answers
1. What is Object-Oriented Programming?
Programming paradigm based on objects containing data and behavior.
2. What are the four main pillars of OOP?
Encapsulation, Inheritance, Polymorphism, Abstraction.
3. Define encapsulation.
Wrapping data (variables) and methods into a single unit (class) and restricting access
using access modifiers.
4. What is inheritance?
Mechanism where a class acquires properties and methods of another class.
5. What is polymorphism?
Ability of one interface to support multiple underlying forms (methods).
6. Explain abstraction.
Hiding complex details and showing only necessary features.
7. What is a class?
Blueprint or template for creating objects.
8. What is an object?
Instance of a class with state and behavior.
9. What are access modifiers in OOP?
Keywords like private, public, protected, default controlling visibility.
10. What is a constructor?
Special method to initialize an object.
11. What is method overloading?
Multiple methods with the same name but different parameters in the same class.
12. What is method overriding?
Subclass provides its own implementation of a method declared in superclass.
13. What is the difference between overloading and overriding?
Overloading – same method name, different parameters; compile-time.
Overriding – same method signature, subclass changes implementation; runtime.
14. What is the difference between class and object?
Class is the blueprint; object is the actual instance.
15. What is multiple inheritance? Does Java support it?
A class inherits from more than one class; Java doesn’t support multiple class
inheritance but supports multiple inheritance through interfaces.
16. What is an abstract class?
A class that cannot be instantiated and may have abstract methods.
17. What is an interface?
A contract with abstract methods that implementing classes must define.
18. Can interfaces have variables?
Yes, variables in interfaces are implicitly public static final.
19. What is the difference between abstract class and interface?
Abstract class can have implemented methods; interface (before Java 8) only abstract
methods.
20. What is a final class?
Class that cannot be subclassed.
21. What is a final method?
A method that cannot be overridden.
22. What is a final variable?
Constant value, cannot be changed once initialized.
23. What is a static variable?
Variable shared by all instances of a class.
24. What is a static method?
Method that belongs to the class, not any object instance.
25. What is the use of super keyword?
Refers to superclass members or constructor.
26. What is the difference between this and super?
this refers to current class; super refers to parent class.
27. What is a nested class?
Class declared inside another class.
28. What is an inner class?
Non-static nested class.
29. What is a static nested class?
Nested class declared static, behaves like a top-level class.
30. What is coupling in OOP?
Degree of interdependence between modules/classes.
31. What is cohesion in OOP?
Degree to which elements of a class belong together.
32. What is a constructor overloading?
Multiple constructors with different parameters.
33. What is an interface inheritance?
An interface inherits another interface.
34. What is polymorphism at compile time?
Method overloading.
35. What is polymorphism at runtime?
Method overriding.
36. What is dynamic method dispatch?
Call to overridden method resolved at runtime.
37. What is a marker interface?
Interface with no methods (e.g., Serializable).
38. What is multiple inheritance through interfaces?
A class implements multiple interfaces.
39. What is the use of instanceof operator?
Checks if an object is an instance of a class or implements an interface.
40. What is message passing in OOP?
Objects communicate by sending messages (calling methods).
41. What is a mutable object?
Object whose state can be changed after creation.
42. What is an immutable object?
Object whose state cannot be changed after creation (e.g., String).
43. What is a design pattern?
Reusable solution to common problems in software design.
44. What is the difference between aggregation and composition?
Aggregation: Has-a relationship but objects can exist independently.
Composition: Has-a relationship but lifetime dependency.
45. What is method hiding?
Static methods can be redefined in subclass but not overridden.
46. What is a pure virtual function?
Abstract method with no implementation (in Java: abstract method).
47. What is duck typing?
Concept that an object's suitability is determined by the presence of certain
methods/properties, not its type.
48. What is an object’s state and behavior?
State: Data stored in fields; Behavior: Actions performed by methods.
49. What are getter and setter methods?
Methods to read and modify private variables.
50. Why is OOP preferred over procedural programming?
It models real-world entities, promotes code reuse, modularity, and maintainability.

SQL – 50 Questions with Answers


1. What is SQL?
Structured Query Language used to manage and manipulate databases.
2. What are the different types of SQL commands?
DDL, DML, DCL, TCL.
3. What is DDL?
Data Definition Language — commands like CREATE, ALTER, DROP.
4. What is DML?
Data Manipulation Language — commands like SELECT, INSERT, UPDATE,
DELETE.
5. What is DCL?
Data Control Language — commands like GRANT, REVOKE.
6. What is TCL?
Transaction Control Language — commands like COMMIT, ROLLBACK.
7. What is a primary key?
Unique identifier for a table’s row; cannot be NULL.
8. What is a foreign key?
A field in one table that refers to the primary key in another table.
9. What is normalization?
Process of organizing data to reduce redundancy.
10. What is denormalization?
Process of combining tables to improve read performance.
11. What is a JOIN?
Combine rows from two or more tables based on related columns.
12. What are the types of JOINs?
INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN.
13. What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns matching rows only; LEFT JOIN returns all left table rows plus
matching right.
14. What is a UNIQUE constraint?
Ensures all values in a column are distinct.
15. What is a CHECK constraint?
Ensures column values meet a specified condition.
16. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping; HAVING filters groups after grouping.
17. What is GROUP BY?
Groups rows sharing a property for aggregation.
18. What is an index?
Data structure to speed up data retrieval.
19. What are aggregate functions?
Functions like COUNT, SUM, AVG, MIN, MAX used for calculations on groups.
20. What is a subquery?
A query nested inside another query.
21. What is the difference between DELETE and TRUNCATE?
DELETE removes rows and can be rolled back; TRUNCATE removes all rows faster
but cannot be rolled back in some DBMS.
22. What is a view?
Virtual table based on the result of a query.
23. What is a stored procedure?
Precompiled SQL code stored in the database for reuse.
24. What is a transaction?
A sequence of SQL operations performed as a single unit.
25. What are ACID properties?
Atomicity, Consistency, Isolation, Durability.
26. What is the difference between CHAR and VARCHAR?
CHAR is fixed-length; VARCHAR is variable-length.
27. What is a composite key?
Primary key made of multiple columns.
28. What is SQL injection?
Security vulnerability allowing malicious SQL code injection.
29. How to prevent SQL injection?
Use prepared statements and parameterized queries.
30. What is the difference between UNION and UNION ALL?
UNION removes duplicates; UNION ALL includes all rows.
31. What is a schema?
Structure that defines the organization of database objects.
32. What is the default join type if JOIN keyword is used without INNER, LEFT,
etc.?
INNER JOIN.
33. What is a self join?
Joining a table with itself.
34. What is a cursor in SQL?
Database object used to retrieve and manipulate row-by-row results.
35. What is the difference between EXISTS and IN?
EXISTS returns true if subquery returns rows; IN compares values to a list.
36. What is a NULL value?
Represents missing or unknown data.
37. How to select distinct values?
Using DISTINCT keyword.
38. How do you find the number of rows in a table?
Using SELECT COUNT(*) FROM table;
39. What is the difference between HAVING and WHERE?
WHERE filters rows before aggregation; HAVING filters groups after aggregation.
40. What is a trigger?
SQL code automatically executed in response to certain events.
41. What is the difference between a primary key and unique key?
Primary key cannot be NULL; unique key can be NULL.
42. What are constraints?
Rules enforced on data columns.
43. What is the difference between correlated and non-correlated subquery?
Correlated subquery depends on outer query; non-correlated does not.
44. What is referential integrity?
Ensures foreign key values match primary key values or are NULL.
45. What is the purpose of the ORDER BY clause?
To sort query result.
46. What is the difference between DELETE and DROP?
DELETE removes data rows; DROP removes table structure.
47. How can you optimize SQL queries?
Use indexes, avoid unnecessary columns, use joins wisely.
48. What is a deadlock?
Situation where two or more transactions block each other.
49. What is the default isolation level in SQL?
Read committed (varies by DBMS).
50. What is a data warehouse?
Centralized repository for large amounts of data used for reporting and analysis.

50 Most Asked Java Coding Questions with Answers

1. Print "Hello World".

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

2. Check if a number is even or odd.

int num = 10;


if (num % 2 == 0) System.out.println("Even");
else System.out.println("Odd");

3. Find factorial of a number (using loop).

int fact = 1, n = 5;
for (int i = 1; i <= n; i++) fact *= i;
System.out.println("Factorial: " + fact);

4. Check if a number is prime.

boolean isPrime = true;


int n = 29;
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
isPrime = false; break;
}
}
System.out.println(isPrime ? "Prime" : "Not prime");

5. Reverse a string.

String s = "Java";
String rev = "";
for (int i = s.length()-1; i >= 0; i--) rev += s.charAt(i);
System.out.println(rev);

6. Check palindrome string.

String s = "madam";
String rev = new StringBuilder(s).reverse().toString();
System.out.println(s.equals(rev) ? "Palindrome" : "Not palindrome");
7. Find largest of three numbers.

int a=5, b=10, c=3;


int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("Largest: " + max);

8. Swap two numbers without temp variable.

int a=5, b=10;


a = a + b; b = a - b; a = a - b;
System.out.println("a="+a+", b="+b);

9. Print Fibonacci series up to n terms.

int n=10, a=0, b=1;


for(int i=1; i<=n; i++){
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
}

10. Check Armstrong number.

int num=153, sum=0, temp=num;


while(temp>0){
int digit = temp % 10;
sum += digit*digit*digit;
temp /= 10;
}
System.out.println(sum == num ? "Armstrong" : "Not Armstrong");

11. Find length of a string without using length() method.

String s = "hello";
int count = 0;
for(char c : s.toCharArray()) count++;
System.out.println("Length: " + count);

12. Convert lowercase string to uppercase.

String s = "hello";
System.out.println(s.toUpperCase());

13. Count vowels in a string.

String s = "education";
int count = 0;
for(char c : s.toLowerCase().toCharArray()){
if("aeiou".indexOf(c) != -1) count++;
}
System.out.println("Vowels: " + count);

14. Print multiplication table of a number.

int n = 5;
for(int i=1; i<=10; i++) System.out.println(n + " x " + i + " = " + (n*i));

15. Find ASCII value of a character.

char c = 'A';
int ascii = c;
System.out.println("ASCII: " + ascii);

16. Check if string contains only digits.

String s = "12345";
boolean isDigit = s.matches("\\d+");
System.out.println(isDigit ? "Digits only" : "Contains other chars");

17. Find second largest number in array.

int[] arr = {10, 20, 15, 30, 25};


int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE;
for(int n : arr){
if(n > max){
secondMax = max;
max = n;
} else if(n > secondMax && n != max){
secondMax = n;
}
}
System.out.println("Second largest: " + secondMax);

18. Remove duplicates from an array.

int[] arr = {1,2,2,3,4,4,5};


Set<Integer> set = new LinkedHashSet<>();
for(int n : arr) set.add(n);
System.out.println(set);

19. Find sum of elements in array.

int[] arr = {1,2,3,4,5};


int sum = 0;
for(int n : arr) sum += n;
System.out.println("Sum: " + sum);

20. Find average of numbers in array.

int[] arr = {2,4,6,8};


double avg = 0;
int sum = 0;
for(int n : arr) sum += n;
avg = (double) sum / arr.length;
System.out.println("Average: " + avg);

21. Check if array is sorted ascending.

int[] arr = {1,2,3,4,5};


boolean sorted = true;
for(int i=0; i<arr.length-1; i++){
if(arr[i] > arr[i+1]){
sorted = false; break;
}
}
System.out.println(sorted ? "Sorted" : "Not sorted");

22. Find largest element in array.

int[] arr = {5,9,2,8};


int max = arr[0];
for(int n : arr) if(n > max) max = n;
System.out.println("Largest: " + max);

23. Find smallest element in array.

int[] arr = {5,9,2,8};


int min = arr[0];
for(int n : arr) if(n < min) min = n;
System.out.println("Smallest: " + min);

24. Find common elements between two arrays.

int[] arr1 = {1,2,3};


int[] arr2 = {2,3,4};
Set<Integer> set = new HashSet<>();
for(int n : arr1) set.add(n);
for(int n : arr2){
if(set.contains(n)) System.out.print(n + " ");
}

25. Find frequency of each character in a string.

String s = "java";
Map<Character, Integer> freq = new HashMap<>();
for(char c : s.toCharArray()){
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq);

26. Convert array to ArrayList.

String[] arr = {"a","b","c"};


List<String> list = new ArrayList<>(Arrays.asList(arr));
System.out.println(list);

27. Check if two strings are anagrams.

String s1 = "listen", s2 = "silent";


char[] a1 = s1.toCharArray(), a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
System.out.println(Arrays.equals(a1, a2) ? "Anagrams" : "Not anagrams");

28. Print all prime numbers between 1 and 100.

for(int num=2; num<=100; num++){


boolean prime = true;
for(int i=2; i<=num/2; i++){
if(num % i == 0){
prime = false; break;
}
}
if(prime) System.out.print(num + " ");
}

29. Count words in a string.

String s = "Java is awesome";


String[] words = s.trim().split("\\s+");
System.out.println("Words count: " + words.length);

30. Find duplicate elements in an array.

int[] arr = {1,2,3,2,1};


Set<Integer> set = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for(int n : arr){
if(!set.add(n)) duplicates.add(n);
}
System.out.println("Duplicates: " + duplicates);

31. Print pattern (triangle) of stars.

int rows = 5;
for(int i=1; i<=rows; i++){
for(int j=1; j<=i; j++){
System.out.print("* ");
}
System.out.println();
}

32. Find sum of digits of a number.

int num = 1234, sum=0;


while(num>0){
sum += num%10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);

33. Check if string contains only alphabets.

String s = "abcXYZ";
boolean alpha = s.matches("[a-zA-Z]+");
System.out.println(alpha ? "Only alphabets" : "Others present");

34. Find ASCII value of a character.

char c = 'Z';
int ascii = (int) c;
System.out.println("ASCII: " + ascii);
35. Convert integer to string.

int n = 100;
String s = String.valueOf(n);
System.out.println(s);

36. Convert string to integer.

String s = "123";
int n = Integer.parseInt(s);
System.out.println(n);

37. Check leap year.

int year = 2024;


boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
System.out.println(leap ? "Leap year" : "Not leap year");

38. Print Fibonacci series using recursion.

static int fib(int n){


if(n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
for(int i=0; i<10; i++){
System.out.print(fib(i) + " ");
}

39. Find sum of even numbers in an array.

int[] arr = {1,2,3,4,5,6};


int sum = 0;
for(int n : arr){
if(n % 2 == 0) sum += n;
}
System.out.println("Sum even: " + sum);

40. Find GCD of two numbers.

int a=24, b=18;


while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
System.out.println("GCD: " + a);

41. Find LCM of two numbers.

int a=12, b=18;


int gcd = 1;
int min = Math.min(a,b);
for(int i=min; i>0; i--){
if(a%i==0 && b%i==0){
gcd = i; break;
}
}
int lcm = (a*b)/gcd;
System.out.println("LCM: " + lcm);

42. Convert decimal to binary.

int num = 10;


String binary = Integer.toBinaryString(num);
System.out.println(binary);

43. Convert binary to decimal.

String binary = "1010";


int decimal = Integer.parseInt(binary, 2);
System.out.println(decimal);

44. Check if number is palindrome.

int num = 121, rev = 0, temp = num;


while(temp > 0){
int digit = temp % 10;
rev = rev * 10 + digit;
temp /= 10;
}
System.out.println(num == rev ? "Palindrome" : "Not palindrome");

45. Print all permutations of a string.


(Advanced, you can ask if want full code.)
46. Count occurrence of a character in a string.

String s = "banana";
char c = 'a';
int count = 0;
for(char ch : s.toCharArray()){
if(ch == c) count++;
}
System.out.println("Count: " + count);

47. Sort array using Arrays.sort().

int[] arr = {5,3,1,2};


Arrays.sort(arr);
System.out.println(Arrays.toString(arr));

48. Reverse array elements.

int[] arr = {1,2,3,4};


for(int i=0, j=arr.length-1; i<j; i++, j--){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println(Arrays.toString(arr));

49. Print multiplication table using nested loops.


for(int i=1; i<=10; i++){
for(int j=1; j<=10; j++){
System.out.print(i*j + "\t");
}
System.out.println();
}

50. Implement a simple class with encapsulation.

class Person {
private String name;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.getName());
}
}

You might also like