0% found this document useful (0 votes)
14 views9 pages

Java Sample Code Examples

The document contains various Java programming examples demonstrating concepts such as static methods, final methods and variables, inheritance, encapsulation, method overloading, dynamic method dispatch, and array manipulations. It includes code snippets for calculating areas, managing bank accounts, handling multiple interfaces, and performing matrix operations. Each example illustrates specific programming principles and their implementations in Java.
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)
14 views9 pages

Java Sample Code Examples

The document contains various Java programming examples demonstrating concepts such as static methods, final methods and variables, inheritance, encapsulation, method overloading, dynamic method dispatch, and array manipulations. It includes code snippets for calculating areas, managing bank accounts, handling multiple interfaces, and performing matrix operations. Each example illustrates specific programming principles and their implementations in Java.
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

1. 1.

Static method to calculate area of a circle

public class CircleArea {


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

public static void main(String[] args) {


[Link]("Area: " + calculateArea(5));
}
}

2. 2. Final method in superclass and attempt to override

class Parent {
public final void display() {
[Link]("Final method in Parent");
}
}

class Child extends Parent {


// Uncommenting below will cause a compile-time error
// public void display() {
// [Link]("Trying to override");
// }
}

3. 3. Final variable initialized in constructor

public class FinalVariable {


final int value;

public FinalVariable(int val) {


value = val;
}

public void show() {


[Link]("Value: " + value);
}

public static void main(String[] args) {


FinalVariable obj = new FinalVariable(10);
[Link]();
}
}

4. 4. Static block for class initialization

public class StaticBlockExample {


static {
[Link]("Static block called before main");
}

public static void main(String[] args) {


[Link]("Main method executed");
}
}

5. 5. Static variable shared among instances

public class StaticVariableDemo {


static int count = 0;

public StaticVariableDemo() {
count++;
}

public static void main(String[] args) {


new StaticVariableDemo();
new StaticVariableDemo();
[Link]("Count: " + count);
}
}

6. 6. Employee and Manager inheritance

class Employee {
String name;
double salary;

Employee(String name, double salary) {


[Link] = name;
[Link] = salary;
}
}

class Manager extends Employee {


double bonus;

Manager(String name, double salary, double bonus) {


super(name, salary);
[Link] = bonus;
}

public void display() {


[Link]("Name: " + name + ", Total Salary: " + (salary + bonus));
}
}

7. 7. Constructor chaining with super()

class A {
A() {
[Link]("Constructor A");
}
}

class B extends A {
B() {
super();
[Link]("Constructor B");
}

public static void main(String[] args) {


B obj = new B();
}
}

8. 8. Dog overrides Animal

class Animal {
public void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


public void sound() {
[Link]("Dog barks");
}

public static void main(String[] args) {


Dog d = new Dog();
[Link]();
}
}

9. 9. Multiple interfaces in HybridVehicle

interface Engine {
void startEngine();
}

interface Battery {
void chargeBattery();
}

class HybridVehicle implements Engine, Battery {


public void startEngine() {
[Link]("Engine started");
}

public void chargeBattery() {


[Link]("Battery charging");
}

public static void main(String[] args) {


HybridVehicle hv = new HybridVehicle();
[Link]();
[Link]();
}
}

10. 10. Multi-level inheritance


class A {
void greet() {
[Link]("Hello from A");
}
}

class B extends A {}
class C extends B {}

public class Test {


public static void main(String[] args) {
C obj = new C();
[Link]();
}
}

11. 11. BankAccount encapsulation

public class BankAccount {


private int accountNumber;
private double balance;

public int getAccountNumber() {


return accountNumber;
}

public void setAccountNumber(int number) {


accountNumber = number;
}

public double getBalance() {


return balance;
}

public void setBalance(double amount) {


balance = amount;
}
}

12. 12. Student with encapsulation

public class Student {


private int rollNumber;
private String name;
private String grade;

public void setData(int r, String n, String g) {


rollNumber = r;
name = n;
grade = g;
}

public void display() {


[Link]("Roll: " + rollNumber + ", Name: " + name + ", Grade: " +
grade);
}

public static void main(String[] args) {


Student s = new Student();
[Link](101, "Ravi", "A");
[Link]();
}
}

13. 13. Method overloading

public class OverloadExample {


void display(int a) {
[Link]("Integer: " + a);
}

void display(String b) {
[Link]("String: " + b);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
[Link](10);
[Link]("Hello");
}
}

14. 14. Override area() in Circle and Rectangle

class Shape {
double area() {
return 0;
}
}

class Circle extends Shape {


double radius = 5;
double area() {
return [Link] * radius * radius;
}
}

class Rectangle extends Shape {


double length = 4, breadth = 5;
double area() {
return length * breadth;
}
}

15. 15. Dynamic method dispatch

class Parent {
void show() {
[Link]("Parent");
}
}

class Child extends Parent {


void show() {
[Link]("Child");
}

public static void main(String[] args) {


Parent ref = new Child();
[Link]();
}
}

16. 16. Varargs sum

public class VarargsSum {


static void sum(int... numbers) {
int total = 0;
for (int n : numbers)
total += n;
[Link]("Sum: " + total);
}

public static void main(String[] args) {


sum(1, 2, 3, 4, 5);
}
}

17. 17. Max from varargs

