[Go to site: main page, start]

0% found this document useful (0 votes)
12 views12 pages

Java Programming Examples and Concepts

The document contains a series of Java programming examples covering fundamental concepts such as printing output, command-line arguments, calculating sum and average, checking even/odd numbers, generating Fibonacci series, and more. Each example includes code snippets and sample outputs demonstrating the functionality of the code. Topics also include advanced concepts like inheritance, interfaces, exception handling, file I/O, threading, and GUI programming.

Uploaded by

Unknown Ch
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)
12 views12 pages

Java Programming Examples and Concepts

The document contains a series of Java programming examples covering fundamental concepts such as printing output, command-line arguments, calculating sum and average, checking even/odd numbers, generating Fibonacci series, and more. Each example includes code snippets and sample outputs demonstrating the functionality of the code. Topics also include advanced concepts like inheritance, interfaces, exception handling, file I/O, threading, and GUI programming.

Uploaded by

Unknown Ch
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.

Hello World
class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World");
}
}
Output
Hello World

2. Command-line Arguments
Code
class CmdArgs {
public static void main(String[] args) {
[Link]("Number of Arguments: " + [Link]);
for (int i = 0; i < [Link]; i++) {
[Link]("Argument " + i + ": " + args[i]);
}
}
}
Output (Example)
Number of Arguments: 3
Argument 0: Ayush
Argument 1: Java
Argument 2: Program

3. Sum & Average of N Numbers


Code
import [Link].*;

class SumAvg {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter count: ");
int n = [Link]();

int sum = 0;
[Link]("Enter numbers:");

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


sum += [Link]();
}
double avg = (double) sum / n;

[Link]("Sum = " + sum);


[Link]("Average = " + avg);
}
}
Output
Enter count: 5
Enter numbers:
10 20 30 40 50
Sum = 150
Average = 30.0

4. Even / Odd Checking


Code
import [Link].*;

class EvenOdd {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int n = [Link]();

if(n % 2 == 0)
[Link](n + " is Even");
else
[Link](n + " is Odd");
}
}
Output
Enter number: 17
17 is Odd

5. Fibonacci Series
Code
class Fibonacci {
public static void main(String[] args) {
int a = 0, b = 1, c, n = 10;

[Link]("Fibonacci Series: ");


for (int i = 0; i < n; i++) {
[Link](a + " ");
c = a + b;
a = b;
b = c;
}
}
}
Output
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

6. Prime Number Checking


Code
import [Link].*;

class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number: ");
int n = [Link]();

boolean prime = true;

if(n < 2) prime = false;


for (int i = 2; i <= n/2; i++) {
if(n % i == 0) {
prime = false;
break;
}
}

if(prime)
[Link](n + " is Prime");
else
[Link](n + " is Not Prime");
}
}
Output
Enter number: 11
11 is Prime
7. Factorial (Recursion)
Code
class FactorialRec {
static int fact(int n) {
if (n == 0) return 1;
return n * fact(n - 1);
}

public static void main(String[] args) {


int n = 5;
[Link]("Factorial of " + n + " = " + fact(n));
}
}
Output
Factorial of 5 = 120

8. String Reverse & Palindrome


Code
import [Link].*;

class StringCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter string: ");
String s = [Link]();

String rev = new StringBuilder(s).reverse().toString();


[Link]("Reversed: " + rev);

if ([Link](rev))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}
Output
Enter string: madam
Reversed: madam
Palindrome
9. Nested Loops – Pattern Printing
Code
class Pattern {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
}
}
Output
*
**
***
****
*****

10. Sorting an Array


Code
import [Link].*;

class ArraySort {
public static void main(String[] args) {
int arr[] = {5, 2, 8, 1, 4};
[Link](arr);

[Link]("Sorted Array:");
for(int x : arr)
[Link](x + " ");
}
}
Output
Sorted Array:
12458

11. GCD & LCM of Two Numbers


