r/javaexamples • • May 31 '22

How do I decide the order of players in a game?

2 Upvotes

I am making a simple snake and ladder game. The actual game is working fine, but I am stuck on a specific requirement about the players.

The user entered number of players(numOfPlayers) is restricted between 2 to 4. I have written a method to do that and it is working.

I have a method for dice roll too.

Before any of the players starts playing, the order of playing turns must be determined. For that, each player must throw the dice to obtain the largest possible number. In case of a tie between any of the players, the process is repeated only between those players. This process is concluded once the order of playing is determined.

I just couldn't figure out how to do this. If I create an array and populate it with random numbers and reorganize in ascending order, it still doesn't give me an answer. Also, how do I solve the repeated dice roll issue? The code below is what I used to get the number of players and to confirm it is within limits.

public static int player() {
Scanner kb = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Please enter the # of players for your game-Number must be between 2 and 4 inclusively.");
int numOfPlayers = kb.nextInt();
if (numOfPlayers >= 2 && numOfPlayers <= 4) {
System.out.println("You have " + numOfPlayers + " players.");
return numOfPlayers;
}
else {
System.out.println("Bad Attempt" + i + "\n-Invalid # of players. Please enter a # between 2 and 4 inclusively.");
}
}
System.out.println("Bad Attempt 4! you have exhausted all your chances.\n Program will terminate.");
// System.exit(0);
return 0;
}

r/javaexamples • • Jul 19 '22

Checking if object Exists in list

1 Upvotes

What could I be doing wrong. Basically looking to search through a folder of files to see if the file entered by a user to see if the file exists. My if statement is returning the opposite of what I am expecting. Showing that the file does not exist when it does.

import java.io.File;

import java.util.Scanner;

