Java Notes
Java Notes
return a + b;
static {
// Initialization code
In this example, the code within the static block will be executed when the
class is loaded.
Static Nested Classes: Nested classes that are declared as static are
associated with their outer class rather than with any instance of the outer
class. They can be accessed using the outer class name.
Static Import: The static import feature allows members (fields and
methods) defined in a class as public static to be used in another class
without specifying the class name. This feature was introduced in Java 5.
In this example, after using a static import for PI from java.lang.Math, you
can directly use PI in your code without referencing Math.PI.
2.
Example:
sb.append(" World");
Example:
Example:
sb.delete(5, 11);
Example:
write a java program which will read a string and rewrite it in alphabetical order for eg the word
STRING should be written as GINRST
import java.util.Arrays;
Arrays.sort(chars);
In this program, we first convert the input string into a character array
using the toCharArray() method. Then, we use Arrays.sort() to sort the
characters in alphabetical order. Finally, we create a new string from the
sorted characters using the String constructor and print the result.
Output:
GINRST
This program can be easily modified to accept user input or read from a
file by using Scanner or other input methods.
**Constructor in Java**
**Types of Constructors**
```java
public class MyClass {
// Default Constructor
public MyClass() {
// Initialization code
}
}
```
```java
public class Employee {
private String name;
private int age;
// Parameterized Constructor
public Employee(String empName, int empAge) {
name = empName;
age = empAge;
}
}
```
```java
public class Point {
private int x;
private int y;
// Copy Constructor
public Point(Point other) {
this.x = other.x;
this.y = other.y;
}
}
```
```java
public class MyClass {
static {
// Static initialization code
}
}
```
```java
public class Singleton {
private static Singleton instance;
// Private Constructor
private Singleton() {
// Initialization code
}
**Conclusion**
Constructors in Java play a crucial role in initializing objects and setting up their
initial state. They provide flexibility in terms of how objects can be initialized and
allow for different types of initialization logic based on the requirements of the
application.
Example:
int x = 10;
if (x > 5) {
In this example, the condition x > 5 is evaluated, and if it’s true, the code
inside the curly braces is executed.
int y = 7;
if (y % 2 == 0) {
System.out.println("y is even");
} else {
System.out.println("y is odd");
Example:
} else {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
default:
In this example, based on the value of day, the corresponding dayName will
be assigned.
Example:
int p = 10;
write a java program which defines a class square and calculate area of square by creating two object
of same class with different values
this.sideLength = sideLength;
}
Now, let’s create two objects of the Square class with different values for
the side length:
We can now use the area method of each object to calculate their areas:
As you can see, the area of the small square is 16, and the area of the
large square is 64.
When a Java program creates objects, they are allocated memory on the
heap. As the program runs, some of these objects may no longer be
needed or referenced by the program. In such cases, the garbage
collector identifies these unreferenced objects and reclaims their memory,
making it available for future allocations. The garbage collection process
typically involves several steps:
Each type of garbage collector has its own characteristics and trade-offs in
terms of throughput, latency, and memory overhead, allowing developers
to choose the most suitable one based on their application’s
requirements.
Conclusion
Garbage collection is a fundamental aspect of memory management in
Java, ensuring that unused memory is reclaimed automatically.
Understanding the principles of garbage collection and being familiar with
different types of garbage collectors empowers developers to make
informed decisions when optimizing memory usage and performance in
Java applications.
The purpose of an initialization code block is to set the initial values of the
object’s fields, and to perform any other necessary setup tasks before the
object is ready to use. This can include things like setting default values
for fields, loading data from a file or database, or connecting to a network
resource.
this.name = name;
this.age = age;
It’s important to note that initialization code blocks are only executed
once, when an object is created. If you need to perform initialization tasks
multiple times, you may need to use a different approach, such as using a
static block or a method that is called before the object is created.
Access control modifiers play a crucial role in defining the scope and
accessibility of classes and members in Java programs. They help in
maintaining the integrity and security of the codebase by controlling how
different parts of the program interact with each other.
Inheritance in Java
discuss methods overloading and method overriding with programming example in java
Method Overloading:
return a + b;
return a + b;
In this example, the add method is overloaded with two versions - one that
takes two integers as parameters and another that takes two doubles.
When calling the add method, the compiler determines which version to
invoke based on the argument types.
Method Overriding:
class Animal {
System.out.println("Some sound");
@Override
System.out.println("Bark");
In this example, the Dog class overrides the makeSound method inherited
from the Animal class by providing its own implementation. When
calling makeSound on an instance of Dog, it will print “Bark” instead of
“Some sound”.
Key Differences:
1. Method overloading involves multiple methods with the same name
but different parameters within the same class, while method
overriding involves redefining a method in a subclass that is already
present in its superclass.
2. Method overloading is determined at compile time based on the
number and type of arguments, while method overriding is
determined at runtime based on the actual object type.
write a program in java a class "Employee" contain two fields "Name" and "Designation"extends the
class to class "Department" it contains "Dept_no" and "Dept_name" in interface named "Company"
using the above classes and interface get the appropriate information and display it
// Company interface
interface Company {
void displayCompanyInfo();
// Employee class
class Employee {
String name;
String designation;
this.designation = designation;
// Department class
int deptNo;
String deptName;
super(name, designation);
this.deptNo = deptNo;
this.deptName = deptName;
}
@Override
department.displayEmployeeInfo();
department.displayCompanyInfo();
Output:
The code for the Equitriangle class might look like this:
package Mypack;
To import the Mypack package in another class and use the Equitriangle
class, you can follow these steps:
import Mypack.Equitriangle;
int side1 = 5;
int side2 = 5;
int side3 = 5;
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
8) A Java abstract class can have Members of a Java interface are public
class members like private, by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
In Java, input stream classes are used to read data from a source. There
are several methods of input stream classes in Java, each with its own
specific use and functionality. Here are three common methods of input
stream classes in Java:
To create a Java program that reads a .txt file and displays its content on
the screen, you can use the following code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
String line;
System.out.println(line);
} catch (IOException e) {
In this program, we use the BufferedReader class to read the file line by
line and then display each line using System.out.println().
To use this program, you need to replace "example.txt" with the actual file
name you want to read.
Save this code in a file named ReadTxtFile.java and compile it using javac
ReadTxtFile.java. Then, run the program using java ReadTxtFile.
Exception handling in Java is done using five keywords: try, catch, throw,
throws, and finally.
try: The try block encloses the code that may throw an exception.
catch: The catch block is used to handle the exception. It catches
the exception thrown by the try block.
throw: The throw keyword is used to explicitly throw an exception.
throws: The throws keyword is used to declare the exceptions that
a method may throw.
finally: The finally block is used to execute important code such as
closing a file or releasing resources regardless of whether an
exception is thrown or not.
try {
// handle ExceptionType1
// handle ExceptionType2
} finally {
}
In this example, if an exception of type ExceptionType1 is thrown in the
try block, it will be caught and handled in the first catch block. If no
exception is thrown or if it is of a different type, the finally block will still
be executed.
In Java, wrapper classes are used to convert primitive data types into
objects. They provide a way to use primitive data types as objects. There
are eight primitive data types in Java: byte, short, int, long, float, double,
char, and boolean. Each of these primitive data types has a corresponding
wrapper class in Java. The wrapper classes are as follows:
Wrapper classes are particularly useful when working with collections such
as ArrayList, where only objects can be stored. They also provide utility
methods for converting strings to their corresponding primitive types and
vice versa.
explain purpose of streams discuss byte and character stream classes in java
In Java, streams are a fundamental concept used for input and output
operations. The purpose of streams is to provide a consistent way to
handle different types of data sources and destinations, such as files,
network connections, and in-memory data. Streams are used to read data
from a source or write data to a destination in a sequential manner.
Byte streams in Java are used for handling raw binary data. They are
represented by classes that end with “InputStream” and “OutputStream”.
Some commonly used byte stream classes include:
Character streams in Java are used for handling text-based data. They are
represented by classes that end with “Reader” and “Writer”. Some
commonly used character stream classes include:
Character stream classes are suitable for handling textual data, such as
reading from or writing to text files.
explain the usage of try, catch and throw with example in java
In Java, try, catch, and throw are keywords used for exception handling.
Exception handling is a mechanism to handle runtime errors and
exceptional situations that may occur during the execution of a program.
These keywords allow developers to write code that can gracefully handle
and recover from unexpected situations.
Try: The try block is used to enclose the code that may throw an
exception. It is followed by one or more catch blocks and/or a finally block.
When an exception occurs within the try block, it is thrown.
Catch: The catch block is used to catch and handle exceptions that are
thrown in the try block. Each catch block is associated with a specific type
of exception. If an exception of the specified type occurs, the
corresponding catch block is executed.
Here’s an example to illustrate the usage of try, catch, and throw in Java:
public class ExceptionExample {
try {
} catch (ArithmeticException e) {
if (num2 == 0) {
By using try, catch, and throw, developers can ensure that their programs
handle unexpected situations gracefully and provide meaningful feedback
to users when errors occur.
what are the uses of multithreading in java
Multithreading in Java
1. New: When a thread is created but not yet started, it is in the new
state.
2. Runnable: Once the thread’s start() method is invoked, the thread
moves to the runnable state, indicating that it is ready to be
scheduled for execution by the JVM.
3. Blocked: A thread transitions to the blocked state when it is waiting
for a monitor lock to enter a synchronized block or method.
4. Waiting: Threads can enter the waiting state due to explicit calls to
wait(), join(), or park() methods, where they await notification or
interruption.
5. Timed Waiting: Threads can also enter a timed waiting state as a
result of calling methods like sleep() or join() with a specified
timeout.
6. Terminated: When a thread completes its execution or is explicitly
terminated, it enters the terminated state and cannot be restarted.
Understanding these methods and their impact on the thread life cycle is
essential for effective multithreaded programming in Java.
write a program to create a thread using thread class and runnabl interface
To create a thread in Java, you can use either the Thread class or
the Runnable interface. Below are examples of how to create a thread
using both methods.
myThread.start();
}
In this example, a class MyThread extends the Thread class and overrides
the run method. In the Main class, an instance of MyThread is created and
started using the start method.
thread.start();
The Object class in Java provides three essential methods for inter thread
communication: wait(), notify(), and notifyAll(). These methods are used in
conjunction with synchronized blocks to enable threads to communicate
with each other. When a thread calls the wait() method within a
synchronized block, it releases the lock on the object and enters a waiting
state until another thread notifies it using the notify() or notifyAll()
method. The notify() method wakes up one waiting thread, while
notifyAll() wakes up all waiting threads. These methods are fundamental
for implementing producer-consumer scenarios, where one thread
produces data while another consumes it.
In Java, the sleep() and wait() methods are used for managing threads
and synchronization. Both methods have different purposes and are used
in different contexts.
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Here, milliseconds is the duration for which the thread will sleep.
The sleep() method throws an InterruptedException, so it needs to be
handled using a try-catch block.
synchronized (object) {
try {
object.wait();
} catch (InterruptedException e) {
Here, object is the object on which the wait operation is being performed.
The wait() method must be called from within a synchronized context,
i.e., within a synchronized block or method.
The wait() method causes the current thread to release the lock on the
object and enter a waiting state until another thread notifies it using
the notify() or notifyAll() methods.