Code
import [Link].*;
class GCDLCM {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter two numbers: ");
int a = [Link]();
int b = [Link]();

int x = a, y = b;

while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}

int gcd = a;
int lcm = (x * y) / gcd;

[Link]("GCD = " + gcd);


[Link]("LCM = " + lcm);
}
}
Output
Enter two numbers: 12 18
GCD = 6
LCM = 36

12. Method Overloading


Code
class OverloadDemo {

int add(int a, int b) {


return a + b;
}

double add(double a, double b) {


return a + b;
}

String add(String a, String b) {


return a + b;
}

public static void main(String[] args) {


OverloadDemo obj = new OverloadDemo();

[Link]("Int Sum: " + [Link](5, 10));


[Link]("Double Sum: " + [Link](3.5, 2.5));
[Link]("String: " + [Link]("Hello ", "World"));
}
}
Output
Int Sum: 15
Double Sum: 6.0
String: Hello World

13. Inheritance Example


Code
class Animal {
void eat() {
[Link]("Animal is eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog is barking...");
}
}

class InheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output
Animal is eating...
Dog is barking...
14. Use of super & this
Code
class A {
int x = 10;
}

class B extends A {
int x = 20;

void display() {
[Link]("this.x = " + this.x);
[Link]("super.x = " + super.x);
}
}

class SuperThisDemo {
public static void main(String[] args) {
B obj = new B();
[Link]();
}
}
Output
this.x = 20
super.x = 10

15. Abstract Class Example


Code
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing Circle");
}
}

class AbstractDemo {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}
Output
Drawing Circle

16. Interface Implementation


Code
interface Vehicle {
void start();
}

class Car implements Vehicle {


public void start() {
[Link]("Car is starting...");
}
}

class InterfaceDemo {
public static void main(String[] args) {
Vehicle v = new Car();
[Link]();
}
}
Output
Car is starting...

17. Exception Handling (Multiple Catch)


Code
class MultipleCatch {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int c = a / b;
[Link](c);
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
catch (Exception e) {
[Link]("Some other error occurred.");
}
}
}
Output
Cannot divide by zero!

18. File I/O Program


Code
import [Link].*;

class FileIODemo {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello File Handling in Java");
[Link]();

FileReader fr = new FileReader("[Link]");


int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
}
catch (Exception e) {
[Link]("Error: " + e);
}
}
}
Output
Hello File Handling in Java

19. Thread Creation (Runnable Interface)


Code
class MyThread implements Runnable {
public void run() {
[Link]("Thread is running...");
}
}

class ThreadDemo {
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
[Link]();
}
}
Output
Thread is running...

20. GUI Program (AWT/Swing) – Student Information


Code
import [Link].*;

class StudentGUI {
public static void main(String[] args) {
JFrame f = new JFrame("Student Info");

JLabel l1 = new JLabel("Name:");


[Link](20, 20, 100, 30);

JTextField t1 = new JTextField();


[Link](120, 20, 150, 30);

JLabel l2 = new JLabel("Roll No:");


[Link](20, 70, 100, 30);

JTextField t2 = new JTextField();


[Link](120, 70, 150, 30);

JButton b = new JButton("Submit");


[Link](120, 120, 100, 30);

[Link](l1); [Link](t1);
[Link](l2); [Link](t2);
[Link](b);

[Link](300, 250);
[Link](null);
[Link](true);
}
}
Output
A GUI window opens showing:
Student Info
Name: [textbox]
Roll No: [textbox]
[Submit Button]

Common questions

Powered by AI

Abstract classes and interfaces serve distinct roles in Java's object-oriented programming. An abstract class provides a partially implemented template for subclasses, allowing shared code and definitions, such as the 'Shape' abstract class which defines a contract for the 'draw' method . Interfaces, like 'Vehicle', declare methods without any implementation, ensuring that classes implementing the interface must define these methods, thereby promoting a form of multiple inheritance and loose coupling . The advantage of abstract classes is the ability to provide default behavior along with interface method contracts, while interfaces excel in offering flexibility to implement multiple abstract behaviors even across unrelated class hierarchies.

