Here are some example Java code samples that demonstrate various programming concepts and techniques:
public class Main { public static void main(String[] args) { System.out.println("Hello, world!"); } }
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(); } }
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" } }
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); } }