0% found this document useful (0 votes)
76 views7 pages

Java Programs for Beginners: Examples

The document contains multiple Java programs demonstrating various concepts such as primitive data types, area and perimeter calculations for a circle, one-dimensional arrays, even number printing, inheritance, array lists, hash sets, thread life cycle, applets, and AWT controls. Each program includes source code, compilation, and execution instructions, along with sample outputs. The programs serve as practical examples for understanding fundamental Java programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views7 pages

Java Programs for Beginners: Examples

The document contains multiple Java programs demonstrating various concepts such as primitive data types, area and perimeter calculations for a circle, one-dimensional arrays, even number printing, inheritance, array lists, hash sets, thread life cycle, applets, and AWT controls. Each program includes source code, compilation, and execution instructions, along with sample outputs. The programs serve as practical examples for understanding fundamental Java programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a java program for display different types of primitive data types
Aim: display different types of primitive data types in java
Source code:
public class PrimitiveTypesExample {
public static void main(String[] args) {
// Integer types
byte myByte = 100;
short myShort = 30000;
int myInt = 100000;
long myLong = 15000000000L;
float myFloat = 3.14f;
double myDouble = 3.14159;
char myChar = 'A';
boolean myBoolean = true;
[Link]("byte: " + myByte);
[Link]("short: " + myShort);
[Link]("int: " + myInt);
[Link]("long: " + myLong);
[Link]("float: " + myFloat);
[Link]("double: " + myDouble);
[Link]("char: " + myChar);
[Link]("boolean: " + myBoolean);
}
}
Compile:
G:\J>javac [Link]
Run:
G:\J>java PrimitiveTypesExample
byte: 100
short: 30000
int: 100000
long: 15000000000
float: 3.14
double: 3.14159
char: A
boolean: true

2. Write a java program to calculate area and perimeter of circle