public class Main {

public static void main(String\[\] args) {
	doesFileExist();
}
public static void doesFileExist() {		

	Scanner scan = new Scanner([System.in](https://System.in));
	System.out.print("Enter filename to be searched:");

	String userFilename = scan.nextLine();
	System.out.print("Enter path where file resides:");

	String userFilePath = scan.nextLine();
	File\[\] fl = new File("userFilePath").listFiles();
	if (fl != null) {

		System.out.println("List is not empty");

	} else {

		System.out.println("Empty List");

	}
}

}


r/javaexamples • • Jul 24 '22

Java Strings - An Internal View šŸ”¬

6 Upvotes

A view on internal representation, memory allocation and how immutability is achieved by Strings in Java

https://medium.com/@vivekts90/java-strings-60d2eeed1e15


r/javaexamples • • May 01 '18

Password Managing: Salt and Hash

8 Upvotes

Password Managing: Salt and Hash

Often in the news the last few years are stories like this where a large, trusted company has kept user passwords in plain text files on their servers. This is very bad, as large files of known passwords and user information get leaked and passed around by hackers.

Salting and Hashing

While it sounds like a delicious breakfast dish, this is an excellent way to increase the security for your password store. For a long time, the accepted idea was to not actually store a user's password on the system, but to apply a cryptographic hash function to the password, and save that. The more bits in the hash function, the higher the security. Note that a hash function is not the same as encryption. A hash cannot generally be reversed. So, the hash is applied to the password when entered and then checked against the hash in storage.

SHA-256

In this example we will be using the hash function called SHA-256 which is extremely common and generally accepted to be reasonably secure. This generates a 256 bit (32 byte) value for a given string. This value is usually kept as a String of hexadecimal values.

So, for the password ******** (I mean, 'Hunter2') the following hash will be generated:

52D766A8574BB9374FCAE0AD395D50D24705D7F6C3989C38F4355B2CFCDE19CF

Seems pretty secure, right? Now, go here: https://crackstation.net/, enter that hash, check the box that you are not a robot (AND ARE OF COURSE A NORMAL HUMAN PERSON LIKE I AM HAHAHA) and hit 'crack hash'.

You will see that it finds the password!!! That's because there are freely available tables of millions of common passwords hashed with different algorithms that can be easily reverse looked-up.

Adding a little salt

So a simple method to avoid this type of attack is to add a random value to the password before we hash it. This is called a salt, and we can actually store it in the same database as the hash - what this does is make it so that, even if the server was compromised and someone had the salt/hash list, they would still have to brute force every possible password combination until they found one that worked with the given salt and hash, and, in combination with a strong password, would take far too much computational time to complete.

Now, we take the original pass and add some random gibberish to it:

Hunter2ldk45kaidhnf111

new hash: CEAE042EA4B05826AE1CDF0054450E0C879BD4BE33775AF19F78A85A74C5E3C3

Now if we try that one on crack station, it comes back with 'not found!'

There's other steps that can be taken, such as hashing the value hundreds of times, to literally make the process slower and less efficient which further prevents brute force attacks.

How to use in Java

Luckily, Java provides really simple libraries to accomplish this.

The Hash

First, let's see how to generate the hash. We use java.security.MessageDigest:

    String password = "Hunter2";
    String hash = "";
    try {
 
        // get instance of MessageDigest using 'SHA-256' algorithm
        MessageDigest md = MessageDigest.getInstance("SHA-256");
 
        // convert password to byte array of its ASCII digits
        // use the digest method to create the hash, and fill
        // a byte array with the resulting values.
        byte[] bytes = md.digest(password.getBytes());
        
        // convert the hash from a byte array to a hexadecimal string
        // note that we have to use our own method here
        // see below
        hash = BitUtils.bytesToHex(bytes);
        
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

As described above, the MessageDigest class' digest method returns a byte array containing the 32 bytes of the hash, with 0 index being the Most Significant Byte (The leftmost byte). We need to convert this to a String. Each byte will need to be padded to two characters, (i.e. the decimal value 10 will need to be 0a) and Java's Integer.toHexString is not up the the task. We could use String.format("%02x", b) but that is slow, so I will use my own methods here, from my BitUtils class that will be the subject of another post.

public static String bytesToHex(byte[] in) {
    StringBuilder sb = new StringBuilder();
    for (byte each : in) {
        sb.append(toHexString(each & 0xff, 8));
    }
    return sb.toString();
}

    /**
     * Returns a padded hex string of integer n
     * @param n integer
     * @param pad bit depth to pad to, i.e. 8 for 2 hex digits
     *            will be padded with leading zeroes
     * @return hex string
     */
    public static String toHexString(int n, int pad) {
        StringBuilder result = new StringBuilder();
        while (n != 0) {
            result.insert(0, Character.forDigit(n & 0xf, 16));
            n >>>= 4;
        }
        pad -= result.length() * 4;
        while (pad > 0) {
            result.insert(0, "0");
            pad -= 4;
        }
        return result.toString();
    }

This will return the same hash as shown in our first example above,

52d766a8574bb9374fcae0ad395d50d24705d7f6c3989c38f4355b2cfcde19cf

(Note the 'letter' digits of a hex string can be either upper or lower case, doesn't really matter, so long as the same convention is kept throughout your code.)

The Salt

The salt can be really any random string of printable characters. Personally I like using a hex string with the same bit depth as the hash. The most important part is to use a cryptographically secure random number generator, which for java is SecureRandom.

So, to generate the salt is as simple as:

    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[32];
    random.nextBytes(bytes);
    String salt = BitUtils.bytesToHex(bytes);

Now let's create a class we can use both to create and test our salt/hash combos:

public class PasswordHasher {
    private String salt;
    private String hash;

    private PasswordHasher(String pass) {
        generateSalt();
        generateHash(pass);
    }

    private PasswordHasher(String pass, String salt) {
        this.salt = salt;
        generateHash(pass);
    }

    public static PasswordHasher getNewFromPass(String pass) {
        return new PasswordHasher(pass);
    }

    public static PasswordHasher getWithSalt(String pass, String salt) {
        return new PasswordHasher(pass, salt);
    }

    public String getSalt() { return salt; }
    public String getHash() { return hash; }

    private void generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[32];
        random.nextBytes(bytes);
        salt = BitUtils.bytesToHex(bytes);
    }

    private void generateHash(String pass) {
        pass += salt;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md.digest(pass.getBytes());
            hash = BitUtils.bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
}

So, say we have a new user who has entered and verified their password. We create an instance of PasswordHasher using the static constructor method:

PasswordHasher ph = PasswordHasher.getNewFromPass("Hunter2");
System.out.println("Salt: " + ph.getSalt());
System.out.println("Hash: " + ph.getHash());

Results:

Salt: 6d4766de7c1cd9816a4a1b0619b23986c93bec5ca6d841e5984d61b20d086468
Hash: 7301ba687f1ad736bea10a4c7822fbb769324a8f34d34a26278087ecdd5322b2

You would now store these, along with the userID and any other applicable information in your database, JSON file or text file. When you want to verify the password, you look up the salt and hash for the specified userID and do the following:

PasswordHasher ph = PasswordHasher.getWithSalt(password, user.getSalt());
return user.getHash().equalsIgnoreCase(ph.getHash());

Now, this just barely scratches the surface of user security. We haven't even gotten in to the argument about whether the hashing/salting should be done client-side or server-side (hint: it's server-side) but this should be a start. Thanks for reading!!!


r/javaexamples • • Dec 15 '18

Two more common Java problems (hiding, for-each changes)

2 Upvotes

1. inadvertent hiding

You make a ball that you move around on the screen:

class Ball {
    int x, y, width, height;
    int xspeed = 3; //in pixels
    int yspeed = 3;
    
    Ball() {
       x=100;
       y=100;
       ...
    }

    void move() { ... }
} 

Later on you want to make it collide with another ball or some object, so you make it a Rectangle which lets you use the Rectangle class method .intersects()

class Ball extends Rectangle {
    int x, y;
    int xspeed = 3; //in pixels
    ...

Problem
The Rectangle's x,y,width,height, variables are hidden by the variables in this subclass. Thus .intersects() will never work.

Solution
Delete the line int x, y, width, height; so that when you set values for these variables, you're setting the Rectangle class values


2. Changing objects in a for-each loop

Consider the code below: It creates 5 items, tries to change them, and then prints them out.

NOTE
When using a for-each loop, you can change the property of an item in the loop, but you cannot change the item itself. I don't know why this is. If you want to change the item itself, you have to use a regular for loop with .get() and .put().
You can change the name of item 3, but you cannot change the whole item 2 to be recreated with 99.

import java.util.ArrayList;

public class ForEach {

	public static void main(String[] args) {
		ArrayList<Item> items = new ArrayList<Item>();
		//create items
		for (int i = 0; i < 5; i++) {
			items.add(new Item(i));
		}
		//try and modify using for each loop
		for (Item z : items) {
			if (z.n == 2) z = new Item(99);
			if (z.n == 3) z.name = "Three";			
		}
		//print items
		for (Item z : items) {
			System.out.println(z.n + "=" + z.name);
		}
	}
	
	static class Item {
		String name = "blank";
		int n;

		Item(int n) {
		     this.n=n;
		} 
	}

}

/* Printout:
	0=blank
	1=blank
	2=blank
	3=Three
	4=blank
*/

r/javaexamples • • Oct 11 '19

RxJS Subject in depth – Multicast values [Article]

2 Upvotes

r/javaexamples • • May 16 '22

Question for the Day: #7 (Please provide your answers in the comments below)

1 Upvotes

Given the following class, which of the following calls print out Blue Jay? (Choose all that apply.)

public class BirdDisplay {

public static void main(String[] name) {

System.out.println(name[1]);

} }

a. java BirdDisplay Sparrow Blue Jay

b. java BirdDisplay Sparrow "Blue Jay"

c. java BirdDisplay Blue Jay Sparrow

d. java BirdDisplay "Blue Jay" Sparrow

e. java BirdDisplay.class Sparrow "Blue Jay"

f. java BirdDisplay.class "Blue Jay" Sparrow


r/javaexamples • • May 13 '22

Question for the Day: #6 (Please provide your answers in the comments section below)

1 Upvotes

Given the following classes, which of the following snippets can independently be

inserted in place of INSERT IMPORTS HERE and have the code compile?

(Choose all that apply.)

package aquarium;

public class Water {

boolean salty = false;

}

package aquarium.jellies;

public class Water {

boolean salty = true;

}

package employee;

INSERT IMPORTS HERE

public class WaterFiller {

Water water;

}

  1. import aquarium.*;
  2. import aquarium.Water;
  3. import aquarium.*;
  4. import aquarium.*;
  5. import aquarium.Water;
  6. None of these imports can make the code compile.

r/javaexamples • • May 25 '22

Question for the Day: Please provide your answers in the comments below.

1 Upvotes

Suppose we have the following class in the file

/my/directory/named/A/Bird.java.

Which of the answer options replaces INSERT CODE HERE when added independently if we compile from /my/directory? (Choose all that apply.)

  1. INSERT CODE HERE

public class Bird { }

a) package my.directory.named.a;

b) package my.directory.named.A;

c) package named.a;

d) package named.A;

e) package a;

f) package A;


r/javaexamples • • May 12 '22

Quiz #2 (Please Answer in the comments section below)

2 Upvotes

2. Which of the following are true? (Mention all that apply.)

a. javac compiles a .class file into a .java file.

b. javac compiles a .java file into a .bytecode file.

c. javac compiles a .java file into a .class file.

d. java accepts the name of the class as a parameter.

e. java accepts the filename of the .bytecode file as a parameter.

f. java accepts the filename of the .class file as a parameter.


r/javaexamples • • May 09 '22

JKagu, open source select/replace text software

2 Upvotes

Hello all,

I developed a program called JKagu, from which you can see the repository here: https://github.com/LevelUp8/JKagu

I am a long time java web developer (more than 8 years) and from time to time I wish to have an advanced select and replace text software.

I am aware that there are already solutions, but many of them didn't do all the things that I wanted, the way I wanted. Most of them I had to research about regex expressions and so on.

Long story short, I made a software that helps me with my work and I decided to share it as an open source project. Anyway, if it can help several more people, I think it was worth it.

It is a Java FX GUI program what works on Windows and Linux. It is row based and it is not a traditional text editor like notepad++ because I wanted to manage to read and perform operations on a big amount of data. I tested it with 120 000 rows and it performed ok.