The error handling mechanism in the MultipleCatch example uses try-catch blocks to manage runtime errors . The code attempts to divide an integer by zero inside a try block, which throws an ArithmeticException. This specific exception is caught by its corresponding catch block, where a custom message "Cannot divide by zero!" is printed. A second catch block for general Exceptions captures any other unhandled errors, prioritizing specific exception handling while providing a fallback for unexpected errors . This layered approach manages known and unknown problem scenarios gracefully.

The 'Hello World' program is a basic Java application that outputs a simple message "Hello World" to standard output without any input or arguments required . In contrast, the 'Command-line Arguments' program reads arguments passed to the program at runtime via the command line, prints the count of these arguments, and iterates over them to display each one . This involves a more complex interaction with the runtime environment as it requires handling input data.

The FileIODemo class demonstrates reading from and writing to files using Java's I/O classes. Writing to a file involves creating a FileWriter object for the target file, using its write method to record data, and closing it to ensure data is saved . For reading, a FileReader object reads characters from the file; a while loop iterates over each character until end-of-file is reached, storing each character in an integer converted to a char, thus reconstructing the file's contents in the console . Exception handling surrounds these operations to catch I/O errors, ensuring reliability during file operations.

Method overloading allows a class to have multiple methods with the same name but different parameter lists, enhancing its capability to handle various types of input with more flexible code design . This is illustrated in the OverloadDemo class, where the 'add' method is overloaded to work with integers, doubles, and strings, thereby allowing the same method name to perform sums of different data types without code duplication . Such flexibility is useful in adapting functions to different contexts within the same class structure.

Nested loops in Java assist in pattern printing by iterating over rows and columns, allowing the creation of structured outputs like pyramids or matrices. In the provided example, the Pattern class uses a nested loop where the outer loop iterates over rows and the inner loop over columns to print a right-angled triangle of asterisks . The outer loop controls the number of rows, while the inner loop prints an increasing number of '*' characters per line, creating the desired pattern progressively by managing iteration counts and space allocation.

Inheritance in Java is illustrated in the InheritanceExample class, where a Dog class inherits from an Animal class . The Dog class can access methods from the Animal class, such as 'eat()', and also define its own methods like 'bark()'. This promotes code reuse and establishes a parent-child relationship where the child class extends the functionality of the parent. The implications include simplified code maintenance and the potential for polymorphism, where a subclass object can be treated as an instance of the parent class, increasing flexibility and reusability of code .

To calculate the GCD of two numbers in Java, the Euclidean algorithm is used, which iteratively assigns the remainder of the division of two numbers to one of the numbers until the remainder is zero, and the last non-zero remainder is the GCD . For the LCM, it is calculated using the formula lcm(a, b) = (|a * b|) / gcd(a, b), which takes the product of the two numbers and divides it by their GCD . This process is implemented in the GCDLCM class, which reads two numbers, calculates their GCD using a loop, and derives the LCM from the obtained GCD.

Recursion offers a clear and simple logic for problems like computing factorials by decomposing them into smaller, identical subproblems, as seen in the FactorialRec class . The primary benefits include clarity and reduced code compared to iterative approaches, serving well for demonstrations of mathematical recursiveness. However, the challenges are significant: recursion in Java can lead to stack overflow errors for large inputs due to call stack limitations and often incurs a performance overhead due to repeated calculations, making iterative solutions more efficient for large datasets .

The challenge in checking for prime numbers is efficiently determining if a number is divisible only by 1 and itself. A basic solution involves checking divisibility from 2 to n/2, which provides a fundamental level of efficiency by reducing the potential divisors . The PrimeCheck class demonstrates this by initially assuming the number is prime and iterating through potential divisors up to n/2; if any divisor is found, the flag is set to false, indicating the number is not prime . While simple, this method is optimized by stopping after finding the first divisor.

You might also like