0% found this document useful (0 votes)
7 views11 pages

Java Programming Examples and Concepts

The document contains various Java programming examples, including basic programs like HelloWorld, Fahrenheit to Celsius conversion, and Palindrome checking. It also includes more advanced topics such as Heap Sort, Matrix Multiplication, Inheritance, Interfaces, and Multithreading. Each section provides code snippets demonstrating the respective concepts and functionalities.

Uploaded by

harinineha97
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)
7 views11 pages

Java Programming Examples and Concepts

The document contains various Java programming examples, including basic programs like HelloWorld, Fahrenheit to Celsius conversion, and Palindrome checking. It also includes more advanced topics such as Heap Sort, Matrix Multiplication, Inheritance, Interfaces, and Multithreading. Each section provides code snippets demonstrating the respective concepts and functionalities.

Uploaded by

harinineha97
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

Java

[Link]

2. Fahrenheit to Celsius
3. Find Odd or Even

4. Palindrome
5, Display Date and Time

6. Fibonacci Series

7. Heap Sort
public class Heapsort {
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
[Link]("Original Array:");
printArray(arr);
heapSort(arr);
[Link]("Sorted Array:");
printArray(arr);
}
public static void heapSort(int[] arr) {
int n = [Link];
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

public static void heapify(int[] arr, int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i){
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}

public static void printArray(int[] arr) {


for (int num : arr) {
[Link](num + " ");
}
[Link]();
}
}

Output:
8. Matrix Multiplication
import [Link];
public class martixmul{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the dimensions of the matrices (n x m and
m x p):");
int n = [Link](); // Rows of the first matrix
int m = [Link](); // Common dimension
int p = [Link](); // Columns of the second matrix

int[][] matrix1 = new int[n][m];


int[][] matrix2 = new int[m][p];

[Link]("Enter elements for the first matrix:");


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix1[i][j] = [Link]();
}
}

[Link]("Enter elements for the second matrix:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
matrix2[i][j] = [Link]();
}
}

int[][] result = new int[n][p];

for (int i = 0; i < n; i++) {


for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
[Link]("Resultant Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}

[Link]();
}
}

Output:

9. Remove Elements from an ArrayList


10. Java Program to print the duplicate elements of an array
11. Java Program to print the elements of an array

12. Java Program to count the total number of characters in a string

13. Package
package pack;
public class A {
public void msg() {
[Link]("Welcom to java");
}
}
14. Interface
public interface Shape {

double calculateArea();
}
class Circle1 implements Shape {
private double radius;

public Circle1(double radius) {


[Link] = radius;
}
public double calculateArea() {
return [Link] * radius * radius;
}
}

15. Inheritance
class A {
int a=10;
public void display1() {
[Link](a);
}
}
class B extends A {
int b=10;
public void display2() {
[Link](b+a);
}
}
class C extends A {
int c=10;
public void display3() {
[Link](b+a+c);
}
}

[Link]
class two extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
int a=i*2;
[Link]("2"+"*"+i+"="+a);
}
}
}
class three extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
int a=i*3;
[Link]("3"+"*"+i+"="+a);
}
}
}
class four extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
int a=i*4;
[Link]("4"+"*"+i+"="+a);
}
}
}
public class multithreading {
public static void main(String args[]) {
two t1=new two();
three t2=new three();
four t3=new four();
[Link]();
[Link]();
[Link]();
}
}

Common questions

Powered by AI

The inheritance structure provided demonstrates how derived classes can reuse code from their parent class. Class B and Class C inherit the 'display1' method from Class A, reducing code redundancy. By deriving common functionalities (such as variable 'a' and method display1()) from a base class, it allows maintaining or modifying the behavior in one place rather than spreading duplicated code across several classes. This maximizes code reusability, maintainability, and readability .

The 'heapify' function ensures that a subtree rooted with node i is a max heap. It compares the node with its children and swaps it with the largest of them if needed. This process is recursively applied downward from the node if a swap was made, ensuring that the subtree follows max heap properties. During the sorting process in Heap Sort, heapify is called to reconstruct the heap structure whenever an element is moved from the root to the end of the heap .

ArrayLists offer dynamic sizing, unlike traditional arrays with a fixed size. They provide convenient built-in methods for operations such as adding, removing, and resizing elements, which would require manual manipulation and potential error-prone coding with arrays. In the provided example, removing elements from an ArrayList simplifies as compared to rearranging or resizing a traditional array, enhancing efficiency in operations that involve frequent inserts and deletions .

Java packages provide a namespace and organizational framework that helps group related classes and interfaces together. This modular structure enhances the architecture by avoiding name clashes of classes in different packages, and facilitating easier maintenance, readability, and reusability of code. In the package example provided, the use of a package delineates a specific context within which classes and interfaces reside, promoting coherent program design and reduced complexity in large-scale applications .

Without proper synchronization, issues such as race conditions, inconsistent data states, and deadlocks can arise in multithreaded environments. Race conditions happen when threads compete to modify shared data, leading to unpredictable results. Synchronization mechanisms, like Atomic variables, Locks, Synchronization blocks, and Volatile keywords, mitigate such issues by ensuring that only one thread updates a shared variable at any given time, or allowing visibility of changes in multithreaded environments .

Interfaces allow the definition of methods that must be implemented by any class that 'implements' the interface, without providing implementations themselves. This abstraction provides a flexible design by decoupling interface specifications from implementation. The 'Shape' interface assures that every class providing a specific behavior guarantees to implement the 'calculateArea' method, promoting extensibility by allowing new shapes to be added without altering existing code .

Exception handling in Java ensures that the program can manage and recover from unexpected events and errors without crashing. In input-sensitive operations like the 'matrixmul' class, it is crucial to handle potential exceptions like invalid input types or out-of-bounds accesses systematically. Utilizing try-catch blocks around input operations or array accesses safeguards against such runtime exceptions, which enhances the application's robustness and user experience by providing controlled feedback instead of abrupt terminations .

Matrix multiplication is performed through a nested three-loop structure: the outer loop iterates over the rows of the result matrix, the middle loop iterates over its columns, and the innermost loop iterates over elements to calculate the dot product corresponding to each element in the resulting matrix. The multiplication executes as per mathematical matrix operations where the element at row i and column j of the result is calculated as the sum of the products of elements from row i of the first matrix and column j of the second matrix .

Implementing multithreading allows concurrent execution of two or more threads, leading to more efficient utilization of CPU resources. In the provided example, separate threads calculate multiplications by 2, 3, and 4 independently, potentially reducing execution time compared to a single-threaded approach. It improves performance when dealing with concurrent operations and is particularly advantageous in resource-intensive applications or when handling multiple tasks simultaneously .

Heap Sort algorithm first constructs a max heap for the given array so that the largest element is at the root. The heap property is maintained by modifying the subtree rooted at a node if the node itself changes. The largest element at the root is swapped with the last element of the heap, reducing the heap's size by one element. This process is repeated, ensuring the root always has the largest value among its children, thus maintaining the heap structure through each swap until the array is sorted .

You might also like