java code samples

java code samples

Here are some example Java code samples that demonstrate various programming concepts and techniques:

  1. Hello, world!: A simple program that outputs the message "Hello, world!" to the console.
‮ot refer‬:lautturi.com
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello, world!");
  }
}
  1. Reading user input: A program that reads a string from the user and outputs it to the console.
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a string: ");
    String str = scanner.nextLine();

    System.out.println("You entered: " + str);

    scanner.close();
  }
}
  1. Calculating the factorial of a number: A program that calculates the factorial of a number using a recursive function.
public class Main {
  public static long factorial(long n) {
    if (n == 0) {
      return 1;
    }
    return n * factorial(n - 1);
  }

  public static void main(String[] args) {
    long n = 5;
    long result = factorial(n);
    System.out.println("The factorial of " + n + " is " + result);  // Outputs: "The factorial of 5 is 120"
  }
}
  1. Creating a simple GUI: A program that creates a simple graphical user interface (GUI) with a button and a label.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Example GUI");
    frame.setLayout(new FlowLayout());

    JButton button = new JButton("Click me");
    frame.add(button);

    JLabel label = new JLabel("Hello, world!");
    frame.add(label);

    frame.setSize(200, 100);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}
Created Time:2017-11-03 00:14:50  Author:lautturi