Learn Java in Y Minutes
Learn Java in Y Minutes
url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Flearnxinyminutes.com%2Fdocs%2Fjava%2F&text=Learn+X+in+Y+minutes%2C+where+X%3Djava)
/*
Multi-line comments look like this.
*/
/**
* JavaDoc comments look like this. Used to describe the Class or various
* 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.
* @deprecated For showing the code is outdated or shouldn't be used.
* @see Links to another part of documentation.
*/
///////////////////////////////////////
// Input/Output
///////////////////////////////////////
/*
* Output
*/
/*
* Input
*/
///////////////////////////////////////
// Variables
///////////////////////////////////////
/*
* Variable Declaration
*/
// Declare a variable using <type> <name>
int fooInt;
// Declare multiple variables of the same
// type <type> <name1>, <name2>, <name3>
int fooInt1, fooInt2, fooInt3;
/*
* Variable Initialization
*/
/*
* Variable types
*/
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
// Note: byte, short, int and long are signed. They can have positive and
negative values.
// There are no unsigned variants.
// char, however, is 16-bit unsigned.
// Strings
String fooString = "My String Is Here!";
// String Building
// #1 - with plus operator
// That's the basic way to do it (optimized under the hood)
String plusConcatenated = "Strings can " + "be concatenated " + "via +
operator.";
System.out.println(plusConcatenated);
// Output: Strings can be concatenated via + operator.
// #2 - with StringBuilder
// This way doesn't create any intermediate strings. It just stores the
string pieces, and ties them together
// when toString() is called.
// Hint: This class is not thread safe. A thread-safe alternative (with
some impact on performance) is StringBuffer.
StringBuilder builderConcatenated = new StringBuilder();
builderConcatenated.append("You ");
builderConcatenated.append("can use ");
builderConcatenated.append("the StringBuilder class.");
System.out.println(builderConcatenated.toString()); // only now is the
string built
// Output: You can use the StringBuilder class.
// Arrays
// The array size must be decided upon instantiation
// The following formats work for declaring an array
// <datatype>[] <var name> = new <datatype>[<array size>];
// <datatype> <var name>[] = new <datatype>[<array size>];
int[] intArray = new int[10];
String[] stringArray = new String[1];
boolean boolArray[] = new boolean[100];
///////////////////////////////////////
// Operators
///////////////////////////////////////
System.out.println("\n->Operators");
// Arithmetic is straightforward
System.out.println("1+2 = " + (i1 + i2)); // => 3
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.0 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
// Comparison operators
System.out.println("3 == 2? " + (3 == 2)); // => false
System.out.println("3 != 2? " + (3 != 2)); // => true
System.out.println("3 > 2? " + (3 > 2)); // => true
System.out.println("3 < 2? " + (3 < 2)); // => false
System.out.println("2 <= 2? " + (2 <= 2)); // => true
System.out.println("2 >= 2? " + (2 >= 2)); // => true
// Boolean operators
System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // =>
false
System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
// Bitwise operators!
/*
~ Unary bitwise complement
<< Signed left shift
>> Signed/Arithmetic right shift
>>> Unsigned/Logical right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
*/
// Increment operators
int i = 0;
System.out.println("\n->Inc/Dec-rementation");
// The ++ and -- operators increment and decrement by 1 respectively.
// If they are placed before the variable, they increment then return;
// after the variable they return then increment.
System.out.println(i++); // i = 1, prints 0 (post-increment)
System.out.println(++i); // i = 2, prints 2 (pre-increment)
System.out.println(i--); // i = 1, prints 2 (post-decrement)
System.out.println(--i); // i = 0, prints 0 (pre-decrement)
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
System.out.println("\n->Control Structures");
// While loop
int fooWhile = 0;
while(fooWhile < 100) {
System.out.println(fooWhile);
// Increment the counter
// Iterated 100 times, fooWhile 0,1,2...99
fooWhile++;
}
System.out.println("fooWhile Value: " + fooWhile);
// Do While Loop
int fooDoWhile = 0;
do {
System.out.println(fooDoWhile);
// Increment the counter
// Iterated 100 times, fooDoWhile 0->99
fooDoWhile++;
} while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
// For Loop
// for loop structure => for(<start_statement>; <conditional>; <step>)
for (int fooFor = 0; fooFor < 10; fooFor++) {
System.out.println(fooFor);
// 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++) {
for (int j = 0; j < 10; j++) {
if (i == 5 && j ==5) {
break outer;
// breaks out of outer loop instead of only the inner one
}
}
}
// Switch Case
// A switch works with the byte, short, char, and int data types.
// 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) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
default: monthString = "Some other month";
break;
}
System.out.println("Switch Case Result: " + monthString);
// 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 : " + bar); // Prints "bar : A", because the
// statement is true.
// Or simply
System.out.println("bar : " + (foo < 10 ? "A" : "B"));
////////////////////////////////////////
// Converting Data Types
////////////////////////////////////////
// Converting data
///////////////////////////////////////
// Classes And Functions
///////////////////////////////////////
class Bicycle {
// Bicycle's Fields/Variables
public int cadence; // Public: Can be accessed from anywhere
private int speed; // Private: Only accessible from within the class
protected int gear; // Protected: Accessible from the class and subclasses
String name; // default: Only accessible from within this package
static String className; // Static class variable
// Static block
// Java has no implementation of static constructors, but
// 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";
}
// Method Syntax:
// <public/private/protected> <return type> <function name>(<args>)
// Java classes often implement getters and setters for their fields
// 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> {
// // Constants
// // Method declarations
// }
// Example - Food:
public interface Edible {
public void eat(); // Any class that implements this interface, must
// implement this method.
}
@Override
public void digest() {
// ...
}
}
// In Java, you can extend only one class, but you can implement many
// interfaces. For example:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
public void InterfaceOneMethod() {
}
@Override
public void InterfaceTwoMethod() {
}
// Abstract Classes
// Final Classes
// Final classes are classes that cannot be inherited from and are therefore a
// final child. In a way, final classes are the opposite of abstract classes
// because abstract classes must be extended, but final classes cannot be
// extended.
public final class SaberToothedCat extends Animal
{
// Note still have to override the abstract methods in the
// abstract class.
@Override
public void makeSound()
{
System.out.println("Roar");
}
}
// Final Methods
public abstract class Mammal()
{
// Final Method Syntax:
// <access modifier> final <return type> <function name>(<args>)
// Enum Type
//
// An enum type is a special data type that enables for a variable to be a set
// of predefined constants. The variable must be equal to one of the values
// that have been predefined for it. Because they are constants, the names of
// an enum type's fields are in uppercase letters. In the Java programming
// language, you define an enum type by using the enum keyword. For example,
// you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
// 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);
*/
// 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));
// The above without use of lambdas would look more traditionally like:
for (String planet : planets.keySet()) {
System.out.format(orbits, planet, planets.get(planet));
}
// 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
The links provided here below are just to get an understanding of the topic, feel free to Google and find
specific examples.
Inheritance (https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
Polymorphism (https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
Abstraction (https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
Exceptions (https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
Interfaces (https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
Generics (https://docs.oracle.com/javase/tutorial/java/generics/index.html)
Codingbat.com (http://codingbat.com/java)
Books: