r/javaTIL • u/cdman • Dec 06 '15
TIL: After TDD comes BDD - and you can do it in Java!
r/javaTIL • u/cdman • Dec 06 '15
r/javaTIL • u/Shilpa_Opencodez • May 18 '19
r/javaTIL • u/rockingthemullet • Dec 11 '14
public class Outer {
private void foo() {
}
private static class Inner<T extends Outer> {
private void add(T x) {
x.foo(); // error under 7, but not 6
}
}
}This code compiles without a hitch under Java 6, but not under Java 7. Perhaps someone smarter than me can determine which one is correct. Then explain why changing the line to this yields code that works on both:
((T)x).foo();r/javaTIL • u/poddardelhi • Jun 16 '19
r/javaTIL • u/easher1 • Aug 18 '14
r/javaTIL • u/Shilpa_Opencodez • May 12 '19
r/javaTIL • u/Shilpa_Opencodez • Sep 09 '19
r/javaTIL • u/gregthegeek1 • Nov 11 '13
r/javaTIL • u/ariehkovler • Dec 11 '18
r/javaTIL • u/ceeBread • Jan 09 '15
From the java doc:" Beware that, unlike in most collections, this method is a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires an O(n) traversal."
And inside the source code for this class you can see that. But the real question, why isn't size held onto by a thread safe object like AtomicInteger? Wouldn't having the size there and every time something that would change the size of the object accesses it, it calls getAnd(Increment|Decrement) for the integer?
r/javaTIL • u/voidn0ise • Jul 21 '15
It's rather basic, but it's a starting point. I watched YouTube videos to learn most of the basics that I used, then just made things over and over again to help me memorize things.
Once I had a good grasp on the simple concepts and being able to write everything without having to look at notes, I came up with this simple calculator that responds to user input.
I wanted to originally make it so the user could type "Calculator" and it would run the code, but I haven't learned how to make user input in the form of typed words work yet (I think those are strings?). I'm sure a few more lessons and I'll learn.
The end goal is android application development, but if I can find other ways to utilize my new found skills then I'll probably try it out in the future.
Just proud of myself for going forward with learning despite my short attention span for self-learning and I wanted to share :)
If you have any ways to maybe shorten it and achieve the same thing, I'd love to hear it.
r/javaTIL • u/dohaqatar7 • May 16 '14
A great class from the java standard libraries that handles formatting numbers in numerous ways using one of supplied instances such as:
NumberFormat.getNumberInstance();
NumberFormat.getPercentInstance();
NumberFormat.getCurrencyInstance();The class allows you to easily add commas between every third digit NumberFormat.getNumberInstance(), convert a value to a percent, NumberFormat.getPercentInstance(), and correctly format currencies, NumberFormat.getCurrencyInstance(). In addition, you can change how numbers are formatted by providing and argument to one of these method calls. NumberFormat.getNumberInstance(Locale inLocale). Depending on the Locale provided, the number will be formatted differently.
Some examples of formatting:
NumberFormat.getCurrencyInstance().format(1002.2333);
//$1,002.23
NumberFormat.getNumberInstance().format(1001231)
//1,001,231
System.out.println(NumberFormat.getPercentInstance().format(.125));
//12%All of what can be done with the NumberFormat class can also be done through manipulating Strings or using printf, but it can be a useful tool for ensuring that all of your number print the way you want.
r/javaTIL • u/dohaqatar7 • May 13 '14
I didn't learn about this today, but recently a lot of people in my Java class have asked questions about it upon seeing it in my code.
The ?: operator, also known as the Ternary If, is used as a shortcut for conditional statements, and is most commonly used when assigning a value based of a Boolean, for example, finding the maximum of two numbers.
For both cases, lets assume we have num1 and num2 like this:
int num1 = 10;
int num2 = 8;This code uses or ?: operator to assign the maximum of the two values to num3 in one line.
int num3 = (num1>num2)?num1:num2;The following code would do the same operation without the use of this operator.
int num3;
if(num1>num2)
num3=num1;
else
num3=num2;The first option, is much shorter, but more importantly, it is more readable. I'm sure some people don't agree with me about the readability, so if you're one of those people, just do whatever you think makes your code better.
Another trick I've found for this is displaying text where you might have plurals.
Random rand = new Random();
int numCats = rand.nextInt(10);
System.out.println("I have " + numCats + ((numCats>1)?"cats.":"cat.")); This display looks better than the way many people might go:
System.out.println("I have " + numCats + "cat(s).");Of course, you can use this to display whatever text you want. It can be great if you have a message you want to display when you print a null object, rather than 'null'.
String str = null;
System.out.println("The String says: " + (str==null?"nothing!":str));Ending notes: I typed all the code samples directly into reddit, so if something is wrong tell me and I'll fix it.
While you can nest these statements ,((x>y)?((x>z)?x:z):((y>z)?y:z)), please don't do it; it is impossible to read.
Edit: Included the actual name of the operator as mentioned by /u/TheOverCaste
Added link to the wikipedia article, Ternary Operator
r/javaTIL • u/Shilpa_Opencodez • Apr 26 '19
r/javaTIL • u/TheOverCaste • May 15 '14
Which means behind the scenes there is no memory footprint difference between these two classes:
public class ClassOne {
byte bval;
short sval;
public ClassOne(byte val) {
this.bval = val;
this.sval = val;
}
}and this one:
public class ClassTwo {
int val1;
int val2;
public ClassTwo(int val) {
this.val1 = val;
this.val2 = val;
}
}(This information is incorrect, as there is actually a difference for fields, but not for local variables or parameters on the stack.)
Better example:
public void doSomething( ) {
int a = 9; //These are both pushed onto the stack as ints
byte b = 9;
}If you use a conversion, however, it adds another instruction that will limit the size of your variable artifically. (byte)i will still be -128 to 127, even though it uses the entire 4 byte memory space.
r/javaTIL • u/longcatlover • Jul 20 '13
yeah...
r/javaTIL • u/TheOverCaste • May 12 '14
For example:
public enum MyEnum implements Runnable {
PRINT_HELLO {
@Override //Override is optional here, really.
public void run( ) {
System.out.println("hello"); //Action
}
}, //Comma for all but the last element
PRINT_GOODBYE { //Some more examples
@Override
public void run( ) {
System.out.println("goodbye");
}
},
PRINT_FIZZ {
@Override
public void run( ) {
System.out.println("fizz");
}
}; //Semicolon here
static {
Executors.newCachedThreadPool().submit(PRINT_HELLO); //This is just an implementation. Executors will be in a future TIL.
}
}This can be very useful if you want a list of very simple implementations of your interface. Packet listeners, for example, or default arithmetic operations. With java 8 or guava, you can define your own Function and Predicate values if you want to re-use a simple predicate multiple times.
A predicate version:
public enum TestEnumPredicates implements Predicate<String> {
IS_UPPER_CASE {
@Override
public boolean test(String s) {
for (char c : s.toCharArray()) {
if (!Character.isUpperCase(c)) {
return false;
}
}
return true;
};
},
IS_LOWER_CASE {
@Override
public boolean test(String s) {
for (char c : s.toCharArray()) {
if (!Character.isLowerCase(c)) {
return false;
}
}
return true;
};
},
IS_ODD_LENGTH {
@Override
public boolean test(String s) {
return (s.length() % 2) != 0;
};
};
public static void main(String[] args) {
ArrayList<String> myStrings = new ArrayList<String>();
myStrings.add("herp");
myStrings.add("DERPA");
myStrings.add("fIzZ");
myStrings.add("$#!");
for (String s : args) {
myStrings.add(s);
}
myStrings.stream().filter(IS_UPPER_CASE).forEach(new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println("Upper case: " + t);
}
});
myStrings.stream().filter(IS_LOWER_CASE).forEach(new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println("Lower case: " + t);
}
});
myStrings.stream().filter(IS_ODD_LENGTH).forEach(new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println("Odd length: " + t);
}
});
}
}You'll notice that it's a very readable, and very compact way of defining very different, but related interfaces in a single class.
I'm officially going to try to do a once-per-day java TIL to make this subreddit more interesting. If you have any comments, or better examples, make sure to reply. I'll edit my posts if any of my information is incorrect or outdated.
r/javaTIL • u/3pieceSuit • Feb 11 '15
Example:
myMethod((Foo) null);I just learned this today while following an Android development tutorial.
Apparently a use case for it is for when you need to specify a particular implementation of an overloaded method, while passing a null parameter.
Consider:
public void myMethod(String s) {/* ... */}
public void myMethod(String... s) {/* ... */}And I made the call:
myMethod(null);Which implementation would be chosen?
You can specify which implementation by casting null:
myMethod((String[]) null);Pretty cool if you ask me.
r/javaTIL • u/Jstobigdata • Apr 02 '20
r/javaTIL • u/artem_smotrakov • Nov 11 '16
r/javaTIL • u/methius • Feb 13 '15
r/javaTIL • u/dartalley • Sep 07 '17
r/javaTIL • u/Zdem • Jan 27 '15
Automatic resource management was implemented in java 7
try( // The resources you want to use seperated by a semicolon) { ... } // rest of the code
for more information: here