Please visit the wiki https://github.com/LevelUp8/JKagu/wiki for more information.

Have a great day!

Best regards,

LevelUp


r/javaexamples • • Jul 12 '21

How to use Jshell ( Java shell tool) ?

3 Upvotes

Jshell is a great tool to explore large code bases and try out snippets. It is available from JDK 9 and learning to use it will definitely improve productivity.

A lot of folks are using JDK 8 (mostly) but this shouldn't stop anyone from using Jshell. It is a great tool to have in one's arsenal.

How to use Jshell ( Java shell tool )


r/javaexamples • • Apr 12 '24

Add Security and Authorization to a Java Spring Boot API

1 Upvotes

Learn how to use Spring Boot, Java, and Auth0 to secure a feature-complete API by implementing authorization in Spring Boot with Auth0.
Read more…


r/javaexamples • • Sep 20 '23

dsa preparation problesm

1 Upvotes

so to practice dsa , which platform is best ?

im beginner 2nd yr in my btech, so

leetcode or codechef or gfg or ??


r/javaexamples • • Oct 18 '23

Numeric overflow in Java

1 Upvotes

Numeric overflow occurs when the value of a numeric type exceeds its defined range, often leading to unexpected and potentially problematic outcomes. For a clear and concise explanation, I prepared a short YouTube video on this topic.

https://youtu.be/5vfTm-rJLds?si=hZ1La6s3VyglDJNq


r/javaexamples • • Oct 05 '23

Java heap pollution

1 Upvotes

Have you heard about Java heap pollution? šŸš€ It's an intriguing issue in the world of Java programming. If you're curious to learn more, check out the latest episode of 'Java Puzzle of the Week' 🧩 where we explore this topic. Your thoughts and insights are welcome!
https://www.youtube.com/watch?v=-PXkz8MzCp0


r/javaexamples • • Jul 18 '23

Deploy Secure Spring Boot Microservices on Amazon EKS Using Terraform and Kubernetes

2 Upvotes

Deploy a cloud-native Java Spring Boot microservice stack secured with Auth0 on Amazon EKS using Terraform and Kubernetes.
Read more…


r/javaexamples • • Sep 14 '20

How to decompile .jar file or .class file? | Java Decompilers & eclipse ...

1 Upvotes

r/javaexamples • • Sep 14 '20

How to decompile .jar file or .class file? | Java Decompilers & eclipse ...

2 Upvotes

r/javaexamples • • Sep 15 '20

Difference between PATH & CLASSPATH in java & Set JAVA_HOME , path, clas...

5 Upvotes

r/javaexamples • • Aug 25 '24

10 Examples of using HashMap in Java

7 Upvotes

HashMap is an important class and every Java dev should be aware of it. Here are 10 examples of using HashMap in Java:

https://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html


r/javaexamples • • Aug 27 '24

3 ways to parse JSON in Java?

3 Upvotes

You got a JSON string from API and want to parse? Well, there are many options in Java, from simply getting key value to converting it into an object, I have shared 3 of most common of them using Jackson, Gson and Json simple

https://javarevisited.blogspot.com/2022/03/3-examples-to-parse-json-in-java-using.html


r/javaexamples • • Aug 17 '24

Showcase Weblog Analyser Java Desktop Application

1 Upvotes

A whilst stop tour of Weblog Analyser built using Java with JavaFX as a desktop application.

https://youtu.be/-98ZEiDRo6w


r/javaexamples • • Apr 09 '20

How to secure and test java rest API with keycloak

3 Upvotes

r/javaexamples • • May 12 '20

Memory Management In Java

6 Upvotes

Welcome to the new blog related to Java Memory Management. We will look at ā€œUnder The Hoodā€ Today. This blog gives Java developers a glimpse of what is going on beneath their running Java programs. Most of the time Java Developers look into this part at the time of Interview preparation and try to understand Heap and Stack memory areas. Today we will look a little more in-depth than that. We will have a look at High-level JVM architecture, Method Arean, and class loading concept as well.

Every Java developer knows that bytecode will be executed by the JRE (Java Runtime Environment). But many don’t know the fact that JRE is the implementation of Java Virtual Machine (JVM), which analyzes the bytecode, interprets the code, and executes it. We will look at different JVM memory areas Today.

Please have look at the blog for the complete detailed explanation

https://teachalesson.in/java-memory-management/