public class MaxVarargs {


static double max(double... values) {
double max = Double.MIN_VALUE;
for (double v : values) {
if (v > max) max = v;
}
return max;
}

public static void main(String[] args) {


[Link]("Max: " + max(1.2, 3.4, 5.6));
}
}

18. 18. Name with multiple phone numbers

public class Contact {


void printContact(String name, String... phones) {
[Link]("Name: " + name);
for (String p : phones)
[Link]("Phone: " + p);
}

public static void main(String[] args) {


new Contact().printContact("Amit", "123", "456", "789");
}
}

19. 19. Print even numbers from array

public class EvenNumbers {


public static void main(String[] args) {
int[] arr = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29};
for (int num : arr) {
if (num % 2 == 0)
[Link](num);
}
}
}

20. 20. Average of array

public class ArrayAverage {


static double average(int[] arr) {
int sum = 0;
for (int num : arr) sum += num;
return (double) sum / [Link];
}

public static void main(String[] args) {


int[] data = {10, 20, 30, 40, 50};
[Link]("Average: " + average(data));
}
}

21. 21. Transpose of 3x3 matrix

public class MatrixTranspose {


public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[j][i] + " ");
}
[Link]();
}
}
}

22. 22. Add two 2x2 matrices

public class MatrixAddition {


public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];

for (int[] row : c) {


for (int n : row)
[Link](n + " ");
[Link]();
}
}
}

23. 23. Jagged array

public class JaggedArray {


public static void main(String[] args) {
int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2};
jagged[1] = new int[]{3, 4, 5};
jagged[2] = new int[]{6};

for (int[] row : jagged) {


for (int n : row)
[Link](n + " ");
[Link]();
}
}
}

24. 24. finalize() method

public class FinalizeDemo {


protected void finalize() {
[Link]("finalize() called");
}

public static void main(String[] args) {


FinalizeDemo obj = new FinalizeDemo();
obj = null;
[Link](); // Suggest GC
}
}

25. 25. [Link]() and finalize observation

public class Temp {


protected void finalize() {
[Link]("finalize() called for Temp");
}

public static void main(String[] args) {


Temp t = new Temp();
t = null;
[Link]();
[Link]("End of main");
}
}

Common questions

Powered by AI

Constructor chaining is a technique where a constructor calls another constructor in the same class or its superclass using this() or super(). Its significance lies in reusing constructor logic and ensuring orderly initialization. In classes A and B, chaining occurs with class B's constructor calling super() to invoke class A's constructor first. This ensures that all initialization steps defined in class A are executed before class B's constructor logic .

Attempting to override a final method in a subclass will result in a compile-time error, as final methods cannot be overridden. In the given example, the Parent class defines a final method display(). If the Child class tries to override this method, it will cause a compile error since final methods are intended to be non-overridable to maintain the method’s original behavior across subclasses .

Polymorphism allows a single function or method to operate in different data contexts. Dynamic method dispatch is a polymorphic behavior where the method to be executed is determined at runtime. With the Parent and Child classes, a Parent class reference (ref) points to a Child object. When ref.show() is called, the Child class's show() method executes due to dynamic dispatch, demonstrating runtime polymorphism, allowing behavior overriding and flexibility in extending class functionality .

Varargs (variable arguments) in Java allow a method to accept zero or more arguments of a specified type. In the VarargsSum program, the sum(int... numbers) method uses varargs to accept multiple integer inputs, making it flexible for summing an array of numbers. Inside the method, a loop iterates over the numbers, adding them to compute the total sum, which is then printed .

Method overloading occurs when multiple methods have the same name but different parameter lists within the same class. In the OverloadExample class, the display() method is overloaded with two versions: one accepts an integer parameter and the other a string. This allows the method to handle different types of input data, executing the corresponding logic for each data type when called .

A class method can be protected from being overridden by declaring it as final. This ensures that subclasses cannot modify the method’s behavior, preserving its intended functionality across all class hierarchies. In the Parent class, marking the display() method as final prevents subclasses like Child from altering or overriding it, which can be beneficial for maintaining consistent logic or adhering to specific business rules .

Static variables are shared among all instances of a class, whereas instance variables are unique to each instance. In the StaticVariableDemo class, the static variable count is incremented each time an instance of the class is created, and its value is shared across all instances. Therefore, after creating two instances, the count value is 2, illustrating that all instances reference the same static variable .

The HybridVehicle class demonstrates Java's multiple inheritance feature via interfaces. By implementing Engine and Battery interfaces, HybridVehicle inherits the behaviors defined by both, allowing a single class to use methods from multiple sources. This illustrates polymorphic capabilities in action, enabling HybridVehicle to start an engine and charge a battery, showing a real-world application of interfaces to simulate complex vehicle functionalities .

In the context of class inheritance, method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass. When class Dog, which extends Animal, overrides the sound() method, calling sound() on a Dog instance will execute the Dog's implementation ('Dog barks'), rather than the Animal's method ('Animal makes sound').

Encapsulation is a principle that restricts access to certain parts of an object and prevents external interference and misuse of class data by using access modifiers like private. The BankAccount class demonstrates encapsulation by making its accountNumber and balance private and exposing public methods (getAccountNumber, setAccountNumber, getBalance, setBalance) to access and modify these fields safely, thus maintaining integrity and security of the data .

You might also like