UPDATED Java Suggestion 200
UPDATED Java Suggestion 200
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Subclass-specific method
}
}
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. Single Inheritance
2. Multilevel Inheritance
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Intermediate subclass
class Mammal extends Animal {
void breathe() {
System.out.println("Mammal breathes air.");
}
}
// Derived subclass
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}
3. Hierarchical Inheritance
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
Example:
interface CanFly {
void fly();
}
interface CanSwim {
void swim();
}
@Override
public void swim() {
System.out.println("Duck swims");
}
}
Example:
interface CanFly {
default void fly() {
System.out.println("Flying with wings");
}
}
interface CanSwim {
default void swim() {
System.out.println("Swimming with fins");
}
}
Example:
interface CanFly {
default void action() {
System.out.println("Flying with wings");
}
}
interface CanSwim {
default void action() {
System.out.println("Swimming with fins");
}
}
Example:
void eat() {
System.out.println("Bird is eating");
}
}
interface CanFly {
void fly();
}
interface CanSwim {
void swim();
}
@Override
public void fly() {
System.out.println("Duck flies");
}
@Override
public void swim() {
System.out.println("Duck swims");
}
}
// Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Single inheritance
class Mammal extends Animal {
void breathe() {
System.out.println("Mammal breathes air.");
}
}
@Override
public void swim() {
System.out.println("Duck swims.");
}
}
Explanation
1. Single Inheritance:
2. Multilevel Inheritance:
Bat class extends the Mammal class, which in turn extends the Animal
class.
3. Hierarchical Inheritance:
Class Structure:
class A {
void foo() {
System.out.println("A's foo");
}
}
class B extends A {
void foo() {
System.out.println("B's foo");
}
}
class C extends A {
void foo() {
System.out.println("C's foo");
}
}
class D extends B, C {
// Ambiguity: Should D inherit B's foo() or C's foo()?
}
Class Structure:
Example:
// Interface A
interface A {
void foo();
}
// Interface B
interface B {
void foo();
}
Explanation
1. Interface A and B:
Both interfaces declare a method foo().
2. Class D:
D implements both interfaces A and B.
1. Abstract Methods:
1. Achieving Abstraction:
2. Multiple Inheritance:
Java does not support multiple inheritance of classes to avoid
complexity and ambiguity. However, a class can implement multiple
interfaces, which allows it to inherit multiple sets of methods.
3. Loose Coupling:
4. Flexibility in Design:
Example of an Interface
// Abstract method
void makeSound();
@Override
public void makeSound() {
System.out.println("Bark");
@Override
System.out.println("Meow");
1. Abstract Methods:
1. Achieving Abstraction:
2. Multiple Inheritance:
3. Loose Coupling:
4. Flexibility in Design:
Interfaces provide flexibility in design and development. They allow
for different implementations of the same set of methods, which
can be swapped interchangeably in the system.
In this example:
Summary
What is an Interface?
Key Points:
Method Signatures : Only method declarations are allowed. No
method bodies.
Constants: Variables defined in interfaces are implicitly public,
static, and final.
Multiple Inheritance : A class can implement multiple interfaces.
Example of an Interface
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
Summary
In this example:
1. Built-in Packages : These are packages that come with the Java
Development Kit (JDK) and provide core functionality. Examples
include java.lang, java.util, java.io, etc.
2. User-defined Packages: These are packages created by developers
to organize their code and avoid name conflicts.
Built-in Packages
These packages are provided by the Java API and contain a large set
of ready-made classes and interfaces for common tasks.
Example:
1. java.lang Package: Automatically imported by the Java compiler.
Contains fundamental classes like String, Math, System, etc.
2. java.util Package: Contains utility classes like ArrayList,
HashMap, Date, etc.
import java.util.ArrayList;
public class BuiltInPackageExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
for (String s : list) {
System.out.println(s);
}
}
}
1. command to compile the classes.
2. Use the Package: Use the import statement to access the classes
and interfaces in the package.
Example:
File: Utils.java
package com.example.utils;
System.out.println(message);
javac -d . Utils.java
Use the Package: Create another class to use the Utils class.
File: Main.java
import com.example.utils.Utils;
javac Main.java
java Main
Directory Structure
project
└ ── com
└ ── example
└ ── utils
└ ──
Utils.javaMain.java
Summary
Step-by-Step Instructions
Directory structure:
calculator
└── Calculator.java
Calculator.java:
package calculator;
Test.java:
import calculator.Calculator;
int a = 10;
int b = 5;
Directory Structure
project
├ ── calculator
│ └── Calculator.java
└── Test.java
Expected Output
When you run the Test class, you should see the following output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Summary
1. Create a Package: Define a package with basic arithmetic
operations.
2. Compile the Package: Compile the package classes.
3. Use the Package: Create a test class to use the package and
perform operations.
4. Run the Test Class: Compile and run the test class to see the
results.
Example:
class MathOperations {
// Method with two parameters
public int add(int a, int b) {
return a + b;
}
Example:
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}
Summary
Polymorphism: Allows methods or objects to process data
differently based on their actual type.
Compile-time Polymorphism: Achieved by method overloading.
The method to be invoked is determined at compile time.
Runtime Polymorphism: Achieved by method overriding. The
method to be invoked is determined at runtime.
Java Exceptions
Java Errors
Errors, on the other hand, represent serious problems that are
typically beyond the control of the programmer. Errors are not
meant to be caught or handled by the program because they
generally indicate severe issues that cannot be easily recovered
from. Errors are usually caused by the environment or the virtual
machine and typically require intervention by system administrators
or developers.
Example
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
Handling Exceptions
Java Exceptions
Java Errors
Handling Exceptions
Summary
1. try-catch Block
2. try-catch-finally Block
3. try-with-resources Statement
4. Nested try-catch Block
5. Multiple catch Blocks
1. try-catch Block
Example:
try-catch-finally Block
Example:
import java.io.FileInputStream;
import java.io.IOException;
try-with-resources Statement
The try-with-resources statement is used to automatically close
resources (like streams) when they are no longer needed,
eliminating the need for a finally block. The resources declared
within the try-with-resources statement are automatically closed at
the end of the block, even if an exception occurs.
Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Example:
Summary
try-catch Block: Handles exceptions within a specific code block.
try-catch-finally Block: Handles exceptions and executes cleanup
operations.
try-with-resources Statement: Automatically closes resources after
usage.
Nested try-catch Block: Handles exceptions at different levels of
granularity.
Multiple catch Blocks: Handles different types of exceptions
separately.
6. A. What is java Thread and Multi Thread? Explain java Thread
Life cycle with suitable example?
Java Thread
Multi-threading
try {
Thread.sleep(1000); // Give some time for the thread to start
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
thread.join(); // Wait for the thread to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
Summary
class Counter {
private int count = 0;
1. start()
thread1.start();
try {
thread1.join(); // Waits for thread1 to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
}
sleep(long millis)
Purpose: Checks whether the thread is alive (i.e., started but not
terminated).
Example:
public class IsAliveExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running.");
});
thread.start();
System.out.println("Is thread alive? " + thread.isAlive()); //
true
}
}
thread1.start();
thread2.start();
}
}
8. A. What is java Files? How many java files with an example?
What is different between java File bit and stream with an
example?
In Java, the java.io.File class represents a file or directory
pathname. It provides methods for creating, deleting, renaming,
and manipulating files and directories on the file system.
1. Source Files : These are the files that contain Java source code,
typically with a .java extension. Source files are compiled into
bytecode by the Java compiler ( javac).
Example:
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Class Files: These are the files generated by compiling Java source
files. They contain bytecode that can be executed by the Java Virtual
Machine (JVM). Class files have a .class extension.
Example:
Example:
java
Copy code
2. Class Files: These are the files generated by compiling Java source
files. They contain bytecode that can be executed by the Java Virtual
Machine (JVM). Class files have a .class extension.
Example:
1. Java File:
Example:
import java.io.File;
System.out.println("File exists.");
} else {
Stream:
import java.io.FileInputStream;
import java.io.IOException;
int data;
} catch (IOException e) {
e.printStackTrace();
Summary
1. Creating a File
You can create a new file using the createNewFile() method of the
java.io.File class.
import java.io.File;
import java.io.IOException;
Deleting a File
You can delete an existing file using the delete() method of the
java.io.File class.
import java.io.File;
Renaming a File
You can rename an existing file using the renameTo() method of
the java.io.File class.
import java.io.File;
You can check if a file exists using the exists() method of the
java.io.File class.
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Writing to a File
You can write data to a file using various output stream classes such
as FileOutputStream or BufferedWriter.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
Note-VVI
Upper case and Lower case in java Files
you can convert the case of characters in a file by reading the
content of the file, converting the characters to uppercase or
lowercase, and then writing the modified content back to the file.
You can achieve this using input and output stream classes along
with character manipulation.
Here's how you can convert the content of a file to uppercase and
lowercase:
Converting to Uppercase
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
Converting to Lowercase
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
In both examples:
Java constructor
In Java, a constructor is a special method used to initialize objects. It is called when an instance of a
class is created. Constructors have the same name as the class and do not have a return type, not
even void.
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor
class DefaultConstructorExample {
int number;
String text;
// Default constructor
DefaultConstructorExample() {
number = 0;
text = "Default";
}
void display() {
System.out.println("Number: " + number + ", Text: " + text);
}
A parameterized constructor allows you to initialize an object with specific values when it is created.
It takes arguments to set the initial state of the object.
class ParameterizedConstructorExample {
int number;
String text;
// Parameterized constructor
ParameterizedConstructorExample(int num, String str) {
number = num;
text = str;
}
void display() {
System.out.println("Number: " + number + ", Text: " + text);
}
3. Copy Constructor
A copy constructor creates a new object as a copy of an existing object. It takes another instance of
the same class as an argument.
class CopyConstructorExample {
int number;
String text;
// Parameterized constructor
CopyConstructorExample(int num, String str) {
number = num;
text = str;
}
// Copy constructor
CopyConstructorExample(CopyConstructorExample obj) {
number = obj.number;
text = obj.text;
}
void display() {
System.out.println("Number: " + number + ", Text: " + text);
}
Constructor overloading in Java is a concept where a class can have more than one constructor with
different parameter lists. It allows objects of a class to be initialized in different ways. Each
constructor must have a unique signature (i.e., a different number or type of parameters).
class ConstructorOverloadingExample {
int number;
String text;
// Default constructor
ConstructorOverloadingExample() {
number = 0;
text = "Default";
}
void display() {
System.out.println("Number: " + number + ", Text: " + text);
}
Method Overloading
Method overloading in Java is a feature that allows a class to have more than one method with the
same name, provided their parameter lists are different. This can be achieved by varying the number
of parameters, the type of parameters, or both. Method overloading increases the readability of the
program by allowing methods to be invoked in different ways.
class MethodOverloadingExample {
return a + b;
return a + b + c;
return a + b;
System.out.println("Sum of 10, 20 and 30: " + obj.add(10, 20, 30)); // Output: Sum of 10, 20 and 30: 60
System.out.println("Sum of 10.5 and 20.5: " + obj.add(10.5, 20.5)); // Output: Sum of 10.5 and 20.5: 31.0
In this example, the Method Overloading Example class has three overloaded add methods:
1. The first add method takes two integer parameters and returns their sum.
2. The second add method takes three integer parameters and returns their sum.
3. The third add method takes two double parameters and returns their sum.
Array
What is an java Array? Different types of an Array with an example?
In Java, an array is a data structure that allows you to store multiple values of the same type in a
single variable. Arrays are fixed in size, meaning that once they are created, their size cannot be
changed. Each element in an array is accessed using an index, which starts from 0.
1. Single-Dimensional Array
2. Multi-Dimensional Array
1. Single-Dimensional Array
A single-dimensional array is a linear array where elements are stored in a single row. It is the
simplest form of an array.
Example:
2. Multi-Dimensional Array
A multi-dimensional array is an array of arrays. The most common type is the two-dimensional array,
which can be thought of as a table with rows and columns.
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Key Points:
scanner.close();
}
}
Explanation:
1. Scanner Class: We use the Scanner class to read input from the user.
2. Matrix Dimensions: The program first prompts the user to enter the dimensions of the two
matrices.
3. Dimension Check: It checks if the multiplication is possible by ensuring the number of
columns in the first matrix equals the number of rows in the second matrix.
4. Input Matrices: The user is then prompted to enter the elements of both matrices.
5. Matrix Multiplication: The program multiplies the two matrices and stores the result in a
new matrix.
6. Display Result: Finally, it prints the resultant matrix.
String
What is java String? Explain Different String function with one example?
In Java, a String is a sequence of characters. It is a widely used class for handling text data. Strings
in Java are immutable, meaning that once a String object is created, its value cannot be changed.
1. length()
2. charAt(int index)
3. substring(int beginIndex, int endIndex)
4. contains(CharSequence s)
5. indexOf(String str)
6. toLowerCase()
7. toUpperCase()
8. trim()
9. replace(char oldChar, char newChar)
10. equals(Object anObject)
11. equalsIgnoreCase(String anotherString)
Here's a Java program that demonstrates the usage of these String methods:
// 1. length()
// 2. charAt(int index)
System.out.println("Substring (0, 5): " + substring); // Output: Substring (0, 5): Hello
// 4. contains(CharSequence s)
// 5. indexOf(String str)
// 7. toUpperCase()
// 8. trim()
System.out.println("Replaced 'l' with 'p': " + replacedStr); // Output: Replaced 'l' with 'p':
Heppo, Worpd!
}
Explanation of Each Method:
String Buffer
What is java String Buffer? Explain Different String Buffer function with
one example?
1. append()
2. insert()
3. replace()
4. delete()
5. reverse()
6. length()
7. capacity()
8. charAt()
9. substring()
10. setCharAt()
sb.append(" World");
// 2. insert()
sb.insert(5, ",");
// 3. replace()
// 4. delete()
sb.delete(5, 6);
// 5. reverse()
sb.reverse();
// 6. length()
// 7. capacity()
// 9. substring()
// 10. setCharAt()
sb.setCharAt(0, 'H');
In Java, the this keyword is a reference to the current object. It can be used to:
When instance variables and parameters have the same name, the this keyword can be used to
distinguish between them.
class Calculator {
}
}
Different between java final and finally keyword using table format
Abstract class of java
What is Abstract class of java Explain with an example ?
In Java, an abstract class is a class that cannot be instantiated directly. It serves as a blueprint for
other classes to extend and provides common methods and fields that subclasses can implement or
override. Abstract classes may contain abstract methods, which are methods declared without
implementation, meant to be implemented by subclasses.
1. Cannot be Instantiated: You cannot create objects of an abstract class using the new
keyword. It's meant to be extended by other classes.
2. May Contain Abstract Methods: Abstract classes can have abstract methods (methods
without a body), which must be implemented by subclasses.
3. Can Have Concrete Methods: Abstract classes can also have regular (concrete) methods
with implementations.
4. May Have Constructors: Abstract classes can have constructors. When a subclass object is
instantiated, the constructor of the abstract class is also called.
// Abstract class
// Concrete method
System.out.println("Animal is eating");
System.out.println("Bark bark");
}
public class Main {
Providing Common Functionality: Abstract classes can define methods that are common to
all subclasses, ensuring consistency in behavior.
Forcing Subclasses to Implement Methods: Abstract methods enforce that subclasses
provide specific functionality without dictating the exact implementation.
Polymorphism: Abstract classes can be used as types to refer to any subclass object,
facilitating polymorphic behavior.
System.out.println(i);
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
int i = 1;
do {
System.out.println(i);
i++;
Explanation:
for Loop: Executes a block of code repeatedly for a fixed number of times, controlled by a
loop variable initialized, tested, and incremented each iteration.
while Loop: Continuously executes a block of code as long as a specified condition is true. It
tests the condition before executing the block.
do-while Loop: Similar to the while loop but guarantees at least one execution of the block
before testing the condition.
Common Usage:
for Loop: Ideal for iterating over arrays or any situation where the number of iterations is
known.
while Loop: Suitable for scenarios where the number of iterations is not known beforehand
or where the loop condition may change dynamically.
do-while Loop: Useful when you need to execute the loop body at least once, regardless of
whether the condition is initially true or false.
if (i == 3) {
System.out.println(i);
if (i == 3) {
System.out.println(i);
System.out.println(sum(5, 3));
}
public static int sum(int a, int b) {
The switch case statement evaluates a variable or expression against multiple possible constant
values. It provides a concise way to handle multiple branches based on the value of an expression.
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
break;