Aim: calculating area and perimeter to a circle
Source code:
import [Link];
public class CircleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get the radius from the user
[Link]("Enter the radius of the circle: ");
double radius = [Link]();
// Calculate the area
// Formula: Area = π * r^2
double area = [Link] * [Link](radius, 2);
// Calculate the perimeter (circumference)
// Formula: Perimeter = 2 * π * r
double perimeter = 2 * [Link] * radius;
// Display the results
[Link]("Area of the circle: " + area);
[Link]("Perimeter of the circle: " + perimeter);
[Link](); // Close the scanner
}
}

Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java CircleCalculator
Enter the radius of the circle: 2.61
Area of the circle: 21.400843315519026
Perimeter of the circle: 16.39911365173872
G:\JAVA LAB>
3. Write a java program for one dimensional array
Aim: one dimensional araay operations in java
Source code:
public class OneDArrayExample {
public static void main(String[] args) {
// 1. Declaration and Initialization of an integer array
// Method 1: Declare and then allocate memory and assign values
int[] numbers = new int[5]; // Declares an array named 'numbers' to hold 5 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Method 2: Declare and initialize directly


String[] fruits = {"Apple", "Banana", "Cherry", "Date"};

// 2. Accessing elements of the array


[Link]("Elements of the 'numbers' array:");
[Link]("First element: " + numbers[0]);
[Link]("Third element: " + numbers[2]);
[Link]("\nElements of the 'fruits' array:");
[Link]("Second fruit: " + fruits[1]);
// 3. Iterating through the array using a for loop
[Link]("\nAll elements of the 'numbers' array using a for loop:");
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
// 4. Iterating through the array using an enhanced for loop (for-each loop)
[Link]("\nAll elements of the 'fruits' array using an enhanced for
loop:");
for (String fruit : fruits) {
[Link](fruit);
}
// 5. Modifying an element
numbers[1] = 25; // Changing the value at index 1
[Link]("\nModified 'numbers' array (element at index 1 changed):");
[Link]("Second element: " + numbers[1]);
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java OneDArrayExample
Elements of the 'numbers' array:
First element: 10
Third element: 30

Elements of the 'fruits' array:


Second fruit: Banana

All elements of the 'numbers' array using a for loop:


Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

All elements of the 'fruits' array using an enhanced for loop:


Apple
Banana
Cherry
Date

Modified 'numbers' array (element at index 1 changed):


Second element: 25
4. Write a java program to print even numbers up to 10.
Aim: Printing Even numbers up to 10 in java
Source code:
public class PrintEvenNumbers {
public static void main(String[] args) {
int n = 10;
[Link]("Even numbers up to " + n + ":");
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
[Link](i + " ");
}
}
[Link](); // For a new line after printing
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java PrintEvenNumbers
Even numbers up to 10:
2 4 6 8 10
G:\JAVA LAB>

5. Implementation of Inheritance in java


Aim: Implementing Inheritance in java
Source code:

// Superclass (Parent Class)


class Animal {
String name;

public Animal(String name) {


[Link] = name;
}

public void eat() {


[Link](name + " is eating.");
}
}

// Subclass (Child Class)


class Dog extends Animal {
public Dog(String name) {
super(name); // Call the superclass constructor
}

public void bark() {


[Link](name + " is barking.");
}
}

public class InheritanceExample {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java InheritanceExample
Buddy is eating.
Buddy is barking.
G:\JAVA LAB>

6. Demonstrating use of array list in java


Aim: Demonstrating use of array list in java
Source code:
import [Link];
public class ArrayListExample {
public static void main(String[] args) {
// 1. Create an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();

// 2. Add elements to the ArrayList


[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Grape");

[Link]("Initial ArrayList: " + fruits);

// 3. Add an element at a specific index


[Link](1, "Cherry"); // Adds Cherry at index 1, shifting Banana, Orange, Grape
[Link]("ArrayList after adding Cherry at index 1: " + fruits);

// 4. Access an element by its index


String firstFruit = [Link](0);
[Link]("First fruit: " + firstFruit);

// 5. Modify an element at a specific index


[Link](2, "Mango"); // Replaces the element at index 2 (Banana) with Mango
[Link]("ArrayList after setting index 2 to Mango: " + fruits);

// 6. Remove an element by its index


[Link](0); // Removes the element at index 0 (Apple)
[Link]("ArrayList after removing element at index 0: " + fruits);

// 7. Remove an element by its value


[Link]("Grape");
[Link]("ArrayList after removing Grape: " + fruits);

// 8. Get the size of the ArrayList


int numberOfFruits = [Link]();
[Link]("Number of fruits in the ArrayList: " + numberOfFruits);

// 9. Check if the ArrayList contains an element


boolean containsOrange = [Link]("Orange");
[Link]("Does the ArrayList contain Orange? " + containsOrange);

// 10. Iterate through the ArrayList using a for-each loop


[Link]("Fruits in the ArrayList: ");
for (String fruit : fruits) {
[Link](fruit + " ");
}
[Link]();

// 11. Clear all elements from the ArrayList


[Link]();
[Link]("ArrayList after clearing all elements: " + fruits);

// 12. Check if the ArrayList is empty


boolean isEmpty = [Link]();
[Link]("Is the ArrayList empty? " + isEmpty);
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java ArrayListExample
Initial ArrayList: [Apple, Banana, Orange, Grape]
ArrayList after adding Cherry at index 1: [Apple, Cherry, Banana, Orange, Grape]
First fruit: Apple
ArrayList after setting index 2 to Mango: [Apple, Cherry, Mango, Orange, Grape]
ArrayList after removing element at index 0: [Cherry, Mango, Orange, Grape]
ArrayList after removing Grape: [Cherry, Mango, Orange]
Number of fruits in the ArrayList: 3
Does the ArrayList contain Orange? true
Fruits in the ArrayList: Cherry Mango Orange
ArrayList after clearing all elements: []
Is the ArrayList empty? true
7. Demonstrating the basic usage of a HashSet
Aim: Demonstrating the basic usage of a HashSet
Source code:
import [Link];
public class HashSetExample {
public static void main(String[] args) {
// 1. Create a HashSet to store String elements
HashSet<String> colors = new HashSet<>();

// 2. Add elements to the HashSet


[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("Red"); // Adding a duplicate element, which will not be added

[Link]("HashSet after adding elements: " + colors);

// 3. Check if an element exists


boolean containsGreen = [Link]("Green");
[Link]("Does HashSet contain 'Green'? " + containsGreen);

// 4. Remove an element
[Link]("Blue");
[Link]("HashSet after removing 'Blue': " + colors);

// 5. Get the size of the HashSet


int size = [Link]();
[Link]("Size of HashSet: " + size);

// 6. Iterate through the HashSet


[Link]("Elements in HashSet:");
for (String color : colors) {
[Link](color);
}

// 7. Clear all elements from the HashSet


[Link]();
[Link]("HashSet after clearing all elements: " + colors);

// 8. Check if the HashSet is empty


boolean isEmpty = [Link]();
[Link]("Is HashSet empty? " + isEmpty);
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java HashSetExample
HashSet after adding elements: [Red, Blue, Green]
Does HashSet contain 'Green'? true
HashSet after removing 'Blue': [Red, Green]
Size of HashSet: 2
Elements in HashSet:
Red
Green
HashSet after clearing all elements: []
Is HashSet empty? true

8. Demonstrating Thread Life cycle in java


Aim: Demonstrating Thread Life cycle in java
Source code:
public class ThreadLifeCycleExample {

public static void main(String[] args) throws InterruptedException {


Thread myThread = new Thread(() -> {
try {
[Link]("Thread State (inside run): " +
[Link]().getState()); // RUNNABLE
[Link](500); // TIMED_WAITING
[Link]("Thread State (after sleep): " +
[Link]().getState()); // RUNNABLE (after waking)
} catch (InterruptedException e) {
[Link]();
}
[Link]("Thread finished execution.");
});
[Link]("Thread State (initial): " + [Link]()); // NEW

[Link]();
[Link]("Thread State (after start): " + [Link]()); // RUNNABLE

// Allow some time for the thread to run and potentially sleep
[Link](100);
[Link]("Thread State (during sleep in myThread): " + [Link]());
// TIMED_WAITING

[Link](); // Main thread waits for myThread to terminate


[Link]("Thread State (after join - terminated): " +
[Link]()); // TERMINATED
}
}
Compile:
G:\JAVA LAB>javac [Link]
Run:
G:\JAVA LAB>java ThreadLifeCycleExample
Thread State (initial): NEW
Thread State (after start): RUNNABLE
Thread State (inside run): RUNNABLE
Thread State (during sleep in myThread): TIMED_WAITING
Thread State (after sleep): RUNNABLE
Thread finished execution.
Thread State (after join - terminated): TERMINATED

G:\JAVA LAB>

9. Demonstrating applet program in java


Aim: Demonstrating applet in java
Source code:
[Link]
import [Link];
import [Link];

public class MyFirstApplet extends Applet {


public void paint(Graphics g) {
[Link]("Hello from a Java Applet!", 50, 50);
}
}
[Link]
<!DOCTYPE html>
<html>
<head>
<title>My First Applet</title>
</head>
<body>
<h1>Demonstrating a Java Applet</h1>
<applet code="[Link]" width="400" height="200"></applet>
</body>
</html>
Compile:
G:\JAVA LAB>javac [Link]
G:\JAVA LAB>appletviewer [Link]
Warning: Can't read AppletViewer properties file: C:\Users\svcn\.hotjava\properties Using
defaults.
[Link] controls in java
Aim:AWT control in java
Source code:
import [Link].*;
import [Link].*;

class MyAWTProgram extends Frame {


MyAWTProgram() {
// Create a Frame
Frame f = new Frame("AWT Button Example");

// Create a Button
Button b = new Button("Click Me");

// Set button position and size


[Link](50, 100, 80, 30);

// Add the button to the frame


[Link](b);

// Set frame size


[Link](300, 200);

// Disable default layout manager for manual positioning


[Link](null);

// Make the frame visible


[Link](true);

// Add a WindowListener to handle closing the window


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});

// Add an ActionListener to the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
}

public static void main(String args[]) {


new MyAWTProgram();
}
}
G:\JAVA LAB>javac [Link]

G:\JAVA LAB>java MyAWTProgram


Button Clicked!

Common questions

Powered by AI

Arrays in Java have a fixed size and can hold elements of the same type with direct indexing being available for access and modification . In contrast, ArrayLists are part of Java's Collection framework, allowing dynamic resizing, which means they can grow or shrink as needed. ArrayLists provide more flexibility with methods to add, remove, and manipulate elements conveniently, and are particularly useful when the number of elements is not known beforehand . Arrays are more performance-efficient, but ArrayLists offer superior ease of use and versatility.

Enhanced for loops (or for-each loops) in Java provide a convenient and readable way to iterate over collections such as arrays and ArrayLists without manually managing the loop counter or dealing with index bounds . They reduce boilerplate code and possible errors associated with traditional indices, making code more concise and less error-prone. However, they don't provide access to the index of the current element, which limits their usefulness if such access is necessary.

Inheritance in Java allows a class to acquire properties and behaviors of another class, fostering maintainability and reusability by enabling code extensions without modifications. It is particularly useful in scenarios where multiple classes share common characteristics; defining these in a superclass avoids redundancy. For instance, if multiple types of animals need to perform common actions, defining these actions once in a superclass (Animal) reduces code duplication . This makes the system easier to maintain and enhances scalability.

Creating a simple applet in Java involves writing a class that extends Applet and overriding the 'paint' method to display graphics. The class is then embedded in an HTML page using <applet> tags. A tool like appletviewer can run the applet . However, applets are less used today due to security restrictions, browser support deprecation, and the rise of more versatile technologies like JavaScript for web-based applications, which are more compatible with modern web standards.

In Java, primitive data types are predefined and are the most basic data types available. They include byte, short, int, long, float, double, char, and boolean. These types are not objects and hold their values in memory locations. Primitive types are significant because they provide the most efficient means of handling data of specific types and allow fine-grained control over their behavior during computation. For instance, using 'byte' saves memory compared to 'int' when storing a small numeric value .

To calculate the area and perimeter (circumference) of a circle in Java, one can use the formulas Area = π * r^2 and Perimeter = 2 * π * r, where 'r' is the radius. A Java program can take radius input from the user, compute these values using Math.PI and Math.pow functions, and display the results . These operations are crucial in software development for applications in graphics, simulations, and any domain that requires spatial calculations.

Java's HashSet is a collection that stores elements in a hash table to ensure unique data by disallowing duplicates. It uses hashing to manage data, which provides quick storage, retrieval, and removal of elements based on computed hash values. HashSet achieves data uniqueness by comparing the hash code of new elements with existing ones, adding elements only if their hash codes do not match any current element. This ensures that each item in the collection is distinct, making HashSet suitable for scenarios where duplicate data must be avoided .

The lifecycle of a Java Thread involves several states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. Initially, a thread is in the NEW state until 'start()' is called, changing it to RUNNABLE, where it can execute. Threads may enter WAITING or TIMED_WAITING during operations like sleep, and return to RUNNABLE after these delays. TERMINATED indicates completion. Understanding these states is crucial in concurrent programming to ensure effective thread management, prevent race conditions, and optimize resource utilization .

The Scanner class in Java greatly simplifies input handling by parsing primitive types and strings using regular expressions. It allows interactive user input from different data streams like keyboard input, facilitating data collection during program execution . Using Scanner enhances user interaction by providing an intuitive means to read user input and respond dynamically, which is essential for developing interactive console-based applications. However, it requires careful management of input types and stream closure to avoid resource leaks.

AWT controls provide basic components like buttons, checkboxes, and text fields for building graphical user interfaces in Java. They allow for the creation of simple applications with GUI components . However, AWT's reliance on native operating system resources can lead to inconsistent behavior across platforms. Compared to modern libraries like Swing and JavaFX, AWT offers fewer features and less flexibility; Swing provides a more sophisticated set of widgets, while JavaFX offers rich media and web integration capabilities, making them preferred for complex applications.

You might also like