- Password Generator
- Online Survey System
- Snake Game
- Number Guessing
- Currency Converter
- Calculator
- To-Do-List
- Quiz Game
- Simple Database
- BMI Calculator
Table of Contents
What is Java?
Developed and created by John Gosling in 1995 in Sun Microsystems, Java is a general-purpose, object-oriented programming language. It was developed and intended to follow the WORA concept which means Write Once Run Anywhere i.e. compiled Java code can run on all platforms that support Java without the need for recompilation. Java programming for beginners
1. Password Generator using Java
With the growing trend of hacking attacks, everyone should create different and complex passwords for their diverse accounts to keep them secure. Remembering every password is not humanly possible and noting it down somewhere is not a wise idea. Hence, people take the help of Password generators to create strong and complex passwords for their accounts. To generate such functionality all by yourself, you can take advantage of the function that java offers. Whenever a user is developing an account on a new website, you can use that program to develop a password. To take the safety of the password a notch above, you can enforce such functionality so that it saves passwords in encrypted form. To incorporate this, you need to study the fundamentals of Cryptography and Java Cryptography Architecture.
Here’s the Source Code.
import java.util.Random;
public class PasswordGenerator {
public static void main(String[] args) {
int passwordLength = 12; // length of the password
String password = generatePassword(passwordLength);
System.out.println("Generated password: " + password);
}
/**
* Generates a random password of the given length
* @param length the length of the password to generate
* @return a random password of the given length
*/
public static String generatePassword(int length) {
String lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
String uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numbers = "0123456789";
String specialCharacters = "!@#$%^&*()-+?_=,<>/";
String allCharacters = lowercaseLetters + uppercaseLetters + numbers + specialCharacters;
Random random = new Random();
StringBuilder password = new StringBuilder(length);
// generate random characters for the password
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(allCharacters.length());
password.append(allCharacters.charAt(randomIndex));
}
return password.toString();
}
}
2. Online Survey System
The idea of this project is to create a core java project that can accumulate the viewpoint of a targeted audience of a survey through the Internet. Based on that, the app can send the targeted audiences promotional emails and can launch online surveys. Any business can make use of this type of software to assemble feedback regarding the services or products they offer. We can build such functionality so that only registered customers can cast their responses. The main attributes of the app should be:
- The apps are programmed in a way that they should be compatible with various databases like SQL and NoSQL.
- Customers can submit their reactions anonymously.
- Should be installed at a doable cost.
Main Java:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Login login = new Login();
login.loginView();
}
}
Login Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Login {
private JFrame frame;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
private JButton signUpButton;
public void loginView() {
frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(10, 20, 80, 25);
panel.add(usernameLabel);
usernameField = new JTextField(20);
usernameField.setBounds(100, 20, 165, 25);
panel.add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordField = new JPasswordField(20);
passwordField.setBounds(100, 50, 165, 25);
panel.add(passwordField);
loginButton = new JButton("LOGIN");
loginButton.setBounds(100, 80, 80, 25);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
boolean loginStatus = login(username, password);
if (loginStatus) {
JOptionPane.showMessageDialog(frame, "Login Successful!");
new MainPage(username);
frame.dispose();
} else {
JOptionPane.showMessageDialog(frame, "Invalid username or password.");
}
}
});
panel.add(loginButton);
signUpButton = new JButton("SIGN UP");
signUpButton.setBounds(100, 110, 80, 25);
signUpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new SignUp().signUpView();
}
});
panel.add(signUpButton);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
private boolean login(String username, String password) {
boolean status = false;
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/survey_system", "root", "");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'");
if (resultSet.next()) {
status = true;
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
}
SignUp Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import
3. Snake Game using Java
In our childhood, nearly all of us enjoyed playing classic snake games. Now we will try to enhance it with the help of Java concepts. The concept appears to be easy but it is not that effortless to implement.
One ought to comprehend the OOPs concept in detail to execute this effectively. Furthermore, ideas from Java Swing are used to create this application.
Here’s the Source Code.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class SnakeGame extends JPanel implements ActionListener {
private static final int WIDTH = 600;
private static final int HEIGHT = 600;
private static final int DOT_SIZE = 20;
private static final int ALL_DOTS = WIDTH * HEIGHT / DOT_SIZE;
private static final int DELAY = 100;
private int[] x = new int[ALL_DOTS];
private int[] y = new int[ALL_DOTS];
private int dots;
private int appleX;
private int appleY;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
public SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.WHITE);
setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT && !rightDirection) {
leftDirection = true;
upDirection = false;
downDirection = false;
} else if (keyCode == KeyEvent.VK_RIGHT && !leftDirection) {
rightDirection = true;
upDirection = false;
downDirection = false;
} else if (keyCode == KeyEvent.VK_UP && !downDirection) {
upDirection = true;
leftDirection = false;
rightDirection = false;
} else if (keyCode == KeyEvent.VK_DOWN && !upDirection) {
downDirection = true;
leftDirection = false;
rightDirection = false;
}
}
});
startGame();
}
public void startGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * DOT_SIZE;
y[i] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void draw(Graphics g) {
if (inGame) {
g.setColor(Color.RED);
g.fillOval(appleX, appleY, DOT_SIZE, DOT_SIZE);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLUE);
}
g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
}
move();
if (checkCollision()) {
inGame = false;
}
repaint();
} else {
gameOver(g);
}
}
private void move() {
for (int i = dots - 1; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i -
4. Number Guessing using java
This is a simple command-line game where the computer generates a random number between 1 and 100, and the user has to guess it. The game provides feedback to the user on whether their guess is too high or too low.
Here’s the Source Code.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int numberToGuess = random.nextInt(100) + 1;
int guess;
int attempts = 0;
System.out.println("Welcome to Guess the Number!");
System.out.println("I have generated a random number between 1 and 100.");
System.out.println("Can you guess what it is?");
do {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high! Try again.");
}
} while (guess != numberToGuess);
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
}
}
5. Currency Converter using java
This is a simple command-line program that converts between US dollars and Euros. The user enters an amount in US dollars, and the program calculates and displays the equivalent amount in Euros.
Here’s the Source Code.
import java.util.Scanner;
public class CurrencyConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Currency Converter!");
System.out.println("Enter the amount in US dollars to convert to Euros: ");
double dollars = scanner.nextDouble();
double euros = dollars * 0.83;
System.out.printf("%.2f US dollars is equivalent to %.2f Euros.%n", dollars, euros);
}
}
6.Calculator using java
This is a simple command-line program that performs basic arithmetic operations such as addition, subtraction, multiplication, and division. The user enters two numbers and an operation, and the program calculates and displays the result.
Here’s the Source Code.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton addButton, subButton, mulButton, divButton, equalButton, clearButton;
private double firstNumber, secondNumber, result;
private int operator;
public Calculator() {
setLayout(new FlowLayout());
textField = new JTextField(10);
add(textField);
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
equalButton = new JButton("=");
clearButton = new JButton("C");
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(equalButton);
add(clearButton);
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
equalButton.addActionListener(this);
clearButton.addActionListener(this);
setTitle("Calculator");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("+")) {
firstNumber = Double.parseDouble(textField.getText());
textField.setText("");
operator = 1;
} else if (command.equals("-")) {
firstNumber = Double.parseDouble(textField.getText());
textField.setText("");
operator = 2;
} else if (command.equals("*")) {
firstNumber = Double.parseDouble(textField.getText());
textField.setText("");
operator = 3;
} else if (command.equals("/")) {
firstNumber = Double.parseDouble(textField.getText());
textField.setText("");
operator = 4;
} else if (command.equals("=")) {
secondNumber = Double.parseDouble(textField.getText());
switch (operator) {
case 1:
result = firstNumber + secondNumber;
break;
case 2:
result = firstNumber - secondNumber;
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber / secondNumber;
break;
}
textField.setText(String.valueOf(result));
} else if (command.equals("C")) {
textField.setText("");
firstNumber = 0;
secondNumber = 0;
result = 0;
operator = 0;
}
}
}
7. To-Do List using java
This is a simple console-based application that allows the user to add, view, and delete tasks from a to-do list. The user can also mark tasks as completed.
Here’s the Source Code.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ToDoList {
private List<String> tasks;
public ToDoList() {
tasks = new ArrayList<>();
}
public void addTask(String task) {
tasks.add(task);
}
public void viewTasks() {
System.out.println("Your tasks:");
int index = 1;
for (String task : tasks) {
System.out.printf("%d. %s%n", index++, task);
}
}
public void deleteTask(int index) {
if (index >= 1 && index <= tasks.size()) {
tasks.remove(index - 1);
} else {
System.out.println("Invalid task index.");
}
}
public void markAsCompleted(int index) {
if (index >= 1 && index <= tasks.size()) {
String task = tasks.get(index - 1);
tasks.set(index - 1, "[x] " + task.substring(4));
} else {
System.out.println("Invalid task index.");
}
}
public static void main(String[] args) {
ToDoList list = new ToDoList();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("To-Do List:");
System.out.println("1. Add task");
System.out.println("2. View tasks");
System.out.println("3. Delete task");
System.out.println("4. Mark as completed");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the task: ");
scanner.nextLine();
String task = scanner.nextLine();
list.addTask(task);
break;
case 2:
list.viewTasks();
break;
case 3:
System.out.print("Enter the task index to delete: ");
int deleteIndex = scanner.nextInt();
list.deleteTask(deleteIndex);
break;
case 4:
System.out.print("Enter the task index to mark as completed: ");
int completeIndex = scanner.nextInt();
list.markAsCompleted(completeIndex);
break;
case 5:
System.out.println("Goodbye!");
System.exit(0);
default:
System.out.println("Invalid choice.");
}
}
}
}
8. Quiz Game in java
This is a simple console-based game that presents the user with a series of multiple-choice questions. The user enters their answers, and the program provides feedback on whether they are correct or not. The game can keep track of the user’s score and display it at the end.
Here’s the source code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class QuizGame {
private List<Question> questions;
private int score;
public QuizGame() {
questions = new ArrayList<>();
score = 0;
}
public void addQuestion(Question question) {
questions.add(question);
}
public void startQuiz() {
Scanner scanner = new Scanner(System.in);
for (Question question : questions) {
System.out.println(question.getQuestion());
int index = 1;
for (String answer : question.getAnswers()) {
System.out.printf("%d. %s%n", index++, answer);
}
System.out.print("Enter your answer (1-%d): ");
int answerIndex = scanner.nextInt();
if (question.isCorrect(answerIndex)) {
score++;
}
}
System.out.printf("Your score is %d out of %d.%n", score, questions.size());
}
public static void main(String[] args) {
QuizGame game = new QuizGame();
game.addQuestion(new Question("What is the capital of France?", "Paris", "London", "Berlin", 1));
game.addQuestion(new Question("What is the largest planet in the solar system?", "Jupiter", "Saturn", "Mars", 1));
game.addQuestion(new Question("What is the smallest prime number?", "2", "3", "5", 1));
game.startQuiz();
}
}
class Question {
private String question;
private List<String> answers;
private List<Integer> correctAnswers;
public Question(String question, String answer1, String answer2, String answer3, int correctAnswer) {
this.question = question;
answers = new ArrayList<>();
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
correctAnswers = new ArrayList<>();
correctAnswers.add(correctAnswer);
}
public String getQuestion() {
return question;
}
public List<String> getAnswers() {
return answers;
}
public boolean isCorrect(int answerIndex) {
return correctAnswers.contains(answerIndex);
}
}
9. Simple Database in java
This is a simple console-based application that allows the user to create, read, update, and delete records in a simple database. The database is implemented using a file or an in-memory data structure.
Here’s the source code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Record {
private int id;
private String name;
private String value;
public Record(int id, String name, String value) {
this.id = id;
this.name = name;
this.value = value;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return String.format("%d,%s,%s%n", id, name, value);
}
}
public class SimpleDatabase {
private static final String DB_FILE = "database.txt";
private List<Record> records;
public SimpleDatabase() {
records = new ArrayList<>();
loadFromFile();
}
public void addRecord(Record record) {
records.add(record);
saveToFile();
}
public void updateRecord(Record record) {
for (int i = 0; i < records.size(); i++) {
if (records.get(i).getId() == record.getId()) {
records.set(i, record);
saveToFile();
break;
}
}
}
public void deleteRecord(int id) {
for (int i = 0; i < records.size(); i++) {
if (records.get(i).getId() == id) {
records.remove(i);
saveToFile();
break;
}
}
}
public Record findRecord(int id) {
for (Record record : records) {
if (record.getId() == id) {
return record;
}
}
return null;
}
public void viewRecords() {
System.out.println("ID\tName\tValue");
for (Record record : records) {
System.out.println(record);
}
}
private void loadFromFile() {
try (BufferedReader reader = new BufferedReader(new FileReader(DB_FILE))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
int id = Integer.parseInt(parts[0]);
String name = parts[1];
String value = parts[2];
records.add(new Record(id, name, value));
}
} catch (IOException e) {
System.out.println("Error loading database: " + e.getMessage());
}
}
private void saveToFile() {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(DB_FILE))) {
for (Record record : records) {
writer.write(record.toString());
}
} catch (IOException e) {
System.out.println("Error saving database: " + e.getMessage());
}
}
public static void main(String[] args) {
SimpleDatabase db = new SimpleDatabase();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Simple Database:");
System.out.println("1. Add record");
System.out.println("2. Update record");
System.out.println("3. Delete record");
}
10. BMI Calculator in java
BMI (Body Mass Index) calculator implemented in Java. This program calculates the BMI based on the user’s weight (in kilograms) and height (in meters), and then displays the BMI along with its interpretation.
Here’s the source code:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("BMI Calculator");
System.out.println("==============");
System.out.print("Enter your weight in kilograms: ");
double weight = scanner.nextDouble();
System.out.print("Enter your height in meters: ");
double height = scanner.nextDouble();
double bmi = calculateBMI(weight, height);
System.out.println("Your BMI is: " + bmi);
System.out.println("BMI Interpretation: " + interpretBMI(bmi));
scanner.close();
}
public static double calculateBMI(double weight, double height) {
return weight / (height * height);
}
public static String interpretBMI(double bmi) {
if (bmi < 18.5) {
return "Underweight";
} else if (bmi >= 18.5 && bmi < 25) {
return "Normal weight";
} else if (bmi >= 25 && bmi < 30) {
return "Overweight";
} else {
return "Obesity";
}
}
}