0% found this document useful (0 votes)
3 views17 pages

java_program-1_250523_122444

The document contains a series of Java programs that demonstrate various programming concepts, including data types, variable scopes, string operations, control structures, constructors, inheritance, interfaces, exception handling, method overloading, polymorphism, and threading. Each program is accompanied by a brief description of its functionality and expected output. The document serves as a practical guide for learning Java programming through hands-on examples.
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)
3 views17 pages

java_program-1_250523_122444

The document contains a series of Java programs that demonstrate various programming concepts, including data types, variable scopes, string operations, control structures, constructors, inheritance, interfaces, exception handling, method overloading, polymorphism, and threading. Each program is accompanied by a brief description of its functionality and expected output. The document serves as a practical guide for learning Java programming through hands-on examples.
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
You are on page 1/ 17

Java Programs

Note: to compile code use javac filename.java after that to execute the code use
java filename
1.Java program to display “Hello World” and display the size of all the data types.

class program1 {

public static void main(String[] args) {

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

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)");

Output:
2. Java program to implement the usage of static,local and global variables.

class program2 {

static int staticVariable = 10;

int instanceVariable = 20;

public void displayVariables() {

int localVariable = 30;

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

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

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

public static void main(String[] args) {

program2 example = new program2();

example.displayVariables();

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

Output:

3. Java program to implement string operations string length, string concatenate,


substring.

class program3

{
public static void main(String[] args)

String str1 = "Hello";

String str2 = "World";

int lengthOfStr1 = str1.length();

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

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

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

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

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

Output:

4. Java program to find the maximum of three numbers.

import java.util.Scanner;

class program4 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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();

int max;

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

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

scanner.close();

Output:

5. Java program to check whether the number is odd or even.

import java.util.Scanner;

public class program5 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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

int num = scanner.nextInt();

if (num % 2 == 0) {

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

} else {

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

scanner.close();

output:

6. Java program to implement default and parameterized constructors.

class MyClass {

int number;

String text;

public MyClass() {

number = 0; // Initialize number to 0

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

public MyClass(int num, String str) {


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

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

public void display() {

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

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

class program6 {

public static void main(String[] args)

MyClass obj1 = new MyClass();

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

obj1.display(); // Display default values

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

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

obj2.display(); // Display assigned values

Output:
7.Java program to implement an array of objects.

class Student {

int id;

String name;

public Student(int id, String name) {

this.id = id;

this.name = name;

public void display() {

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

class program7 {

public static void main(String[] args) {

Student[] students = new Student[3];

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

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

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

for (Student student : students) {

student.display();

Output:
8. Java program to implement Single Inheritance.

class Animal {

public void eat() {

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

class Dog extends Animal {

public void bark() {

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

class program8 {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.eat();

myDog.bark();

Output:
9.Java program to implement Multiple Inheritance using Interface.

interface Walkable{

void walk();

interface Swimmable{

void swim();

class Duck implements Walkable, Swimmable {

public void walk() {

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

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.

}
}

Output:

10.Java program to implement an applet.

Step1: typr the java code and save it as program10.java and comile it

import java.applet.Applet;

import java.awt.Graphics;

// 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);

Step2: write the html code and save it as program10.html

<html>

<body>

<applet code=program10.class width=400

height=400>

</applet>

</body>
</html>

Step3: Compile it using appletviewer program10.html.

Output:

11. Java program to demonstrate a division by zero exception.

class program11 {

public static void main(String[] args) {

int numerator = 10;

int denominator = 0;

try {

int result = numerator / denominator;

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

} catch (ArithmeticException e) {

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

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


}

Output:

12. Java program to add two integers and two float numbers. When no arguments are
supplied give a default value to calculate the sum. Use method overloading.

class program12 {

public int add(int a, int b) {

return a + b;

public float add(float a, float b) {

return a + b;

public int add() {

return add(5, 10);

public float add(float a) {

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

public static void main(String[] args) {

program12 calculator = new program12();

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


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

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

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

int defaultIntSum = calculator.add();

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

float defaultFloatSum = calculator.add(4.5f);

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

Output:

13. Java program that demonstrates run-time polymorphism.

class Animal {

public void sound() {

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

class Dog extends Animal {

@Override

public void sound() {

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

class Cat extends Animal {

@Override

public void sound() {

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

public class program13 {

public static void main(String[] args) {

Animal myAnimal;

myAnimal = new Dog();

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

myAnimal = new Cat();

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

Output:
14. Java program to catch negative array size Exception. This exception is caused when the
array is initialized to negative values.

class program14 {

public static void main(String[] args) {

try {

int size = -5;

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

} catch (NegativeArraySizeException e) {

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

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

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

Output:

15. Java program to check whether a number is palindrome or not.

import java.util.Scanner;

class program15{

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


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

int originalNum = scanner.nextInt();

int num = originalNum;

int reversedNum = 0;

while (num != 0) {

int remainder = num % 10;

reversedNum = reversedNum * 10 + remainder;

num /= 10;

if (originalNum == reversedNum) {

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

} else {

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

scanner.close();

Output:

16. Java program to create a thread using Runnable Interface.

class program16 implements Runnable {

@Override
public void run() {

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

public static void main(String[] args) {

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

Runnable runnable = new program16();

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

//Runnable instance to it

Thread thread = new Thread(runnable);

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

thread.start();

Output:

You might also like