0% found this document useful (0 votes)
6 views

Java Programs

The document contains a series of Java programs that demonstrate various programming concepts, including primitive data types, variable scopes, string manipulation, user input handling, constructors, inheritance, interfaces, exception handling, and more. Each program is designed to illustrate specific programming techniques and functionalities, such as calculating maximum values, checking even/odd numbers, and implementing polymorphism. The document serves as a comprehensive guide to basic Java programming practices.

Uploaded by

reachspchaitra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Programs

The document contains a series of Java programs that demonstrate various programming concepts, including primitive data types, variable scopes, string manipulation, user input handling, constructors, inheritance, interfaces, exception handling, and more. Each program is designed to illustrate specific programming techniques and functionalities, such as calculating maximum values, checking even/odd numbers, and implementing polymorphism. The document serves as a comprehensive guide to basic Java programming practices.

Uploaded by

reachspchaitra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Program 1

class program1 {

public static void main(String[] args) {

// Display "Hello World"

System.out.println("Hello World!");

// Display the size of all primitive data types

System.out.println("Size of byte: " + Byte.SIZE + " bits");

System.out.println("Size of short: " + Short.SIZE + " bits");

System.out.println("Size of int: " + Integer.SIZE + " bits");

System.out.println("Size of long: " + Long.SIZE + " bits");

System.out.println("Size of float: " + Float.SIZE + " bits");

System.out.println("Size of double: " + Double.SIZE + " bits");

System.out.println("Size of char: " + Character.SIZE + " bits");

System.out.println("Size of boolean: Typically 1 bit (implementation-dependent)");

}
Program 2

class program2 {

// Static variable (global)

static int staticVariable = 10;

// Instance variable (global)

int instanceVariable = 20;

public void displayVariables() {

// Local variable

int localVariable = 30;

// Displaying the values of all variables

System.out.println("Static Variable: " + staticVariable);

System.out.println("Instance Variable: " + instanceVariable);

System.out.println("Local Variable: " + localVariable);

public static void main(String[] args) {

// Creating an object to access instance variable

program2 example = new program2();

// Accessing the method to display variables

example.displayVariables();

// Accessing the static variable directly using class name

System.out.println("Accessing Static Variable from main: " + program2.staticVariable);

}
Program 3

class program3 {

public static void main(String[] args) {

// Initialize strings

String str1 = "Hello";

String str2 = "World";

// 1. String Length

int lengthOfStr1 = str1.length();

System.out.println("Length of '" + str1 + "': " + lengthOfStr1);

// 2. String Concatenation

String concatenatedString = str1.concat(" ").concat(str2);

System.out.println("Concatenated String: " + concatenatedString);

// 3. Substring

String substring = concatenatedString.substring(0, 5); // Extracting "Hello"

System.out.println("Substring: " + substring);


}

Program 4

import java.util.Scanner;

class program4 {

public static void main(String[] args) {

// Create a Scanner object to read input from the user

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter three numbers

System.out.print("Enter the first number: ");

int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");

int num2 = scanner.nextInt();

System.out.print("Enter the third number: ");

int num3 = scanner.nextInt();


// Initialize a variable to hold the maximum value

int max;

// Compare the numbers to find the maximum

if (num1 >= num2 && num1 >= num3) {

max = num1; // num1 is greater than or equal to both num2 and num3

} else if (num2 >= num1 && num2 >= num3) {

max = num2; // num2 is greater than or equal to both num1 and num3

} else {

max = num3; // If neither of the above, then num3 is the largest

// Display the maximum number

System.out.println("The maximum number is: " + max);

// Close the scanner

scanner.close();

}
Program 5

import java.util.Scanner;

public class program5 {

public static void main(String[] args) {

// Create a Scanner object to read input from the user

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number: ");

int num = scanner.nextInt();

// Check if the number is even or odd using the modulus operator

if (num % 2 == 0) {

System.out.println(num + " is even");

} else {

System.out.println(num + " is odd");

// Close the scanner

scanner.close();

}
Program 6

class MyClass {

// Instance variables

int number;

String text;

// Default constructor

public MyClass() {

number = 0; // Initialize number to 0

text = "Default Text"; // Initialize text to a default string

// Parameterized constructor

public MyClass(int num, String str) {

number = num; // Assign the passed value to number

text = str; // Assign the passed value to text

// Method to display values

public void display() {

System.out.println("Number: " + number);

System.out.println("Text: " + text);

class program6 {

public static void main(String[] args) {

// Creating an object using the default constructor

MyClass obj1 = new MyClass();

System.out.println("Using Default Constructor:");


obj1.display(); // Display default values

// Creating an object using the parameterized constructor

MyClass obj2 = new MyClass(42, "Parameterized Text");

System.out.println("\nUsing Parameterized Constructor:");

obj2.display(); // Display assigned values

Program 7

class Student {

// Instance variables

int id;

String name;

// Constructor to initialize the student object

public Student(int id, String name) {

this.id = id;

this.name = name;
}

// Method to display student details

public void display() {

System.out.println("ID: " + id + ", Name: " + name);

class program7 {

public static void main(String[] args) {

// Creating an array of Student objects

Student[] students = new Student[3]; // Array to hold 3 Student objects

// Initializing the array with Student objects

students[0] = new Student(1, "Alice");

students[1] = new Student(2, "Bob");

students[2] = new Student(3, "Charlie");

// Displaying the details of each student

for (Student student : students) {

student.display();

}
Program 8

class Animal {

// Method in the parent class

public void eat() {

System.out.println("Animal is eating");

// Child class that extends the Animal class

class Dog extends Animal {

// Method in the child class

public void bark() {

System.out.println("Dog is barking");

// Main class to test the inheritance

class program8 {

public static void main(String[] args) {


// Create an object of the Dog class

Dog myDog = new Dog();

// Call the inherited method from Animal class

myDog.eat(); // Output: Animal is eating

// Call the method from Dog class

myDog.bark(); // Output: Dog is barking

Program 9

// Implementing both interfaces in a single class

class Duck implements Walkable, Swimmable {

// Implementing the walk method from Walkable interface

public void walk() {

System.out.println("Duck is walking.");

}
// Implementing the swim method from Swimmable interface

public void swim() {

System.out.println("Duck is swimming.");

// Main class to test the implementation

public class program9 {

public static void main(String[] args) {

// Create an object of Duck class

Duck myDuck = new Duck();

// Call the methods from both interfaces

myDuck.walk(); // Output: Duck is walking.

myDuck.swim(); // Output: Duck is swimming.

Walkable.java

// Define the first interface

interface Walkable {

void walk();

Swimmable.java

// Define the second interface

interface Swimmable {

void swim();

}
Program 10

import java.applet.Applet;

import java.awt.Graphics;

/* <applet code=program10.class width=400 height=400>


</applet>

*/

// Creating a simple applet by extending the Applet class

public class program10 extends Applet {

// Overriding the paint method to draw something on the applet window

@Override

public void paint(Graphics g) {

// Using the Graphics object to draw a string on the applet window

g.drawString("Hello, World!", 50, 50);

Program 11

class program11 {

public static void main(String[] args) {

int numerator = 10;

int denominator = 0; // Setting denominator to zero

try {

// Attempting to perform division

int result = numerator / denominator;

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

// Handling the ArithmeticException

System.out.println("Error: " + e.getMessage());

System.out.println("Cannot divide a number by zero.");

}
Program 12

class program12 {

// Method to add two integers with default values

public int add(int a, int b) {

return a + b;

// Overloaded method to add two float numbers with default values

public float add(float a, float b) {

return a + b;

// Method to add two integers using default values

public int add() {

return add(5, 10); // Default values for integers

// Overloaded method to add two float numbers using default values


public float add(float a) {

return add(a, 5.0f); // Default value for the second float number

public static void main(String[] args) {

program12 calculator = new program12();

// Adding two integers without default values

int intSum = calculator.add(3, 7);

System.out.println("Sum of integers: " + intSum); // Output: 10

// Adding two float numbers without default values

float floatSum = calculator.add(3.5f, 2.5f);

System.out.println("Sum of floats: " + floatSum); // Output: 6.0

// Adding two integers with default values

int defaultIntSum = calculator.add();

System.out.println("Sum of integers with default values: " + defaultIntSum); // Output: 15

// Adding two float numbers with one default value

float defaultFloatSum = calculator.add(4.5f);

System.out.println("Sum of floats with one default value: " + defaultFloatSum); // Output: 9.5

}
Program 13

// Parent class

class Animal {

// Method to be overridden

public void sound() {

System.out.println("Animal makes a sound");

// Child class that overrides the sound method

class Dog extends Animal {

@Override

public void sound() {

System.out.println("Dog barks");

// Another child class that overrides the sound method


class Cat extends Animal {

@Override

public void sound() {

System.out.println("Cat meows");

// Main class to demonstrate runtime polymorphism

class program13 {

public static void main(String[] args) {

// Creating references of the parent class

Animal myAnimal;

// Assigning Dog object to Animal reference

myAnimal = new Dog();

myAnimal.sound(); // Output: Dog barks

// Assigning Cat object to Animal reference

myAnimal = new Cat();

myAnimal.sound(); // Output: Cat meows

}
Program 14

class program14 {

public static void main(String[] args) {

try {

// Attempting to create an array with a negative size

int size = -5;

int[] array = new int[size]; // This line will throw NegativeArraySizeException

} catch (NegativeArraySizeException e) {

// Handling the NegativeArraySizeException

System.out.println("Error: Attempted to create an array with a negative size.");

e.printStackTrace(); // Print the stack trace for debugging

// Continue with the program execution

System.out.println("Continuing execution...");

}
Program 15

class program15 {

public static void main(String[] args) {

String str = null; // Initializing a String variable to null

try {

// Attempting to access a method on a null reference

System.out.println("Length of the string: " + str.length());

} catch (NullPointerException e) {

// Handling the NullPointerException

System.out.println("Error: A NullPointerException has been caught.");

System.out.println("You cannot access methods or properties of a null object.");

} finally {

// This block will execute regardless of whether an exception occurred or not

System.out.println("Execution completed. Please check your variables.");

}
Program 16

import mypackage.*;

class program16 {

public static void main(String[] args) {

// Creating an object of the Greeting class from the imported package

Greeting greeting = new Greeting();

// Calling the method to display the message

greeting.displayMessage();

Greeting.java

package mypackage;

public class Greeting {

public void displayMessage() {

System.out.println("Hello from the user-defined package!");

}
Program 17

import java.util.Scanner;

class program17 {

public static void main(String[] args) {

// Create a Scanner object to read user input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number: ");

int originalNum = scanner.nextInt(); // Read the input number

int num = originalNum; // Store the original number for comparison

int reversedNum = 0; // Variable to hold the reversed number

// Reverse the number

while (num != 0) {

int remainder = num % 10; // Get the last digit

reversedNum = reversedNum * 10 + remainder; // Build the reversed number

num /= 10; // Remove the last digit from num

// Check if the original number and reversed number are the same

if (originalNum == reversedNum) {

System.out.println(originalNum + " is a palindrome.");

} else {

System.out.println(originalNum + " is not a palindrome.");

// Close the scanner

scanner.close();

}
Program 18

class program18{

public static void main(String[] args) {

// Check if any command line arguments are provided

if (args.length == 0) {

System.out.println("No command line arguments found. Please provide numbers.");

return; // Exit the program if no arguments are provided

// Iterate through each command line argument

for (String arg : args) {

try {

// Convert the argument from String to Integer

int num = Integer.parseInt(arg);

// Calculate the factorial of the number

long factorial = calculateFactorial(num);

// Display the result


System.out.println("Factorial of " + num + " is: " + factorial);

} catch (NumberFormatException e) {

System.out.println("Invalid input: " + arg + " is not a valid integer.");

} catch (IllegalArgumentException e) {

System.out.println(e.getMessage());

// Method to calculate factorial

private static long calculateFactorial(int n) {

if (n < 0) {

throw new IllegalArgumentException("Factorial is not defined for negative numbers.");

long result = 1; // Use long to handle larger factorials

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

result *= i; // Multiply the result by each number up to n

return result;

}
Program 19

import java.util.Scanner;

class program19 {

public static void main(String[] args) {

// Create a Scanner object to read input from the user

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the lower limit

System.out.print("Enter the lower limit: ");

int lowerLimit = scanner.nextInt();

// Prompt the user to enter the upper limit

System.out.print("Enter the upper limit: ");

int upperLimit = scanner.nextInt();

System.out.println("Prime numbers between " + lowerLimit + " and " + upperLimit + " are:");
// Loop through each number in the range

for (int num = lowerLimit; num <= upperLimit; num++) {

// Check if the number is prime

if (isPrime(num)) {

System.out.print(num + " "); // Print the prime number

// Close the scanner

scanner.close();

// Method to check if a number is prime

private static boolean isPrime(int number) {

// Numbers less than 2 are not prime

if (number < 2) {

return false;

// Check for factors from 2 to the square root of the number

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

return false; // Not a prime number

return true; // It is a prime number

}
Program 20

// Implementing the Runnable interface

class program20 implements Runnable {

@Override

public void run() {

// Code to be executed by the thread

System.out.println("Inside: " + Thread.currentThread().getName());

public static void main(String[] args) {

System.out.println("Inside: " + Thread.currentThread().getName());

// Creating a Runnable instance

Runnable runnable = new program20();

System.out.println("Creating Thread...");

// Creating a Thread object and passing the Runnable instance to it

Thread thread = new Thread(runnable);


System.out.println("Starting Thread...");

// Starting the thread

thread.start();

You might also like