summaryrefslogtreecommitdiffhomepage
path: root/java.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'java.html.markdown')
-rw-r--r--java.html.markdown340
1 files changed, 241 insertions, 99 deletions
diff --git a/java.html.markdown b/java.html.markdown
index 12de0c73..79769352 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -10,6 +10,8 @@ contributors:
- ["Rachel Stiyer", "https://github.com/rstiyer"]
- ["Michael Dähnert", "https://github.com/JaXt0r"]
- ["Rob Rose", "https://github.com/RobRoseKnows"]
+ - ["Sean Nam", "https://github.com/seannam"]
+ - ["Shawn M. Hanes", "https://github.com/smhanes15"]
filename: LearnJava.java
---
@@ -29,13 +31,13 @@ Multi-line comments look like this.
* attributes of a Class.
* Main attributes:
*
- * @author Name (and contact information such as email) of author(s).
- * @version Current version of the program.
- * @since When this part of the program was first added.
- * @param For describing the different parameters for a method.
- * @return For describing what the method returns.
+ * @author Name (and contact information such as email) of author(s).
+ * @version Current version of the program.
+ * @since When this part of the program was first added.
+ * @param For describing the different parameters for a method.
+ * @return For describing what the method returns.
* @deprecated For showing the code is outdated or shouldn't be used.
- * @see Links to another part of documentation.
+ * @see Links to another part of documentation.
*/
// Import ArrayList class inside of the java.util package
@@ -43,13 +45,19 @@ import java.util.ArrayList;
// Import all classes inside of java.security package
import java.security.*;
-// Each .java file contains one outer-level public class, with the same name
-// as the file.
public class LearnJava {
- // In order to run a java program, it must have a main method as an entry
+ // In order to run a java program, it must have a main method as an entry
// point.
- public static void main (String[] args) {
+ public static void main(String[] args) {
+
+ ///////////////////////////////////////
+ // Input/Output
+ ///////////////////////////////////////
+
+ /*
+ * Output
+ */
// Use System.out.println() to print lines.
System.out.println("Hello World!");
@@ -65,6 +73,32 @@ public class LearnJava {
// Use System.out.printf() for easy formatted printing.
System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
+ /*
+ * Input
+ */
+
+ // use Scanner to read input
+ // must import java.util.Scanner;
+ Scanner scanner = new Scanner(System.in);
+
+ // read string input
+ String name = scanner.next();
+
+ // read byte input
+ byte numByte = scanner.nextByte();
+
+ // read int input
+ int numInt = scanner.nextInt();
+
+ // read long input
+ float numFloat = scanner.nextFloat();
+
+ // read double input
+ double numDouble = scanner.nextDouble();
+
+ // read boolean input
+ boolean bool = scanner.nextBoolean();
+
///////////////////////////////////////
// Variables
///////////////////////////////////////
@@ -74,7 +108,7 @@ public class LearnJava {
*/
// Declare a variable using <type> <name>
int fooInt;
- // Declare multiple variables of the same
+ // Declare multiple variables of the same
// type <type> <name1>, <name2>, <name3>
int fooInt1, fooInt2, fooInt3;
@@ -83,11 +117,12 @@ public class LearnJava {
*/
// Initialize a variable using <type> <name> = <val>
- int fooInt = 1;
- // Initialize multiple variables of same type with same
- // value <type> <name1>, <name2>, <name3> = <val>
- int fooInt1, fooInt2, fooInt3;
- fooInt1 = fooInt2 = fooInt3 = 1;
+ int barInt = 1;
+ // Initialize multiple variables of same type with same
+ // value <type> <name1>, <name2>, <name3>
+ // <name1> = <name2> = <name3> = <val>
+ int barInt1, barInt2, barInt3;
+ barInt1 = barInt2 = barInt3 = 1;
/*
* Variable types
@@ -95,7 +130,7 @@ public class LearnJava {
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
-
+
// If you would like to interpret a byte as an unsigned integer
// then this simple operation can help
int unsignedIntLessThan256 = 0xff & fooByte;
@@ -137,7 +172,7 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // final variables can't be reassigned to another object,
+ // final variables can't be reassigned,
final int HOURS_I_WORK_PER_WEEK = 9001;
// but they can be initialized later.
final double E;
@@ -149,12 +184,12 @@ public class LearnJava {
// integers longer than 64-bits. Integers are stored as an array of
// of bytes and are manipulated using functions built into BigInteger
//
- // BigInteger can be initialized using an array of bytes or a string.
+ // BigInteger can be initialized using an array of bytes or a string.
BigInteger fooBigInteger = new BigInteger(fooByteArray);
// BigDecimal - Immutable, arbitrary-precision signed decimal number
//
- // A BigDecimal takes two parts: an arbitrary precision integer
+ // A BigDecimal takes two parts: an arbitrary precision integer
// unscaled value and a 32-bit integer scale
//
// BigDecimal allows the programmer complete control over decimal
@@ -164,7 +199,7 @@ public class LearnJava {
// BigDecimal can be initialized with an int, long, double or String
// or by initializing the unscaled value (BigInteger) and scale (int).
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
-
+
// Be wary of the constructor that takes a float or double as
// the inaccuracy of the float/double will be copied in BigDecimal.
// Prefer the String constructor when you need an exact value.
@@ -196,13 +231,13 @@ public class LearnJava {
builderConcatenated.append("You ");
builderConcatenated.append("can use ");
builderConcatenated.append("the StringBuilder class.");
- System.out.println(builderConcatenated.toString()); // only now is the string built
+ System.out.println(builderConcatenated.toString()); // only now is the string built
// Output: You can use the StringBuilder class.
-
+
// StringBuilder is efficient when the fully constructed String is not required until the end of some processing.
StringBuilder stringBuilder = new StringBuilder();
String inefficientString = "";
- for(int i = 0 ; i < 10; i++){
+ for (int i = 0 ; i < 10; i++) {
stringBuilder.append(i).append(" ");
inefficientString += i + " ";
}
@@ -211,12 +246,12 @@ public class LearnJava {
// inefficientString requires a lot more work to produce, as it generates a String on every loop iteration.
// Simple concatenation with + is compiled to a StringBuilder and toString()
// Avoid string concatenation in loops.
-
+
// #3 - with String formatter
// Another alternative way to create strings. Fast and readable.
String.format("%s may prefer %s.", "Or you", "String.format()");
// Output: Or you may prefer String.format().
-
+
// Arrays
// The array size must be decided upon instantiation
// The following formats work for declaring an array
@@ -244,7 +279,7 @@ public class LearnJava {
// LinkedLists - Implementation of doubly-linked list. All of the
// operations perform as could be expected for a
// doubly-linked list.
- // Maps - A set of objects that map keys to values. Map is
+ // Maps - A mapping of key Objects to value Objects. Map is
// an interface and therefore cannot be instantiated.
// The type of keys and values contained in a Map must
// be specified upon instantiation of the implementing
@@ -253,10 +288,16 @@ public class LearnJava {
// HashMaps - This class uses a hashtable to implement the Map
// interface. This allows the execution time of basic
// operations, such as get and insert element, to remain
- // constant even for large sets.
- // TreeMap - This class is a sorted tree structure. It implements a red
- // black tree and sorts the entries based on the key value or
- // the comparator provided while creating the object
+ // constant-amortized even for large sets.
+ // TreeMap - A Map that is sorted by its keys. Each modification
+ // maintains the sorting defined by either a Comparator
+ // supplied at instantiation, or comparisons of each Object
+ // if they implement the Comparable interface.
+ // Failure of keys to implement Comparable combined with failure to
+ // supply a Comparator will throw ClassCastExceptions.
+ // Insertion and removal operations take O(log(n)) time
+ // so avoid using this data structure unless you are taking
+ // advantage of the sorting.
///////////////////////////////////////
// Operators
@@ -270,7 +311,7 @@ public class LearnJava {
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
- System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
+ System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -340,7 +381,7 @@ public class LearnJava {
do {
System.out.println(fooDoWhile);
// Increment the counter
- // Iterated 99 times, fooDoWhile 0->99
+ // Iterated 100 times, fooDoWhile 0->99
fooDoWhile++;
} while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
@@ -352,7 +393,7 @@ public class LearnJava {
// Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
-
+
// Nested For Loop Exit with Label
outer:
for (int i = 0; i < 10; i++) {
@@ -363,7 +404,7 @@ public class LearnJava {
}
}
}
-
+
// For Each Loop
// The for loop is also able to iterate over arrays as well as objects
// that implement the Iterable interface.
@@ -381,6 +422,9 @@ public class LearnJava {
// It also works with enumerated types (discussed in Enum Types), the
// String class, and a few special classes that wrap primitive types:
// Character, Byte, Short, and Integer.
+ // Starting in Java 7 and above, we can also use the String type.
+ // Note: Do remember that, not adding "break" at end any particular case ends up in
+ // executing the very next case(given it satisfies the condition provided) as well.
int month = 3;
String monthString;
switch (month) {
@@ -394,38 +438,21 @@ public class LearnJava {
break;
}
System.out.println("Switch Case Result: " + monthString);
-
- // Starting in Java 7 and above, switching Strings works like this:
- String myAnswer = "maybe";
- switch(myAnswer) {
- case "yes":
- System.out.println("You answered yes.");
- break;
- case "no":
- System.out.println("You answered no.");
- break;
- case "maybe":
- System.out.println("You answered maybe.");
- break;
- default:
- System.out.println("You answered " + myAnswer);
- break;
- }
-
-
+
+
// Try-with-resources (Java 7+)
// Try-catch-finally statements work as expected in Java but in Java 7+
// the try-with-resources statement is also available. Try-with-resources
- // simplifies try-catch-finally statements be closing resources
+ // simplifies try-catch-finally statements by closing resources
// automatically.
-
- // In order to use a try-with-resources, include a an instance of a class
+
+ // In order to use a try-with-resources, include an instance of a class
// in the try statement. The class must implement java.lang.AutoCloseable.
- try(BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
+ try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
// You can attempt to do something that could throw an exception.
System.out.println(br.readLine());
// In Java 7, the resource will always be closed, even if it throws
- // an Exception.
+ // an Exception.
} catch (Exception ex) {
//The resource will be closed before the catch statement executes.
System.out.println("readLine() failed.");
@@ -435,18 +462,22 @@ public class LearnJava {
// a finally statement might not be called.
// To learn more:
// https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
-
-
+
+
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
// Reads as "If (statement) is true, use <first value>, otherwise, use
// <second value>"
int foo = 5;
String bar = (foo < 10) ? "A" : "B";
- System.out.println(bar); // Prints A, because the statement is true
+ System.out.println("bar : " + bar); // Prints "bar : A", because the
+ // statement is true.
+ // Or simply
+ System.out.println("bar : " + (foo < 10 ? "A" : "B"));
+
////////////////////////////////////////
- // Converting Data Types And Typecasting
+ // Converting Data Types
////////////////////////////////////////
// Converting data
@@ -462,11 +493,6 @@ public class LearnJava {
// Long
// String
- // Typecasting
- // You can also cast Java objects, there's a lot of details and deals
- // with some more intermediate concepts. Feel free to check it out here:
- // https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
-
///////////////////////////////////////
// Classes And Functions
///////////////////////////////////////
@@ -531,10 +557,10 @@ class Bicycle {
String name; // default: Only accessible from within this package
static String className; // Static class variable
- // Static block
+ // Static block
// Java has no implementation of static constructors, but
- // has a static block that can be used to initialize class variables
- // (static variables).
+ // has a static block that can be used to initialize class variables
+ // (static variables).
// This block will be called when the class is loaded.
static {
className = "Bicycle";
@@ -617,6 +643,14 @@ class PennyFarthing extends Bicycle {
}
}
+// Object casting
+// Since the PennyFarthing class is extending the Bicycle class, we can say
+// a PennyFarthing is a Bicycle and write :
+// Bicycle bicycle = new PennyFarthing();
+// This is called object casting where an object is taken for another one. There
+// are lots of details and deals with some more intermediate concepts here:
+// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
// Interfaces
// Interface declaration syntax
// <access-level> interface <interface-name> extends <super-interfaces> {
@@ -632,10 +666,10 @@ public interface Edible {
public interface Digestible {
public void digest();
- // In Java 8, interfaces can have default method.
- // public void digest() {
- // System.out.println("digesting ...");
- // }
+ // Since Java 8, interfaces can have default method.
+ public default void defaultMethod() {
+ System.out.println("Hi from default method ...");
+ }
}
// We can now create a class that implements both of these interfaces.
@@ -668,20 +702,27 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// Abstract Classes
// Abstract Class declaration syntax
-// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
+// <access-level> abstract class <abstract-class-name> extends
+// <super-abstract-classes> {
// // Constants and variables
// // Method declarations
// }
-// Marking a class as abstract means that it contains abstract methods that
-// must be defined in a child class. Similar to interfaces, abstract classes
-// cannot be instantiated, but instead must be extended and the abstract
-// methods defined. Different from interfaces, abstract classes can contain a
-// concrete and abstract methods. Methods in an interface cannot have a body,
-// mixture of unless the method is static, and variables are final by default,
-// unlike an abstract class. Also abstract classes CAN have the "main" method.
+// Abstract Classes cannot be instantiated.
+// Abstract classes may define abstract methods.
+// Abstract methods have no body and are marked abstract
+// Non-abstract child classes must @Override all abstract methods
+// from their super-classes.
+// Abstract classes can be useful when combining repetitive logic
+// with customised behavior, but as Abstract classes require
+// inheritance, they violate "Composition over inheritance"
+// so consider other approaches using composition.
+// https://en.wikipedia.org/wiki/Composition_over_inheritance
+
public abstract class Animal
{
+ private int age;
+
public abstract void makeSound();
// Method can have a body
@@ -692,17 +733,12 @@ public abstract class Animal
age = 30;
}
- // No need to initialize, however in an interface
- // a variable is implicitly final and hence has
- // to be initialized.
- protected int age;
-
public void printAge()
{
- System.out.println(age);
+ System.out.println(age);
}
- // Abstract classes can have main function.
+ // Abstract classes can have main method.
public static void main(String[] args)
{
System.out.println("I am abstract");
@@ -717,7 +753,7 @@ class Dog extends Animal
public void makeSound()
{
System.out.println("Bark");
- // age = 30; ==> ERROR! age is private to Animal
+ // age = 30; ==> ERROR! age is private to Animal
}
// NOTE: You will get an error if you used the
@@ -781,18 +817,18 @@ public abstract class Mammal()
// you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
- THURSDAY, FRIDAY, SATURDAY
+ THURSDAY, FRIDAY, SATURDAY
}
// We can use our enum Day like that:
public class EnumTest {
// Variable Enum
Day day;
-
+
public EnumTest(Day day) {
this.day = day;
}
-
+
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
@@ -800,17 +836,17 @@ public class EnumTest {
break;
case FRIDAY:
System.out.println("Fridays are better.");
- break;
- case SATURDAY:
+ break;
+ case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
- break;
+ break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
-
+
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs(); // => Mondays are bad.
@@ -819,10 +855,112 @@ public class EnumTest {
}
}
-// Enum types are much more powerful than we show above.
+// Enum types are much more powerful than we show above.
// The enum body can include methods and other fields.
// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+// Getting Started with Lambda Expressions
+//
+// New to Java version 8 are lambda expressions. Lambdas are more commonly found
+// in functional programming languages, which means they are methods which can
+// be created without belonging to a class, passed around as if it were itself
+// an object, and executed on demand.
+//
+// Final note, lambdas must implement a functional interface. A functional
+// interface is one which has only a single abstract method declared. It can
+// have any number of default methods. Lambda expressions can be used as an
+// instance of that functional interface. Any interface meeting the requirements
+// is treated as a functional interface. You can read more about interfaces
+// above.
+//
+import java.util.Map;
+import java.util.HashMap;
+import java.util.function.*;
+import java.security.SecureRandom;
+
+public class Lambdas {
+ public static void main(String[] args) {
+ // Lambda declaration syntax:
+ // <zero or more parameters> -> <expression body or statement block>
+
+ // We will use this hashmap in our examples below.
+ Map<String, String> planets = new HashMap<>();
+ planets.put("Mercury", "87.969");
+ planets.put("Venus", "224.7");
+ planets.put("Earth", "365.2564");
+ planets.put("Mars", "687");
+ planets.put("Jupiter", "4,332.59");
+ planets.put("Saturn", "10,759");
+ planets.put("Uranus", "30,688.5");
+ planets.put("Neptune", "60,182");
+
+ // Lambda with zero parameters using the Supplier functional interface
+ // from java.util.function.Supplier. The actual lambda expression is
+ // what comes after numPlanets =.
+ Supplier<String> numPlanets = () -> Integer.toString(planets.size());
+ System.out.format("Number of Planets: %s\n\n", numPlanets.get());
+
+ // Lambda with one parameter and using the Consumer functional interface
+ // from java.util.function.Consumer. This is because planets is a Map,
+ // which implements both Collection and Iterable. The forEach used here,
+ // found in Iterable, applies the lambda expression to each member of
+ // the Collection. The default implementation of forEach behaves as if:
+ /*
+ for (T t : this)
+ action.accept(t);
+ */
+
+ // The actual lambda expression is the parameter passed to forEach.
+ planets.keySet().forEach((p) -> System.out.format("%s\n", p));
+
+ // If you are only passing a single argument, then the above can also be
+ // written as (note absent parentheses around p):
+ planets.keySet().forEach(p -> System.out.format("%s\n", p));
+
+ // Tracing the above, we see that planets is a HashMap, keySet() returns
+ // a Set of its keys, forEach applies each element as the lambda
+ // expression of: (parameter p) -> System.out.format("%s\n", p). Each
+ // time, the element is said to be "consumed" and the statement(s)
+ // referred to in the lambda body is applied. Remember the lambda body
+ // is what comes after the ->.
+
+ // The above without use of lambdas would look more traditionally like:
+ for (String planet : planets.keySet()) {
+ System.out.format("%s\n", planet);
+ }
+
+ // This example differs from the above in that a different forEach
+ // implementation is used: the forEach found in the HashMap class
+ // implementing the Map interface. This forEach accepts a BiConsumer,
+ // which generically speaking is a fancy way of saying it handles
+ // the Set of each Key -> Value pairs. This default implementation
+ // behaves as if:
+ /*
+ for (Map.Entry<K, V> entry : map.entrySet())
+ action.accept(entry.getKey(), entry.getValue());
+ */
+
+ // The actual lambda expression is the parameter passed to forEach.
+ String orbits = "%s orbits the Sun in %s Earth days.\n";
+ planets.forEach((K, V) -> System.out.format(orbits, K, V));
+
+ // The above without use of lambdas would look more traditionally like:
+ for (String planet : planets.keySet()) {
+ System.out.format(orbits, planet, planets.get(planet));
+ }
+
+ // Or, if following more closely the specification provided by the
+ // default implementation:
+ for (Map.Entry<String, String> planet : planets.entrySet()) {
+ System.out.format(orbits, planet.getKey(), planet.getValue());
+ }
+
+ // These examples cover only the very basic use of lambdas. It might not
+ // seem like much or even very useful, but remember that a lambda can be
+ // created as an object that can later be passed as parameters to other
+ // methods.
+ }
+}
```
## Further Reading
@@ -858,6 +996,10 @@ The links provided here below are just to get an understanding of the topic, fee
* [Codingbat.com](http://codingbat.com/java)
+* [Codewars - Java Katas](https://www.codewars.com/?language=java)
+
+* [University of Helsinki - Object-Oriented programming with Java](http://moocfi.github.io/courses/2013/programming-part-1/)
+
**Books**:
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)