fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,34 @@
---
title: Exceptions in Java
---
## What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the programs instructions.
## Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
## Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
## How to use try-catch clause
```
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally {
// block of code to be executed after try block ends
}
```

View File

@ -0,0 +1,49 @@
---
title: Abstract Classes in Java
---
Lets discuss abstract classes. Before diving into this tutorial it is better that you have understood concepts of classes
and inheritance.
Abstract classes are classes that can be subclassed (i.e. extended) but cannot be instantiated. You can think of them as a **class version** of interfaces, or as an interface with actual code attached to the methods.
Consider the following example to understand abstract classes:
You have a class Vehicle which defines certain basic functionality (methods) and certain components (object variables) that a machinery should have, to be classified as a vehicle. You cannot create an object of Vehicle because a vehicle in itself is an abstract concept. You can however extend the functionality of the vehicle class to create a Car or a Motorcycle.
``` java
abstract class Vehicle
{
//variable that is used to declare the no. of wheels in a vehicle
private int wheels;
//Variable to define the type of motor used
private Motor motor;
//an abstract method that only declares, but does not define the start
//functionality because each vehicle uses a different starting mechanism
abstract void start();
}
public class Car extends Vehicle
{
...
}
public class Motorcycle extends Vehicle
{
...
}
```
You cannot create an object of Vehicle class anywhere in your program. You can however, extend the abstract vehicle class and create objects of the child classes;
``` java
Vehicle newVehicle = new Vehicle(); // Invalid
Vehicle car = new Car(); // valid
Vehicle mBike = new Motorcycle(); // valid
Car carObj = new Car(); // valid
Motorcycle mBikeObj = new Motorcycle(); // valid
```
If the child class doesn't implement the abstract methods of the father, it becomes an abstract class.

View File

@ -0,0 +1,120 @@
---
title: Access Modifiers
---
# Access Modifiers
Have you ever wanted to define how people would access some of your properties? You would not want anyone using your underwear. However, your close friends and relatives can use your sweater and maybe your car.
Similarly to how you set a level of access to your posessions, Java controls access, too. You want to define the access level for variables, methods and classes depending on which other classes you want accessing them.
Java provides 4 levels of access modifiers. This means that you can modify access to a variable, method or a class in 4 ways. These 4 ways are private, public, protected and default.
These access modifiers can be applied to fields, methods and classes (Classes are a special case, we will look at them at the end of this artice). Here is a quick overview<sup>1</sup> of what the `Access Levels` are for each `Access Modifier`:
#### Access Modifiers Table Reference:
![Access Modifiers Table](https://i.imgur.com/zoMspyn.png)
#### Private Access Modifier
Allows a variable or method to only be accessed in the class in which it was created. No other class beyond the class that created the variable or method can access it. This is closely similar to your internal organs. They are only accessible to the owner. To make a variable or method private, you simply append the private keyword before the variable or method type.
Let us use private in a coding example. If a bank wants to provide an interest rate of 10% on it's loans, it would make sure that the interest rate variable(let us suppose `int int_rate;`) would stay private so as no other class would try to access it and change it.
For example;
`private String name;`
The above example creates a variable called name and ensures that it is only accessible within the class from which it was created.
Another example for a method is
```java
private void setAge(){
System.out.println("Set Age");
}
```
The above example ensures that the method setAge is accessible only within the class from which it was created and nowhere else.
#### Public Access Modifier
The public access modifier is the direct opposite of the private access modifier. A class, method or variable can be declared as public and it means that it is accessible from any class. Public access modifier can be likened to a public school where anyone can seek admission and be admitted.
A public class, method, or variable can be accessed from any other class at any time.
For example, to declare a class as public, all you need is:
```java
public class Animal{
}
```
As such, the Animal class can be accessed by any other class.
```java
public int age;
public int getAge(){
}
```
Above are ways of specifying a variable and a method as public.
#### The Default Access Modifier
The default access modifier is different from all the other access modifiers in that it has no keyword. To use the default access modifier, you simply use none of the other access modifiers and that simply means you are using a default access modifier.
For example, to use the default access modifier for a class, you use
```java
class Bird{
}
```
This basically means you are using the default access modifier. The default access modifier allows a variable, method, or class to be accessible by other classes within the same package. A package is a collection of related classes in a file directory. For more information about packages, check out the section on packages.
Any variable, method, or class declared to use the default access modifier cannot be accessed by any other class outside of the package from which it was declared.
```java
int age;
void setNewAge(){
}
```
Above are some ways of using the default access modifier for a variable or method.
Don't forget, the default access modifier does not have a key word. The absence of the 3 other access modifiers means you are using the default access modifier.
#### Protected Access Modifier
The protected access modifier is closely related to the default access modifier. The protected access modifier has the properties of the default access modifier but with a little improvement.
A variable and method are the only ones to use the protected access modifier. The little improvement is that a class outside the class package from which the variable or method was declared can access the said variable or method. This is possible ONLY if it inherits from the Class, however.
The class from another package which can see protected variables or methods must have extended the Class that created the variables or methods.
Note without the advantage of Inheritance, a default access modifier has exactly the same access as a protected access modifier.
Examples of using the protected access modifier is shown below:
```java
protected int age;
protected String getName(){
return "My Name is You";
}
```
#### Access Modifiers on Classes
By default, classes can only have 2 modifiers:
- public
- no modifier (default modifier)
So this means classes can never be set to `private` or `protected`?
This is logical, why would you want to make a private class? No other class would be able to use it. But sometimes, you can embed a class into another class. These special classes, `inner classes`, can be set to private or protected so that only its surrounding class can access it:
```java
public class Car {
private String brand;
private Engine engine;
// ...
private class Engine {
// ...
}
}
```
In the above example, only the `Car` class can use the `Engine`class. This can be useful in some cases.
Other classes can never be set to `protected` or `private`, because it makes no sense. The `protected`access modifier is used to make things `package-private` but with the option to be accessible to subclasses. There is no concept such as 'subpackages' or 'package-inheritance' in java.
### Sources
[1. Oracle docs on Access Modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html "Oracle Docs")

View File

@ -0,0 +1,69 @@
---
title: ArrayList
---
# ArrayList
ArrayList is a part of something called the *Collection framework*.
The *Collection framework* consists of all interfaces and classes that can hold a set of values (similar to [arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)). **ArrayList** is a class that is in this hierarchy and known as a _**Collection object**_. It implements the *List* interface which in turn implements the *Collection* interface. This *Collection* interface can be found in the `java.util` package. You will need to import this package.
import java.util.ArrayList; //it would more efficient.
always import specific package that saves memory size and works in less time
ArrayList is a class that is used to create dynamic arrays. It is slower than regular arrays but allows for a lot of manipulation. It can be initialized to have a specific size or it will have a default size of 10 units.
```java
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> ages = new ArrayList<>(5);
```
In the above snippet, the angle breackets `<>` take a generic data type as argument specifying data type of the elements in the ArrayList. The first ArrayList `names` is specified as containing *String* elements. Thus, it will only be allowed to contain String elements. Its size is not specified so it will have a default size of 10. The second ArrayList `ages` has specified that it will only hold integers. But ArrayList cannot hold primitives, it only holds objects. Thus to make it store integers, floats, etc., we can use wrapper classes. `names` will have a specified size of 5.
Since ArrayList implements *List*, an ArrayList can be created using the following syntax:
```java
List<Integer> students = new ArrayList<>();
```
An ArrayList is dynamic, meaning it will grow in size if required and similarly shrink in size if elements are deleted from it. This is what makes it better to use than normal arrays.
To clear/delete all elements from ArrayList
```java
variable.clear();
```
we can delete existing element from the list
```java
variable_name.remove(index_number);
```
to access existing element from the list
```java
variable_name.get(index_number);
```
we can modify the existing element too
```java
variable_name.set(index_number,element);
```
we can reverse the order of elements in Array-list.
import java.util.Collections // package
```java
Collections.reverse(variable_name);
```
Sort the collection // in ascending order
```java
Collections.sort(variable_name);
```
for sorting in decending order
```java
Collections.reverseOrder());
```
An ArrayList allows us to randomly access elements. ArrayList is similar to *Vector* in a lot of ways. But it is faster than Vectors. The main thing to note is that - Vectors are faster than arrays but ArrayLists are not.
So when it comes down to choosing between the two - if speed is critical then Vectors should be considered, otherwise ArrayLists are better when it comes to storing large number of elements and accessing them efficiently.

View File

@ -0,0 +1,171 @@
---
title: Arrays
---
# Array
An Array is a collection of values (or objects) of similar datatypes (primitive and reference both form of datatypes are allowed) held in sequencial memory addresses.
An Array is used to store a collection of similar data types.
Arrays always start with the index of 0 and are instantiated to a set number of indexes.
All the variables in the array must be of the same type, declared at instantiation.
**Syntax:**
```java
dataType[] arrayName; // preferred way
```
Here, ```java datatype[] ``` describes that all the variables stated after it will be instantiated as arrays of the specified datatype. So, if we want to instantiate more arrays of the similar datatype, we just have to add them after the specified ```java arrayName```(Don't forget to separate them through commas only). An example is given below in the next section for reference.
```java
dataType arrayName[]; // works but not preferred way
```
Here, ```java datatype``` describes only that the variables stated after it belong to that datatype. Besides, ```java []``` after the variable name describes that the variable is an array of the specified datatype (not just a value or object of that datatype). So, if we want to instantiate more arrays of the similar datatype, we will add the variables names just after the one already specified, separated by commas and each time we will have to add ```java []``` after the variable name otherwise the variable will be instantiated as an ordinary value-storing variable (not an array). For better understanding an example is given in the next section.
## Code snippets of above syntax:
```java
double[] list1, list2; // preferred way
```
Above code snippet instantiates 2 arrays of double type names list1 and list2.
```java
double list1[], list2; // works but not preferred way
```
Above code snippet an array of datatype double named list1 and a simple variable of datatype double named list2 (Don't be confused with the name **list2**. Variables names have nothing to do with the type of variable).
Note: The style `double list[]` is not preferred as it comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Additionally it's more readable: you can read that it's a "double array named list" other than "a double called list that is an array"
## Creating Arrays:
```java
dataType[] arrayName = new dataType[arraySize];
```
## Code snippets of the above syntax:
```java
double[] List = new double[10];
```
## Another way to create an Array:
```java
dataType[] arrayName = {value_0, value_1, ..., value_k};
```
## Code snippets of above syntax:
```java
double[] list = {1, 2, 3, 4};
The code above is equivalent to:
double[] list = new double[4];
*IMPORTANT NOTE: Please note the difference between the types of brackets
that are used to represent arrays in two different ways.
```
## Accessing Arrays:
```java
arrayName[index]; // gives you the value at the specified index
```
## Code snippets of above syntax:
```java
System.out.println(list[1]);
```
Output:
```
2.0
```
## Modifying Arrays:
```java
arrayName[index] = value;
```
Note: You cannot change the size or type of an array after initialising it.
Note: You can however reset the array like so
```java
arrayName = new dataType[] {value1, value2, value3};
```
## Size of Arrays:
It's possible to find the number of elements in an array using the "length attribute". It should be noticed here that ```java length``` is an **attribute** of every array i.e. a variable name storing the length of the variable. It must not be confused for a **method** of array since the name is same as the ```java length()``` method corresponding to String classes.
```java
int[] a = {4, 5, 6, 7, 8}; // declare array
System.out.println(a.length); //prints 5
```
## Code snippets of above syntax:
```java
list[1] = 3; // now, if you access the array like above, it will output 3 rather than 2
```
_Example of code:_
```java
int[] a = {4, 5, 6, 7, 8}; // declare array
for (int i = 0; i < a.length; i++){ // loop goes through each index
System.out.println(a[i]); // prints the array
}
```
Output:
```java
4
5
6
7
8
```
### Multi-dimensional Arrays
Two-dimensional arrays (2D arrays) can be thought of as a table with rows and columns. Though this representation is only a way to visualize the array for better problem-solving. The values are actually stored in sequential memory addresses only.
```java
int M = 5;
int N = 5;
double[][] a = new double [M][N]; //M = rows N = columns
for(int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
//Do something here at index
}
}
```
This loop will execute M ^ N times and will build this:
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
Similarly a 3D array can also be made. It can be visualised as a cuboid instead of a rectangle(as above), divided into smaller cubes with each cube storing some value. It can be initialised follows:
```java
int a=2, b=3, c=4;
int[][][] a=new int[a][b][c];
```
In a similar manner, one can an array of as many dimensions as he/she wishes to but visualizing an array of more than 3 dimensions is difficult to visualize in a particular way.
### Jagged Arrays
Jagged arrays are multi-dimensional arrays that have a set number of rows but a varying number of columns. Jagged arrays are used to conserve memory use of the array. Here is a code example:
```java
int[][] array = new int[5][]; //initialize a 2D array with 5 rows
array[0] = new int[1]; //creates 1 column for first row
array[1] = new int[2]; //creates 2 columns for second row
array[2] = new int[5]; //creates 5 columns for third row
array[3] = new int[5]; //creates 5 columns for fourth row
array[4] = new int[5]; //creates 5 columns for fifth row
```
Output:
[ 0 ]
[ 0 | 1 ]
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
[ 0 | 1 | 2 | 3 | 4 ]
#### More Information:
* Source: <a href='https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html' target='_blank' rel='nofollow'>Java Arrays</a>

View File

@ -0,0 +1,61 @@
---
title: bitwise operator example
---
# Bitwise operators
## Truth table
![truth table](https://4.bp.blogspot.com/-0KPDI41veH0/V-OtObm_UWI/AAAAAAAAAso/CkTS0zUMGKIjlE3gUD0fMhmp-B0zcfBmACLcB/s1600/Bitwise-truthtable-Javaform.jpg "truth table")
The bitwise operators are similar to the logical operators, except that they work on a smaller scale -- binary representations of data. Any data can be converted to its binary equivalent. Though binary operators work at binary level but they are operated between normal decimal values only.
## Types of Bitwise Operators
### Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If not, it gives 0.
### Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.
### Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
### Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.
### Left Shift
The left shift operator << shifts a bit pattern to the left by certain number of specified bits, and zero bits are shifted into the low-order positions.
### Right Shift
The right shift operator >> shifts a bit pattern to the right by certain number of specified bits.If the number is a 2's complement signed number, the sign bit is shifted into the high-order positions.
### Unsigned Right Shift
The unsigned right shift operator >>> shifts zero into the leftmost position.
### Example bitwise operators :
```java
int a = 60; /* 60 = 0011 1100 represents 60 in binary*/
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
c = a | b; /* 61 = 0011 1101 */
c = a ^ b; /* 49 = 0011 0001 */
c = ~a; /*-61 = 1100 0011 :Invert all bits */
// shift operators : zeros are shifted in to replace the discarded bits
c = a << 2; /* 240 = 1111 0000 : Shift left 2 bits*/
c = a >> 2; /* 15 = 1111 */
c = a >>> 2; /* 15 = 0000 1111 : Zero fill right shift*/
```
**FOR FURTHER INFORMATION:** <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html">Click Here</a>

View File

@ -0,0 +1,51 @@
---
title: Basic Operations
---
# Basic Operations
Java supports the following operations on variables:
* __Arithmetic__ : `Addition (+)`, `Subtraction (-)`, `Multiplication (*)`, `Division (/)`, `Modulus (%)`,`Increment (++)`,`Decrement (--)`.
* __String concatenation__: `+` can be used for String concatenation, but subtraction `-` on a String is not a valid operation.
* __Relational__: `Equal to (==)`, `Not Equal to (!=)`, `Greater than (>)`, `Less than (<)`, `Greater than or equal to (>=)`, `Less than or equal to (<=)`
* __Bitwise__: `Bitwise And (&)`, `Bitwise Or (|)`, `Bitwise XOR (^)`, `Bitwise Compliment (~)`, `Left shift (<<)`, `Right Shift (>>)`, `Zero fill right shift (>>>)`
* __Logical__: `Logical And (&&)`, `Logical Or (||)`, `Logical Not (!)`
* __Assignment__: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `&=`, `^=`, `|=`
* __Others__: `Conditional/Ternary(?:)`, `instanceof`
While most of the operations are self-explanatory, the Conditional (Ternary) Operator works as follows:
`expression that results in boolean output ? return this value if true : return this value if false;`
Example:
True Condition:
```java
int x = 10;
int y = (x == 10) ? 5 : 9; // y will equal 5 since the expression x == 10 evaluates to true
```
False Condition:
```java
int x = 25;
int y = (x == 10) ? 5 : 9; // y will equal 9 since the expression x == 10 evaluates to false
```
The instance of operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass or an interface. General format-
*object **instance** of class/subclass/interface*
Here is a program to illustrate instanecof operator:
```Java
Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an
// instance of Boy or interface
System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person)); /*it returns true since obj1 is an instance of person */
```

View File

@ -0,0 +1,20 @@
---
title: Build Tools
---
# Build Tools
Java build tools allow you to customize your builds to do things such as specifying which files need to be included in your jar, adding dependencies from the internet, and automatically executing tasks like tests or github commits. Build tools also make it easy to modularize your projects. Popular build tools include [Gradle](https://gradle.org/) and [Maven](https://maven.apache.org/)
## Gradle
Gradle build scripts can be written in Groovy or Kotlin and are highly customizable. Most projects use the Gradle wrapper, allowing them to be built on any system, even without Gradle installed. Gradle is the recommended build tool for Android development.
## Maven
Maven build files are written with XML. Like Gradle, many plugins are written for Maven to customize your builds, however Maven is not as customizable because you cannot directly interact with a Maven API.
### More Information:
https://gradle.org/
https://en.wikipedia.org/wiki/Gradle
https://maven.apache.org/what-is-maven.html
https://en.wikipedia.org/wiki/Apache_Maven

View File

@ -0,0 +1,13 @@
---
title: Built-In Functions
---
# Built-In Functions
Java also has many built-in or pre-defined functions which are usually stored in the java.lang and java.io packages,
which are automatically imported in editors like BlueJ or can be imported using the following Syntax-
```java
import java.lang.*;
import java.io.*;
```
These comprise functions which make an otherwise long and hard task easier to do.

View File

@ -0,0 +1,84 @@
---
title: Classes and Objects
---
# Classes and Objects
Classes are groups of variables and operations on them. A class can have variables, methods (or functions), and constructors (or methods which are used to initiate, more on that later!).
A class may contain any of the following variable types.
* Class Variables: These are the variables that are declared inside the class definition, outside any method, with the static keyword. A class variable is shared across all the instances of a class. Class variables are also known as the static variables, they are initialised only once at the time of the compilation of the class hence only single copy of this is available for all the instances.
* Instance variables: The difference with the class variables is that instance variables are initialized inside the class constructor and they are not shared across all the objects. At the time of the instantiation a new copy of the instance variable is created.
```java
public class Example {
private static int myVar = 1; // Class Variable
private int mySecondVar; // Instance Variable
Example(int mySecondVar) {
this.mySecondVar = mySecondVar; // An instance variable must be initialized inside the constructor
```
Think of a `Class` as a blueprint for creating something concrete. A `Class` tells you how the 'what' and 'how' an `object` of said Class will look once `instantiated`. In essence, it defines `properties` (say color, engine capacity) and `behavior` (stop, speed up, change gears, honk etc.) for a Car in the case below.
Objects are _instances_ of a class. All objects are instances of a certain class. Imagine a class being a "template", from which every Object copies. When you create an Object, it basically creates a new object on the blueprint of a class. Now let's look at this in a little piece of code :
```java
// Car class
public class Car {
// car name
private String name;
// car manufacturer name
private String manufacturerName;
// constructor 1
public Car() {
}
// constructor 2
public Car(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
// getter name method
public String getName() {
return name;
}
// getter manufacture method
public String getManufacturerName() {
return manufacturerName;
}
//setter name method
public void setName(String name){
this.name = name;
}
//setter manufacture method
public void setManufacture(String man){
this.manufacturerName = man;
}
}
// sample code
Car modelS = new Car("Model S","Tesla");
// prints Tesla Model S
System.out.println("Full Car Model S= " + modelS.getManufacturerName() + " : " + modelS.getName());
Car modelX = new Car();
modelX.setName("Model X");
modelX.setManufacture("BMW");
// prints Tesla Model X
System.out.println("Full Car Model X= " + modelX.getManufacturerName() + " : " + modelX.getName());
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZP/0' target='_blank' rel='nofollow'>Run Code</a>
So, `Car` is a class, which has the fields or properties `name` and `manufacturerName`. `modelS` is an object of `Car` class. So `modelS` also has the same properties and methods.
It is pretty much standard to ensure the object's 'information', in this case the `name` an `manufacturerName` variables, to be private and only be accessed via these getters and setters. This prevents an issue with debugging code that involves an object's member variables. If the member variables were made public, and for whatever reason the program crashes, you could get a rather complex stack trace that may be difficult to point out the error. Keeping the variables private, and only accessible via getters and setters, will simplify this error message down.

View File

@ -0,0 +1,126 @@
---
title: Collections
---
# Collections
A Collection in Java is a group of objects which can be ordered(LinkedList) or unordered(Set). The Collection interface is at the top of the hierarchy and all other classes and interfaces extend from this interface. It is located in the java.util package.
The Collection interface also extends Iterable interface, which means that every collection in java must be iterable. This in turn means that a for-each loop can be used to fetch them in a sequence.
```java
public interface Collection<E> extends Iterable<E>
```
Some of the most common methods provided by this interface are:
```java
boolean add(E e) // Adds the specified element to the collection if not present and returns true if this collection changed.
void clear() // Removes all the elements from the collection.
boolean contains(Object o) // Returns true if the specified element is in the collection else false
boolean isEmpty() // Returns true if the collection is empty else false
boolean remove(Object o) // Removes the specifies element and return true on successful removal else false.
int size() // Returns number of items in the collection.
```
These and various other methods have to be implemented by any class implementing Collection interface.
## Interfaces extending Collection interface
Other important interfaces extending the collection interface are:
Set:
A collection containing only unique elements.
Queue:
Implement the queue behaviour where elements are added only in the beginning and removed from the end.
List:
This collection handles a list/sequence of object.
These four interfaces (Collection, Set, Queue, List) along with SortedSet, Deque and NavigableSet form the collective Collection hierarchy.
# The LinkedList class
LinkedList is one the most important Collection classes which provides a doubly-linked list implementation. It implements the List, Deque, Cloneable and Serializable interfaces.
**Create a LinkedList**
```java
LinkedList<Integer> intList = new LinkedList<Integer>(); // Creates a new list of Integer objects.
```
You can also create a list of any other object type. For eg.
```java
LinkedList<String> stringList = new LinkedList();
LinkedList<LinkedList<Integer>> listOfList = new LinkedList();
```
Note: All collections in Java have been converted to generic types since JDK 1.5
**Add elements to the list**
```java
intList.add(new Integer(1)); // Add 1 to the end.
intList.add(2); // This works as Java provides autoboxing and unboxing of primitive datatypes and their respective wrapper classes
intList.addFirst(3); // Add to the beginning of the list
intList.addLast(2); // Add to the end of the list
intList.add(2, 5); // Add element 5 at index 2
```
Let us print the list
```java
System.out.println(intList); // toString() method is automatically called on the list
```
Output:
[3, 1, 5, 2, 2]
**Retrieve elements from the list**
```java
intList.get(3); // Returns element at index 3 i.e. 2
intList.getFirst(); // Get the first element i.e. 3
intList.getLast(); // Returns last element i.e. 2
intList.indexOf(2); // Returns first occured index of 2 i.e. 3
intList.lastIndexOf(2); // Returns last occured index of 2 i.e. 4
```
**LinkedList as a Stack**
Since Java does not provide a separate
```java
intList.push(5); // Add element to the end of list. Works same as addLast()
intList.pop(); // Removes and returns the last element of the list.
```
**Remove elements from the list**
```java
intList.remove(3); // Removes the element at index 3 of the list
intList.removeFirst(); // Removes first element of the list
intList.removeLast(); // Removes last element of the list
```
Note: All the above mentioned methods for removing and fetching an element return NoSuchElementException on an empty list.
#### More Information:
* Source: <a href='https://docs.oracle.com/javase/9/docs/api/overview-summary.html' target='_blank' rel='nofollow'>Java Documentation</a>

View File

@ -0,0 +1,63 @@
---
title: Comments in Java
---
## Comments in Java
Comments in java are like real life post-it notes used to display some information, which other programmers or developers can read and understand.
It is good practice to add comments to your code, especially when working with a team or at a company. This helps future developers or teammates to know what is going on more easily when they look at your code. Comments make your code more neat and organized.
Java comments are not executed by compiler and interpreter.
### Types of Java Comments
#### 1. Single Line Comment
To create a single line comment just add two `//` forward slashes before the text.
```java
// This is how single line comment looks like
```
#### 2. Multi Line Comment
To Create a Multi line comment wrap the lines in between `/*` line goes here `*/`
```java
public class MyFirstJava {
public static void main(String[] args) {
/* This Java Code
Prints out "Hello world"
and you are looking at a multi line comment
*/
System.out.println("Hello World");
}
}
```
#### 3. Documentation Comment
Documentation comment is used by Javadoc tool to create documentation for the code. Documentation Comment is used by developers to document code, like what a class does or what a method does. This is used by a javadoc tool which will compile a preformatted set of html files containing all the information available in the comment.
```java
/**
* The Following Java program displays a random between 0 - 50
* Most Developer dont document simple program like this
*
* @author Quincy Larson
* @version 1.0
*/
public class RandomNumbers{
public static void main(String[] args) {
int random = (int)(Math.random() * 50 + 1);
System.out.println("Hello World");
}
}
```
#### More Information:
* [Java Resources](http://guide.freecodecamp.org/java/resources/)
* [Compiled Javadoc Example](https://docs.oracle.com/javase/8/docs/api/)

View File

@ -0,0 +1,180 @@
---
title: Constructors
---
If an object copies from a class, the what's the point? I should be able to store data in it right?
That's when we use either **getter** (e.g., getName()) / **setter** (e.g., setName()) methods, or in this case constructors, to initialize a class. Basically, every Java Class has a constructor which is the method called first when any object of the class is initialized. Think of it as a bit of starter code.
When you write a class without any constructor, the Java compiler creates a default constructor :
```java
public class Car {
private String name;
}
Car modelS = new Car();
```
This initializing with no parameters is a way of calling the default constructor. You can also have a default constructor written this way:
```java
public class Car {
private String name;
// User Specified Default Constructor
public Car() {
name = "Tesla";
}
}
```
Then, when calling `new Car()`, the variable `name` will get auto-initialized to "Tesla" for that instance of the Car object.
Clearly, constructors are exactly as they sound: they are used to `construct` i.e., instantiate an object of a particular class.
Constructors look similar to method declarations, but are slightly different in the sense that they:
1. Are named exactly the same as the class.
2. Don't have a return type.
Hence, the purpose of using `constructors` is to provide:
1. A way to instantiate an object.
2. Provide initial values to a object properties.
3. Control how an object is created.
Let's look at another example. Say, Honda (the car manufacturer), wants all of its cars to be named `Honda <a name>`. In order to enforce this, we might represent this using a class as follows:
```java
public class Car {
private String name;
// Constructor.
public Car(String model){
this.name = "Honda " + model;
}
public String getName(){
return this.name;
}
public static void main(String args[]){
Car car = new Car("Civic");
System.out.println( car.getName() );
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CTJ4/1' target='_blank' rel='nofollow'>Run Code</a>
Notice that when we write a constructor in this way i.e., providing a parameter, we are controlling (point no. 3) the way an instance of `Car` is created. In short, we are saying in this example that **you MUST provide a model name in order to get an instance of Car class**.
Why is this important? There are times when you'd want `one and only one` instance of a class for use in your entire application. One way of achieving this is by using a `private` constructor.
Assume you need a class to represent a Bank. You wouldn't want people to create instance of `Bank` ever. So, you design your class:
```java
public class Bank {
private static Bank instance;
private Bank(){
}
public static Bank getInstance(){
if(null == instance){
instance = new Bank();
}
return instance;
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CTJz/0' target='_blank' rel='nofollow'>Run Code</a>
Notice that the constructor is `private`. This enforces the fact that no one else is allowed to create an instance of the Bank.
In fact, if in another class, you try:
```java
Bank account = new Bank(); // Throws a compilation error: Bank() has private access in Bank.
```
So, the only way to gain access to the instance is by using `Bank.getInstance()`. Such instances are called `Singleton` since you get exactly one instance (per VM to be precise) throughout the life of your application.
There can be many number of constructors in a class. But they should differ in the method parameters. This is Constructor Overloading. To be precise, we say constructor overloading has occurred when there are two or more constructors with the same name, but different method parameters. As a result, the two functions have different method signatures and are treated by Java as different constructors entirely. For example:
```java
public class Car {
private String name;
private String carType;
// Constructor.
public Car(){
this.name = "No Name";
this.carType = "No Type";
}
public Car(String model){
this.name = "Honda " + model;
}
public Car(String model, String carType){
this.name = model;
this.carType = carType;
}
public String getName(){
return this.name;
}
public String getCarType(){
return this.name;
}
public static void main(String args[]){
Car car = new Car("Civic");
System.out.println( car.getName() );
// Other Way To Initialize
Car car = new Car("Civic","Sedan");
System.out.println( car.getName() + " "+ car.getCarType() );
}
}
```
So, the only way to gain access to the instance is by using `Bank.getInstance()`. Such instances are called `Singleton` since you get exactly one instance (per VM to be precise) throughout the life of your application.
## Copy constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to-
1. Initialize an object from another of the same type.
2. Copy an object to pass it as an argument to a function.
3. Copy an object to return it from a function.
Here is a program that shows a simple use of copy constructor:
```Java
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// Copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
}
}
```
[run the full code](https://repl.it/MwnJ)
//## Constructor Chaining

View File

@ -0,0 +1,101 @@
---
title: Control Flow
---
# Control Flow
Control flow statements are exactly what the term means. They are statements that alter execution flow based on decisions, loops and branching so that the program can conditionally execute blocks of code.
Primarily, Java has the following constructs for flow control:
* `if`
```java
if( <expression that results in a boolean> ){
//code enters this block if the above expression is 'true'
}
```
* `if...else`
```java
if( <expression that results in a boolean> ){
//execute this block if the expression is 'true'
} else{
//execute this block if the expression is 'false'
}
```
* `switch`
Switch is an alternative for the `if...else` construct when there are multiple values and cases to check against.
```java
switch( <integer / String / Enum > ){
case <int/String/Enum>:
<statements>
break;
case <int/String/Enum>:
<statements>
break;
default:
<statements>
}
```
Note: The program flow `falls through` the next `case` if the `break` statement is missing. e.g. Let's say you say the standard 'Hello' to everyone at office, but you are extra nice to the girl who sits next to you and sound grumpy to your boss. The way to represent would be something like:
```java
switch(person){
case 'boss':
soundGrumpy();
break;
case 'neighbour':
soundExtraNice();
break;
case 'colleague':
soundNormal();
break;
default:
soundNormal();
}
```
Note: The `default` case runs when none of the `case` matches. Remember that when a case has no `break` statement, it `falls through` to the next case and will continue to the subsequent `cases` till a `break` is encountered. Because of this, make sure that each case has a `break` statement. The `default` case does not require a `break` statement.
* `nested statements`
Any of the previous control flows can be nested. Which means you can have nested `if`,`if..else`and`switch..case`statements. i.e., you can have any combination of these statements within the other and there is no limitation to the depth of`nesting`.
For example, let's consider the following scenario:
* If you have less than 25 bucks, you get yourself a cup of coffee.
* If you have more than 25 bucks but less than 60 bucks, you get yourself a decent meal.
* If you have more than 60 bucks but less than a 100, you get yourself a decent meal along with a glass of wine.
* However, when you have more than a 100 bucks, depending on who you are with, you either go for a candle lit dinner (with your wife) or you go to a sports bar (with your friends).
One of the ways to represent this will be:
```java
int cash = 150;
String company = "friends";
if( cash < 25 ){
getCoffee();
} else if( cash < 60 ){
getDecentMeal();
} else if( cash < 100 ){
getDecentMeal();
getGlassOfWine();
} else {
switch(company){
case "wife":
candleLitDinner();
break;
case "friends":
meetFriendsAtSportsBar();
break;
default:
getDecentMeal();
}
}
```
In this example, `meetFriendsAtSportsBar()` will be executed.
![:rocket:](https://forum.freecodecamp.org/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZi/1' target='_blank' rel='nofollow'>Run Code</a>

View File

@ -0,0 +1,16 @@
---
title: Data Abstraction
---
## Definition
As per dictionary, abstraction is the quality of dealing with ideas rather than events.
Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
## Resources
[Tutorials Point - Java Abstract classes and interfaces](https://www.tutorialspoint.com/java/java_abstraction.htm)
<br />
[Java Tutorials - Java Abstract methods and classes](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)

View File

@ -0,0 +1,199 @@
---
title: Data Types
---
# Data Types
Java is a strongly typed language. This means that, in Java, each data type has its own strict definition. There are no implicit data type conversions when any conflicts occur between the data types. Any change in data types should be explicitly declared by the programmer.
Java defines 8 primitive data types : `byte`, `short`, `int`, `long`, `char`, `float`, `double` and `boolean`.
They are divided into the following categories:
* Integers
* Floating Point Numbers
* Characters
* Boolean Type
The details of each of the data types is given below :
## Integers:
These are of four types: `byte`, `short`, `int`, `long`. It is important to note that these are signed positive and negative values. Signed integers are stored in a computer using [2's complement](http://www.ele.uri.edu/courses/ele447/proj_pages/divid/twos.html). It consist both negative and positive values but in different formats like `(-1 to -128)` or `(0 to +127)`. An unsigned integer can hold a larger positive value, and no negative value like `(0 to 255)`. Unlike C++ there is no unsigned integer in Java.
### byte:
Byte data type is an 8-bit signed two's complement integer.
Wrapper Class: Byte
Minimum value: -128 (-2^7)
Maximum value: 127 (2^7 -1)
Default value: 0
Example: byte a = 10 , byte b = -50;
### short:
Short data type is a 16-bit signed two's complement integer.
Wrapper Class: Short
Minimum value: -32,768 (-2^15)
Maximum value: 32,767 (2^15 -1)
Default value: 0.
Example: short s = 10, short r = -1000;
### int:
int data type is a 32-bit signed two's complement integer. It is generally used as the default data type for integral values unless there is a concern about memory.
Wrapper Class: Integer
Minimum value: (-2^31)
Maximum value: (2^31 -1)
The default value: 0.
Example: int a = 50000, int b = -20
### long:
Long data type is a 64-bit signed two's complement integer.
Wrapper Class: Long
Minimum value: (-2^63)
Maximum value: (2^63 -1)
Default value: 0L.
Example: long a = 100000L, long b = -600000L;
By default all integer type variable is "int". So long num=600851475143 will give an error.
But it can be specified as long by appending the suffix L (or l)
## Floating­ Point:
These are also called real numbers and are used for expressions involving fractional precision. These are of two types: `float`, `double`. Float is actually avoided in case of precise data such as currency or research data.
### float:
float data type is a single-precision 32-bit [IEEE 754 floating point](http://steve.hollasch.net/cgindex/coding/ieeefloat.html).
Wrapper Class: Float
Float is mainly used to save memory in large arrays of floating point numbers.
Default value: 0.0f.
Example: float f1 = 24.5f;
The default data type of floating-point number is double. So float f = 24.5 will introduce an error.
However, we can append the suffix F (or f) to designate the data type as float.
### double:
double data type is a double-precision 64-bit [IEEE 754 floating point](http://steve.hollasch.net/cgindex/coding/ieeefloat.html). This data type is generally the default choice. This data type should never be used for precise values, such as currency.
Wrapper Class: Double
This data type is generally used as the default data type for decimal values.
Default value: 0.0d.
Example: double d1 = 123.400778;
## Character:
We use this data type to store characters. This is not the same as the char in C/C++. Java uses a `UNICODE`, internationally accepted character set. Char in Java is 16­bits long while that in C/C++ is 8­bits.
Wrapper Class: Character
Minimum value: '\u0000' (or 0).
Maximum value: '\uffff' (or 65,535).
Default value: null ('\u0000').
Example: char letterA ='a';
## Boolean:
This is used for storing logical values. A boolean type can have a value of either true or false. This type is generally returned by relational operators.
There are only two possible values: true and false.
Wrapper Class: Boolean
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean b = true, boolean b1 = 1(this is not possible in java and give incompatible type error), boolean b2;
## Reference Data Types:
Apart from primitive data types there are reference variables created using constructors of different classes. Reference variables are used for any class as well as array, String, Scanner, Random, Die etc. Reference variables are initialised using the new keyword.
Example :
```java
public class Box{
int length, breadth, height;
public Box(){
length=5;
breadth=3;
height=2;
}
}
class demo{
public static void main(String args[]) {
Box box1 = new Box(); //box1 is the reference variable
char[] arr = new char[10]; //arr is the reference variable
}
}
```
## String:
String is not a primitive data type, but it lets you store multiple character data types in an array and has many methods that can be used. It is used quite commonly when the user types in data and you have to manipulate it.
In the example below, we try to remove all of the letters from the string and output it:
```java
String input = "My birthday is 10 January 1984 and my favorite number is 42";
String output = "";
for(int i=0;i<input.length();i++){
//if the character at index i on the string is a letter or a space, move on to the next index
if(Character.isLetter(input.charAt(i)) || input.charAt(i)==' '){
continue;
}
output = output + input.charAt(i); //the number is added onto the output
}
System.out.println(output);
```
Output:
```
10198442
```

View File

@ -0,0 +1,49 @@
---
title: Defining Attributes
---
## Defining Attributes
A class has attributes and methods. The attributes are basically variables within a class.
***Example:***
```java
public class Vehicle {
int maxSpeed;
int wheels;
String color;
void horn() {
System.out.println("Beep beep!");
}
}
```
`maxSpeed`, `wheels`, and `color` are all attributes of our Vehicle class and the `horn()` is the only method.
### Creating Objects
We can create multiple objects of our Vehicle class, and use the dot syntax to access their attributes and methods.
```java
class MyClass {
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
v1.color = "red";
v2.horn();
}
}
```
### Visibility modifiers
In the above Vehicle example, the attributes are declared without a visibility modifier (e.g. public, private, or protected). When no modifier is included in an attribute delaration, it defaults to something called "package private" which means that the attribute can be accessed directly using the "." dot notation by any other class within the same package.
'public' variables can be accessed from any class
'protected' variables can be accessed by any class within the same package, as well as by subclasses in any other packages having parent child relationship
'private' variables can only be accessed from within the class where they are declared
'package private' members can be accessed by the classes in the same package
'public', variables, methods, constructors and classes(only one) caan be declared as public.
'protected', variables, methods and constructors can be declared as private but not the classes and interfaces.
'private', variables, methods and constructors can be declared as private but not the classes and interfaces.
'default', variables, methods, constructors and classes can be of default type (declared by not writing anything).
#### public > protected > default > private (on the basis of ease of accessibility)
It's generally a good idea to make all of the attributes of a class private, and control access to them through the use of "getter" and "setter" methods.

View File

@ -0,0 +1,65 @@
---
title: Checking for Equality
---
# Checking for Equality
In Java, there are two ways to check if two variables are the "same": `==` and `.equals()`. These two methods do not work the same, however.
## The `==` Operator
The basic equality operation in Java, `==` as in `var1 == var2`, checks whether `var1` and `var2` point to the same *object reference*.
That is, if `var1` is the same *instance* of a class in memory as `var2`, then `var1 == var2` is true.
However, if `var1` and `var2` were created as two separate instances of a class (i.e. with the `new` keyword), then `var1 == var2` will be false. Even if both objects happen to contain the exact same properties and values, the `==` comparison would not pass because they are not pointing to the same object in memory.
For primitive variable types, such as `int` and `double`, the `==` operator can always be used to check for equality, as their values are stored directly with the variable (rather than as a reference to another slot in memory).
```java
int var1 = 1;
int var2 = 1;
System.out.println(var1 == var2) // true
MyObject obj1 = new MyObject();
MyObject obj2 = obj1;
MyObject obj3 = new MyObject();
System.out.println(obj1 == obj2) // true
System.out.println(obj1 == obj3) // false
System.out.println(obj2 == obj3) // false
```
## The `.equals()` Method
The built-in `Object` class in Java, which all other classes automatically extend, contains a number of helpful built-in methods. One such method is `equals()`, which takes another object as its argument and returns whether the two objects should be considered "equal" according to the relevant logic for that class.
The 'String' class is one of the most common examples of a class that overrides the 'equals()' method. When comparing two 'String's for equality, you need to use the 'equals()' method, as '==' won't work as you expect.
```java
String s1 = "Bob";
String s2 = "ob";
s2 = "B" + s2; //s2 now is also "Bob"
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //true
```
When you create a new class in Java, you will often want to override the `equals()` method in order to provide a more meaningful way to compare two objects of the same class. How this method is implemented is completely up to the developer's judgement.
For example, you may decide that two `Person`s should be considered "equal" if their `name` and `dateOfBirth` are the same. This logic would be implemented in your `Person` class's `equals()` method:
```java
public class Person {
public String name;
public Date dateOfBirth;
public boolean equals(Person person) {
return this.name.equals(person.name) && this.dateOfBirth.equals(person.dateOfBirth);
}
}
```
Most of the built-in classes in Java, as well as classes provided by popular libraries, will implement the `equals()` method in a meaningful way.
For example, the `java.util.Set` interface specifies that a `Set`'s `equals()` method will return true if "the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set".
However, if a class does not override the default `equals()` implementation, the default implementation will apply, which simply uses the `==` operator to compare the two objects.

View File

@ -0,0 +1,58 @@
---
title: Final
---
## final
You use the `final` keyword to mark a variable constant, so that it can be assigned only once. So you must initialize a final variable with a value. If its not initialized (when declared, inside Constructor or inside static blocks), compile time error will occur.
***Example:***
```java
class MyClass {
public static final double PI = 3.14;
public static void main(String[] args){
System.out.println(PI);
}
}
```
PI is now a constant. Any attempt to assign it a value will cause an error.
-----------------------------------------------------------------------------------------
If you make any method as final, you cannot override it.
```java
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
```
Output wil be -
Output:Compile Time Error
---------------------------------------------------------------------------------------
If you make any class as final, you cannot extend it.
```java
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
```
Output will be-
Output:Compile Time Error

View File

@ -0,0 +1,33 @@
---
title: Finally
---
## finally
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
***Example:***
```java
try {
// Normal execution path
throw new EmptyStackException();
} catch (ExampleException ee) {
// deal with the ExampleException
} finally {
// This optional section is executed upon termination of any of the try or catch blocks above,
// except when System.exit() is called in "try" or "catch" blocks;
}
```
The finally block does not need the catch block to precede it.There can also be a finally block without the catch block.
***Example:***
```java
try {
//Normal code
System.out.println("hello world!");
} finally {
System.out.println("In finally block");
}
```
The above code works fine even though the catch statement is not used.

View File

@ -0,0 +1,91 @@
---
title: Garbage Collection
---
# Garbage Collection in Java
In languages like C/C++, it is the duty of the programmer to create and destroy objects. But if the programmer does not performs his duty, sufficient memory may not be available for the creation of a new object and the program may terminate causing **OutOfMemoryErrors**.
Java relieves the programmer from memory management task and itself reclaims the memory occupied by the objects which are no longer in use. Garbage Collection in java is carried out by a daemon thread called **Garbage Collector**. **JVM(Java Virtual Machine)** invokes it when there is lack of memory(heap) for new objects.
## When an object becomes eligible for Garbage Collection?
* An object becomes eligible for Garbage Collection if it is not reachable from any live threads or any static references.
* An object becomes eligible for Garbage Collection if its all references are null.
```java
Integer n = new Integer();
n = null; //the Integer object is no longer accessible
```
* Cyclic dependencies are not counted as reference so if Object X has reference of Object Y and Object Y has reference of Object X and they dont have any other live reference then both Objects X and Y will be eligible for Garbage Collection.
## How to manually make an object eligible for Garbage Collection?
* Even though it is not the task of the programmer to destroy the objects, it is a good programming practice to make an object unreachable(thus eligible for GC) after it is used.
* There are generally four different ways to make an object eligible for garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. Object is created inside a block and reference goes out of scope once control exit that block.
4. [Island of Isolation](http://www.geeksforgeeks.org/island-of-isolation-in-java/)
## Ways of requesting JVM to run Garbage Collector<sup>1</sup>
* Though making an object eligible for Garbage Collection, it depends on sole discretion of JVM to run the Garbage Collector to destroy it.
* We can also request JVM to run Garbage Collector. There are two ways to do it :
1. Using _**System.gc()**_ method : System class contain static method gc() for requesting JVM to run Garbage Collector.
2. Using _**Runtime.getRuntime().gc()**_ method : Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.
```java
// Java program to request
// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test test1 = new Test();
Test test2 = new Test();
// Nullifying the reference variable
test1 = null;
// requesting JVM for running Garbage Collector
System.gc();
// Nullifying the reference variable
test2 = null;
// requesting JVM for running Garbage Collector
Runtime.getRuntime().gc();
}
@Override
// finalize method is a method which is called on object once
// before garbage collector is destroying it and reclaiming its memory
protected void finalize() throws Throwable
{
System.out.println("Garbage collector is called");
System.out.println("Object garbage collected : " + this);
}
}
```
```java
OUTPUT -
Garbage collector called
Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8
```
Note :
1. There is no guarantee that any one of above two methods will definitely run Garbage Collector.
2. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()
## Object Finalization
* Objects have resources associtated with them. It is their responsibility to free the resources.
* The finalize(), is declared in Object class and is called by garbage collector once, just before destroying the object. An object can take any last action using this method jst before its area is reclaimed by the garbage collector.
* finalize() method is present in Object class with following prototype.
```java
protected void finalize() throws Throwable
```
## NOTE<sup>1</sup> :
1. The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one of the module of JVM.
2. Object class finalize() method has empty implementation, thus it is recommended to override finalize() method to dispose of system resources or to perform other cleanup.
3. The finalize() method is never invoked more than once for any given object.
4. If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.
### SOURCES
1. [geeksforgeeks.](http://www.geeksforgeeks.org/garbage-collection-java/)Accessed: October 24,2017.

View File

@ -0,0 +1,81 @@
---
title: Generics
---
# Generics
Java Generics is a way to conviently use collections and classes for specific data types with out having to cast data back into the original data type. This prevents a lot of headache in the form of compile time and run time bugs.
Simply put Generics lets you explicitly say that, for example an ArrayList object holds Integers so that when you call the get method you do not need to convert between Object and Integer. Below is an example of how you would have used an ArrayList prior to Generics.
```java
import java.util.ArrayList;
public class Example {
private ArrayList classNames;
public Example() {
classNames = new ArrayList();
}
public void addName(String name) {
classNames.add(name);
}
public String getNameAtIndex(int index) {
return (String) classNames.get(index);
}
}
```
The main problem with the above is if somehow an Object not of type String got added to the ArrayList then the `getNameAtIndex(int index)` method would result in a runtime error. To solve this we use Generics.
The syntax for Generics is very simple. Below is an example of instantiating an ArrayList.
```java
import java.util.ArrayList;
public class Example {
private ArrayList<String> classNames;
public Example() {
classNames = new ArrayList<String>();
}
public void addName(String name) {
classNames.add(name);
}
public String getNameAtIndex(int index) {
return classNames.get(index);
}
}
```
The syntax to create your own Generic class would be as follows.
```java
import java.util.ArrayList;
public class Example <T> {
private ArrayList<T> classNames;
public Example() {
classNames = new ArrayList<T>();
}
public void addName(T name) {
classNames.add(name);
}
public T getNameAtIndex(int index) {
return classNames.get(index);
}
}
```
Note that inside the angular brackets when naming the class, you can ensure that the Generic type is something that
you want. For example, if you wanted to make sure the type can be read as a form of String, you would go `<T extends String>`.
Note that the letter `T` is a placeholder, you could make that anything you like, as long as you use the same one
throughout the class.

View File

@ -0,0 +1,65 @@
---
title: Getters & Setters
---
# Getters & Setters
Getters and Setters are used to effectively protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Getters and setters are also known as accessors and mutators, respectively.
By convention, getters start with get, followed by the variable name, with the first letter of the variable name capitalized. Setters start with set, followed by the variable name, with the first letter of the variable name capitalized.
***Example:***
```java
public class Vehicle {
private String color;
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
```
The getter method returns the value of the attribute.
The setter method takes a parameter and assigns it to the attribute.
Once the getter and setter have been defined, we use it in our main:
```java
public stativ void main(String[] args) {
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
// Outputs "Red"
```
****************
Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.
## Why getter and setter?
By using getter and setter, the programmer can control how their important variables are accessed and updated, such as changing value of a variable within a specified range. Consider the following code of a setter method:
```java
public void setNumber(int num) {
if (num < 10 || num > 100) {
throw new IllegalArgumentException();
}
this.number = num;
}
```
This ensures the value of number is always set between 10 and 100. If the programmer allows the variable number to be updated directly, the caller can set any arbitrary value to it:
```java
obj.number = 3;
```
This violates the constraint for values ranging from 10 to 100 for that variable. Since we don't expect that to happen, hiding the variable number as private and using a setter prevents it.
On the other hand, a getter method is the only way for the outside world to read the variables value:
```java
public int getNumber() {
return this.number;
}
```

122
guide/english/java/index.md Normal file
View File

@ -0,0 +1,122 @@
---
title: Java
---
**What is Java?**
<a href='https://www.oracle.com/java/index.html' target='_blank' rel='nofollow'>Java</a> is a programming language developed by <a href='https://en.wikipedia.org/wiki/Sun_Microsystems' target='_blank' rel='nofollow'>Sun Microsystems</a> in 1995, which got later acquired by <a href='http://www.oracle.com/index.html' target='_blank' rel='nofollow'>Oracle</a>. It's now a full platform with lots of standard APIs, open source APIs, tools, huge developer community and is used to build the most trusted enterprise solutions by big and small companies alike. <a href='https://www.android.com/' target='_blank' rel='nofollow'>Android</a> application development is done fully with Java and its ecosystem. To know more about Java, read <a href='https://java.com/en/download/faq/whatis_java.xml' target='_blank' rel='nofollow'>this</a> and <a href='http://tutorials.jenkov.com/java/what-is-java.html' target='_blank' rel='nofollow'>this</a>.
## Version
The latest version is <a href='http://www.oracle.com/technetwork/java/javase/overview' target='_blank' rel='nofollow'> Java 11</a>, which was released in 2018 with <a href='https://www.oracle.com/technetwork/java/javase/11-relnote-issues-5012449.html' target='_blank' rel='nofollow'>various improvements</a> over the previous version, Java 10. But for all intents and purposes, we will use Java 8 in this wiki for all tutorials.
Java is also divided into several "Editions" :
* <a href='http://www.oracle.com/technetwork/java/javase/overview/index.html' target='_blank' rel='nofollow'>SE</a> - Standard Edition - for desktop and standalone server applications
* <a href='http://www.oracle.com/technetwork/java/javaee/overview/index.html' target='_blank' rel='nofollow'>EE</a> - Enterprise Edition - for developing and executing Java components that run embedded in a Java server
* <a href='http://www.oracle.com/technetwork/java/embedded/javame/overview/index.html' target='_blank' rel='nofollow'>ME</a> - Micro Edition - for developing and executing Java applications on mobile phones and embedded devices
## Installation : JDK or JRE ?
Download the latest Java binaries from the <a href='http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html' target='_blank' rel='nofollow'>official website</a>. Here you may face a question, which one to download, JDK or JRE? JRE stands for Java Runtime Environment, which is the platform dependent Java Virtual Machine to run Java codes, and JDK stands for Java Development Kit, which consists of most of the development tools, most importantly the compiler `javac`, and also the JRE. So, for an average user JRE would be sufficient, but since we would be developing with Java, we would download the JDK.
## Platform specific installation instructions
### Windows
* Download the relevant <a href='https://en.wikipedia.org/wiki/Windows_Installer' target='_blank' rel='nofollow'>.msi</a> file (x86 / i586 for 32bits, x64 for 64bits)
* Run the .msi file. Its a self extracting executable file which will install Java in your system!
### Linux
* Download the relevant <a href='http://www.cyberciti.biz/faq/linux-unix-bsd-extract-targz-file/' target='_blank' rel='nofollow'>tar.gz</a> file for your system and install :
`bash
$ tar zxvf jdk-8uversion-linux-x64.tar.gz`
* <a href='https://en.wikipedia.org/wiki/List_of_Linux_distributions#RPM-based' target='_blank' rel='nofollow'>RPM based Linux platforms</a> download the relevant <a href='https://en.wikipedia.org/wiki/RPM_Package_Manager' target='_blank' rel='nofollow'>.rpm</a> file and install :
`bash
$ rpm -ivh jdk-8uversion-linux-x64.rpm`
* Users have the choice to install an open source version of Java, OpenJDK or the Oracle JDK. While OpenJDK is in active development and in sync with Oracle JDK, they just differ in <a href='http://openjdk.java.net/faq/' target='_blank' rel='nofollow'>licensing</a> stuff. However few developers complain of the stability of Open JDK. Instructions for **Ubuntu** :
Open JDK installation :
`bash
sudo apt-get install openjdk-8-jdk`
Oracle JDK installation :
`bash
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer`
### Mac
* Either download Mac OSX .dmg executable from Oracle Downloads
* Or use <a href='http://brew.sh/' target='_blank' rel='nofollow'>Homebrew</a> to <a href='http://stackoverflow.com/a/28635465/2861269' target='_blank' rel='nofollow'>install</a> :
```bash
brew tap caskroom/cask
brew install brew-cask
brew cask install java
```
### Verify Installation
Verify Java has been properly installed in your system by opening Command Prompt (Windows) / Windows Powershell / Terminal (Mac OS and *Unix) and checking the versions of Java runtime and compiler :
$ java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
$ javac -version
javac 1.8.0_66
**Tip** : If you get an error such as "Command Not Found" on either `java` or `javac` or both, dont panic, its just your system PATH is not properly set. For Windows, see <a href='http://stackoverflow.com/questions/15796855/java-is-not-recognized-as-an-internal-or-external-command' target='_blank' rel='nofollow'>this StackOverflow answer</a> or <a href='http://javaandme.com/' target='_blank' rel='nofollow'>this article</a> on how to do it. Also there are guides for <a href='http://stackoverflow.com/questions/9612941/how-to-set-java-environment-path-in-ubuntu' target='_blank' rel='nofollow'>Ubuntu</a> and <a href='http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/' target='_blank' rel='nofollow'>Mac</a> as well. If you still can't figure it out, dont worry, just ask us in our <a href='https://gitter.im/FreeCodeCamp/java' target='_blank' rel='nofollow'>Gitter room</a>!
## JVM
Ok now since we are done with the installations, let's begin to understand first the nitty gritty of the Java ecosystem. Java is an <a href='http://stackoverflow.com/questions/1326071/is-java-a-compiled-or-an-interpreted-programming-language' target='_blank' rel='nofollow'>interpreted and compiled</a> language, that is the code we write gets compiled to bytecode and interpreted to run . We write the code in .java files, Java compiles them into <a href='https://en.wikipedia.org/wiki/Java_bytecode' target='_blank' rel='nofollow'>bytecodes</a> which are run on a Java Virtual Machine or JVM for execution. These bytecodes typically has a .class extension.
Java is a pretty secure language as it doesn't let your program run directly on the machine. Instead, your program runs on a Virtual Machine called JVM. This Virtual Machine exposes several APIs for low level machine interactions you can make, but other than that you cannot play with machine instructions explicitely. This adds a huge bonus of security.
Also, once your bytecode is compiled it can run on any Java VM. This Virtual Machine is machine dependent, i.e it has different implementations for Windows, Linux and Mac. But your program is guranteed to run in any system thanks to this VM. This philosophy is called <a href='https://en.wikipedia.org/wiki/Write_once,_run_anywhere' target='_blank' rel='nofollow'>"Write Once, Run Anywhere"</a>.
## Hello World!
Let's write a sample Hello World application. Open any editor / IDE of choice and create a file `HelloWorld.java`.
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
**N.B.** Keep in mind in Java file name should be the **exact same name of the public class** in order to compile!
Now open the terminal / Command Prompt. Change your current directory in the terminal / Command Prompt to the directory where your file is located. And compile the file :
$ javac HelloWorld.java
Now run the file using `java` command!
$ java HelloWorld
Hello, World
Congrats! Your first Java program has run successfully. Here we are just printing a string passing it to the API `System.out.println`. We will cover all the concepts in the code, but you are welcome to take a <a href='https://docs.oracle.com/javase/tutorial/getStarted/application/' target='_blank' rel='nofollow'>closer look</a>! If you have any doubt or need additional help, feel free to contact us anytime in our <a href='https://gitter.im/FreeCodeCamp/java' target='_blank' rel='nofollow'>Gitter Chatroom</a>!
## Documentation
Java is heavily <a href='https://docs.oracle.com/javase/8/docs/' target='_blank' rel='nofollow'>documented</a>, as it supports huge amounts of API's. If you are using any major IDE such as Eclipse or IntelliJ IDEA, you would find the Java Documentation included within.
Also, here is a list of free IDEs for Java coding:
* <a href='https://netbeans.org/' target='_blank' rel='nofollow'>NetBeans</a>
* <a href='https://eclipse.org/' target='_blank' rel='nofollow'>Eclipse</a>
* <a href='https://www.jetbrains.com/idea/features/' target='_blank' rel='nofollow'>IntelliJ IDEA</a>
* <a href='https://developer.android.com/studio/index.html' target='_blank' rel='nofollow'>Android Studio</a>
* <a href='https://www.bluej.org/' target='_blank' rel='nofollow'>BlueJ</a>
* <a href='http://www.jedit.org/' target='_blank' rel='nofollow'>jEdit</a>
* <a href='http://www.oracle.com/technetwork/developer-tools/jdev/overview/index-094652.html' target='_blank' rel='nofollow'>Oracle JDeveloper</a>

View File

@ -0,0 +1,52 @@
---
title: Inheritance Basics
---
# Inheritance Basics
So great you have successfully created a Car class. But, wait, aren't Tesla cars supposed to be electric variants? I want an Electric car class, but it also should have the properties of the original `Car` class.
Solution : **Inheritance**. Java provides a neat way to "inherit" parent properties :
```java
public class Car {
private String name;
private String manufacturerName;
public Car(String name, String man) {
this.name = name;
this.manufacturerName = man;
}
// Getter method
public String getName() {
return name;
}
// Getter method
public String getManufacturerName() {
return manufacturerName;
}
}
public class ElectricCar extends Car {
public ElectricCar(String name, String man) {
super(name, man);
}
public void charge() {
System.out.println("Charging ...");
}
}
ElectricCar modelS = new ElectricCar("Model S","Tesla");
// prints Tesla
System.out.println(modelS.getManufacturerName());
// prints Charging ...
modelS.charge();
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZY/0' target='_blank' rel='nofollow'>Run Code</a>
See here that the class `ElectricCar` inherits or `extends` the public methods from `Car` class, as well as has its own methods and properties. Cool way to pass on information!
Also notice the usage of <a href='https://docs.oracle.com/javase/tutorial/java/IandI/super.html' target='_blank' rel='nofollow'>super</a> keyword here. Since our `Car` class had a constructor, so we have to initialize that constructor from the child class as well. We do that using the `super` keyword. Read more about <a>Inheritance here</a>.

View File

@ -0,0 +1,191 @@
---
title: Inheritance
---
# Inheritance
Java inheritance refers to the ability of a Java Class to `inherit` the properties from some other Class. Think of it like a child inheriting properties from its parents, the concept is very similar to that. In Java lingo, it is also called _extend_-ing a class. Some simple things to remember :
* The Class that extends or inherits is called a **subclass**
* The Class that is being extended or inherited is called a **superclass**
Thus, inheritance gives Java the cool capability of _re-using_ code, or sharing code between classes!
Let's describe it with the classic example of a `Vehicle` class and a `Car` class :
```java
public class Vehicle {
public void start() {
// starting the engine
}
public void stop() {
// stopping the engine
}
}
public class Car extends Vehicle {
int numberOfSeats = 4;
public int getNumberOfSeats() {
return numberOfSeats;
}
}
```
Here, we can see the `Car` class inheriting the properties of the `Vehicle` class. So, we don't have to write the same code for the methods `start()` and `stop()` for `Car` as well, as those properties are available from its parent or superclass. Therefore, objects created from the `Car` class will _also_ have those properties!
```java
Car tesla = new Car();
tesla.start();
tesla.stop();
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJXz/0' target='_blank' rel='nofollow'>Run Code</a>
But, does the parent class have the methods of the child? No, it doesn't.
Therefore, whenever you need to share some common piece of code between multiple classes, it is always good to have a parent class, and then extend that class whenever needed! Reduces the number of lines of code, makes code modular, and simplifies testing.
## What can be inherited ?
* All `protected` and `public` members (fields, methods, and nested classes) from parent, regardless what package the sub-class is in. If a sub-class is in the same package as its parent, it will also inherit `package-private` members from parent.
## What cannot be inherited ?
* `private` fields and methods
* Constructors. Although, the subclass constructor _has_ to call the superclass constructor if its defined (More on that later!)
* Multiple classes. Java supports only **single inheritance**, that is, you can only inherit one class at a time.
* Fields. Individual fields of a class cannot be overriden by the subclass.
## Type Casting & Reference
In Java, it is possible to reference a subclass as an _instance_ of its superclass. It is called _Polymorphism_ in Object Oriented Programming (OOP), the ability for an object to take on many forms. For example, the `Car` class object can be referenced as a `Vehicle` class instance like this :
```java
Vehicle car = new Car();
```
Although, the opposite is not possible :
```java
Car car = new Vehicle(); // ERROR
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJYB/0' target='_blank' rel='nofollow'>Run Code</a>
Since you can reference a Java subclass as a superclass instance, you can easily cast an instance of a subclass object to a superclass instance. It is possible to cast a superclass object into a subclass type, but _only if the object is really an instance of the subclass_. So keep this in mind :
```java
Car car = new Car();
Vehicle vehicle = car; // upcasting
Car car2 = (Car)vechile; //downcasting
Bike bike = new Bike(); // say Bike is also a subclass of Vehicle
Vehicle v = bike; // upcasting, no problem here.
Car car3 = (Car)bike; // Compilation Error : as bike is NOT a instance of Car
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJYM/0' target='_blank' rel='nofollow'>Run Code</a>
Now you know how to share code through a parent-child relationship. But, what if, you do not like the implementation of a particular method in the child class and want to write a new one for it? What do you do then?
## Override it!
Java lets you _override_ or redefine the methods defined in the superclass. For example, your `Car` class has a different implementation of `start()` than the parent `Vehicle`, so you do this :
```java
public class Vehicle {
public void start() {
System.out.println("Vehicle start code");
}
}
public class Car extends Vehicle {
public void start() {
System.out.println("Car start code");
}
}
Car car = new Car();
car.start(); // "Car start code"
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJYZ/1' target='_blank' rel='nofollow'>Run Code</a>
So, it's pretty simple to override methods in the subclass. Although, there is a _catch_. Only that superclass method with the _exact same method signature_ as the subclass method will be overriden. That means the subclass method definition must have the exact same name, same number and type of parameters, and in the exact same sequence. Thus, `public void start(String key)` would not override `public void start()`.
**Notes** :
* You cannot override private methods of the superclass. (Quite obvious, isn't it?)
* What if the method of superclass which you are overriding in the subclass suddenly gets obliterated or methods changed? It would fail in runtime! So Java provides you a nifty annotation `@Override` which you can place over the subclass method, which will warn the compiler of those incidents!
Annotations in Java is a good coding practice, but they are not a necessity. The compiler is smart enough to figure out overriding on its own though. Unlike other OOP languages, Annotations in Java it doesn't necessarily modify the method or add extra functionality.
## How to call super class methods?
Funny you ask about it! Just use the keyword `super` :
```java
public class Vehicle() {
public void start() {
System.out.println("Vehicle start code");
}
}
public class Car extends Vehicle {
public void run() {
super.start();
}
}
Car car = new Car();
car.run(); // "Vehicle start code"
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJY4/0' target='_blank' rel='nofollow'>Run Code</a>
**N.B.** : Although you can call the parent method by using a `super` call, you cannot go up the inheritance hierarchy with chained `super` calls.
## How to know the type of a class?
Using the `instanceof` keyword. Having lots of classes and subclasses it would be a little confusing to know which class is a subclass of which one in runtime. So, we can use `instanceof` to determine whether an object is an instance of a class, an instance of a subclass, or an instance of an interface.
```java
Car car = new Car();
boolean flag = car instanceof Vehicle; // true in this case!
```
## Constructors & Inheritance
As mentioned earlier, constructors cannot be directly inherited by a subclass. Although, a subclass is _required_ to call its parent's constructor as the <a href='http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor' target='_blank' rel='nofollow'>first operation</a> in its own constructor. How? You guessed it, using `super` :
```java
public class Vehicle {
public Vehicle() {
// constructor
}
public void start() {
System.out.println("Vehicle start code");
}
}
public class Car extends Vehicle {
public Car() {
super();
}
public void run() {
super.start();
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJY8/0' target='_blank' rel='nofollow'>Run Code</a>
Remember, if the superclass does not have any constructors defined, you don't have to call it explicitely in the subclass. Java handles that internally for you! Invocation to `super` constructor is done in the case when the super class is to be called with any other constructor other than the _default constructor_.
If no other constructors are defined, then Java invokes the default super class constructor (_even if not defined explicitly_).
Congrats, now you know all about Inheritance! Read more about advanced ways to inherit things in Abstract Classes and [Interfaces](//forum.freecodecamp.com/t/java-docs-interfaces)!

View File

@ -0,0 +1,14 @@
---
title: instanceof Operator
---
# `instanceof` operator
The `instanceof` operator allows you to check the validity of a `IS A` relationship. If at any point of time, we are not sure about this and we want to validate this at runtime, we can do the following:
```java
//assuming vehicle is an instance of Class `Car` the expression inside the 'if' will return true
if(vehicle instanceof Car){
//do something if vehicle is a Car
}
```
**Note**: If you apply the instanceof operator with any variable that has null value, it returns false.

View File

@ -0,0 +1,264 @@
---
title: Interfaces
---
# Interfaces
Interface in Java is a bit like the Class, but with a significant difference : an `interface` can _only_ have method signatures, fields and default methods. Since Java 8, you can also create [default methods](https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). In the next block you can see an example of interface :
```java
public interface Vehicle {
public String licensePlate = "";
public float maxVel
public void start();
public void stop();
default void blowHorn(){
System.out.println("Blowing horn");
}
}
```
The interface above contains two fields, two methods, and a default method. Alone, it is not of much use, but they are usually used along with Classes. How? Simple, you have to make sure some class `implements` it.
```java
public class Car implements Vehicle {
public void start() {
System.out.println("starting engine...");
}
public void stop() {
System.out.println("stopping engine...");
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CItd/0' target='_blank' rel='nofollow'>Run Code</a>
Now, there is a **ground rule** : The Class must implement **all** of the methods in the Interface. The methods must have _the exact same_ signature (name, parameters and exceptions) as described in the interface. The class _does not_ need to declare the fields though, only the methods.
## Instances of an Interface
Once you create a Java Class which `implements` any Interface, the object instance can be referenced as an instance of the Interface. This concept is similar to that of Inheritance instantiation.
```java
// following our previous example
Vehicle tesla = new Car();
tesla.start(); // starting engine ...
```
An Interface **can not** contain a constructor methods,therefore,you **can not** create an instance of an Interface itself. You must create an instance of some class implementing an Interface to reference it. Think of interfaces as a blank contract form, or a template.
What can you do with this feature? Polymorphism! You can use only interfaces to refer to object instances!
```java
class Truck implements Vehicle {
public void start() {
System.out.println("starting truck engine...");
}
public void stop() {
System.out.println("stopping truck engine...");
}
}
class Starter {
// static method, can be called without instantiating the class
public static void startEngine(Vehicle vehicle) {
vehicle.start();
}
}
Vehicle tesla = new Car();
Vehicle tata = new Truck();
Starter.startEngine(tesla); // starting engine ...
Starter.startEngine(tata); // starting truck engine ...
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CItm/0' target='_blank' rel='nofollow'>Run Code</a>
## But how about multiple interfaces?
Yes, you can implement multiple Interfaces in a single class. While in [Inheritance](//forum.freecodecamp.com/t/java-docs-inheritance) within Classes you were restricted to inherit only one class, here you can extend any number of interfaces. But do not forget to implement _all_ of the methods of all the Interfaces, otherwise compilation will fail!
```java
public interface GPS {
public void getCoordinates();
}
public interface Radio {
public void startRadio();
public void stopRadio();
}
public class Smartphone implements GPS,Radio {
public void getCoordinates() {
// return some coordinates
}
public void startRadio() {
// start Radio
}
public void stopRadio() {
// stop Radio
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CIto/0' target='_blank' rel='nofollow'>Run Code</a>
## Some features of Interfaces
* You can place variables within an Interface, although it won't be a sensible decision as Classes are not bound to have the same variable. In short, avoid placing variables!
* All variables and methods in an Interface are public, even if you leave out the `public` keyword.
* An Interface cannot specify the implementation of a particular method. Its up to the Classes to do it. Although there has been a recent exception (see below).
* If a Class implements multiple Interfaces, then there is a remote chance of method signature overlap. Since Java does not allow multiple methods of the exact same signature, this can lead to problems. See <a href='http://stackoverflow.com/questions/2598009/method-name-collision-in-interface-implementation-java' target='_blank' rel='nofollow'>this question</a> for more info.
## Interface Default Methods
Before Java 8, we had no way to direct an Interface to have a particular method implementation. This lead to lot of confusion and code breaks if an Interface definition is suddenly changed.
Suppose, you wrote an open source library, which contains an Interface. Say, your clients, i.e. practically all developers around the world, are using it heavily and are happy. Now you have had to upgrade the library by adding a new method definition to the Interface to support a new feature. But that would break _all_ builds since all Classes implementing that Interface have to change now. What a catastrophe!
Thankfully, Java 8 now provides us `default` methods for Interfaces. A `default` method _can_ contain its own implementation _directly_ within the Interface! So, if a Class does not implement a default method, the compiler will take the implementation mentioned within the Interface. Nice, isn't it? So in your library, you may add any number of default methods in interfaces without the fear of breaking anything!
```java
public interface GPS {
public void getCoordinates();
default public void getRoughCoordinates() {
// implementation to return coordinates from rough sources
// such as wifi & mobile
System.out.println("Fetching rough coordinates...");
}
}
public interface Radio {
public void startRadio();
public void stopRadio();
}
public class Smartphone implements GPS,Radio {
public void getCoordinates() {
// return some coordinates
}
public void startRadio() {
// start Radio
}
public void stopRadio() {
// stop Radio
}
// no implementation of getRoughCoordinates()
}
Smartphone motoG = new Smartphone();
motog.getRoughCoordinates(); // Fetching rough coordinates...
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CItp/0' target='_blank' rel='nofollow'>Run Code</a>
### But, what happens if two interfaces have the same method signature?
Awesome question. In that case, if you do not provide the implementation in the Class, poor compiler will get confused and simply fail! You have to provide a default method implemention within the Class also. There is also a nifty way using `super` to call which implementation you like :
```java
public interface Radio {
// public void startRadio();
// public void stopRadio();
default public void next() {
System.out.println("Next from Radio");
}
}
public interface MusicPlayer {
// public void start();
// public void pause();
// public void stop();
default public void next() {
System.out.println("Next from MusicPlayer");
}
}
public class Smartphone implements Radio, MusicPlayer {
public void next() {
// Suppose you want to call MusicPlayer next
MusicPlayer.super.next();
}
}
Smartphone motoG = new Smartphone();
motoG.next(); // Next from MusicPlayer
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CIts/0' target='_blank' rel='nofollow'>Run Code</a>
## Static Methods in Interfaces
Also new to Java 8 is the ability to add static methods to interfaces. Static methods in interfaces are almost identical to static methods in concrete classes. The only big difference is that `static` methods are not inherited in the classes that implement the interface. This means that the interface is referenced when calling the static method not the class that implements it.
```java
interface MusicPlayer {
public static void commercial(String sponsor) {
System.out.println("Now for a message brought to you by " + sponsor);
}
public void play();
}
class Smartphone implements MusicPlayer {
public void play() {
System.out.println("Playing from smartphone");
}
}
class Main {
public static void main(String[] args) {
Smartphone motoG = new Smartphone();
MusicPlayer.commercial("Motorola"); // Called on interface not on implementing class
// motoG.commercial("Motorola"); // This would cause a compilation error
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CIts/9' target='_blank' rel='nofollow'>Run Code</a>
## Inheriting an Interface
It is also possible in Java for an Interface to _inherit_ another Interface, by using, you guessed it, `extends` keyword :
```java
public interface Player {
public void start();
public void pause();
public void stop();
}
public interface MusicPlayer extends Player {
default public void next() {
System.out.println("Next from MusicPlayer");
}
}
```
That means, the Class implementing `MusicPlayer` Interface has to implement _all_ methods of `MusicPlayer` as well as `Player` :
```java
public class SmartPhone implements MusicPlayer {
public void start() {
System.out.println("start");
}
public void stop() {
System.out.println("stop");
}
public void pause() {
System.out.println("pause");
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CIty/0' target='_blank' rel='nofollow'>Run Code</a>
Whoops, did I forget `next()` ? See, since it was a `default` method, I didn't had to provide an implementation at all. (Won't work for JDK < 8)
So, now you have a good grasp of Interfaces! Go learn about Abstract Classes to know how Java gives you yet another way to define contracts.

View File

@ -0,0 +1,13 @@
---
title: Java Bean
---
## Java Bean
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,34 @@
---
title: JavaFX
---
## Introduction
JavaFX is a graphics framework created by Sun Microsystems used for developing rich desktop and Internet applications. JavaFX was created to replace the much older Swing and Abstract Window Toolkit (AWT) libraries and serve as the Java language's standard graphics API for Java Standard Edition.
## Development Tools
### Gulon SceneBuilder
Gulon Scene Builder is an application used for user interface (UI) design in JavaFX. The application uses drag-and-drop for rapid UI design that allows you to visualize the interface you are creating while designing it.
#### Screeenshots:
![Scene Builder UI](https://i.imgur.com/3d9SqBR.png)
### FXML
FXML is an XML-based markup language used for defining structures in JavaFX. The FXML document lays out the various objects in the class in a tree similar to tag nesting in XML documents.
#### Example:
```XML
<HBox spacing="10" alignment="bottom_right" > // Creates an HBox Object
<Button text="Sign In"/> // Nested inside the HBox is a Button object with the text 'Sign In'
</HBox>
```
### Gulon Scenic View
Scenic View is an application designed to show the current state of your JavaFX application. Scenic View enables you to debug the graphic elements in your application in real time, including changing various values.
### References:
[FXML Documentation](https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html)
[Scene Builder Tutorial](https://docs.oracle.com/javase/8/scene-builder-2/get-started-tutorial/overview.htm#JSBGS164)
[Official JavaFX Documentation](https://docs.oracle.com/javase/8/javase-clienttechnologies.htm)
[Official Scenic View Page](http://fxexperience.com/scenic-view/)

View File

@ -0,0 +1,78 @@
---
title: Lambda Expressions
---
## Lambda Expressions
Lambda expressions were introduced in Java 8 and it marks Java's foray to the functional programming paradigm. It helps produce readable and concise code and can tremendously simplify your Java applications.
Lambda functions are essentially functions — independent units of code that you can use anywhere you would normally use an object, like passing an argument to a method. In this case, instead of creating a class and then creating an object from the class, or directly using an anonymous class, you write your lambda expression and just pass it to the method instead of a class object.
A lambda expression is composed of three parts — function parameters, the `->` symbol, and a function body.
- The first part, function parameters, indicates what arguments you expect your lambda function to take. For instance, if you are iterating over a list of `Person` objects, you can write the function parameter of the lambda expression as `(Person p)`. If you expect to get two (or more) `Person` objects as arguments, you would separate them with a comma, `(Person p1, Person p2)`. If you don't expect any arguments, you simply use empty parentheses `()`. The rule is that you can omit the parentheses in case your Lambda expression accepts only 1 argument. In all other cases, the parentheses are mandatory.
- Function parameters are followed by the `->` symbol (dash followed by a greater-than symbol).
- The third component of a lambda expression is a function body, which performs the actual work. You write the function body within curly braces `{}`. However, if your function body is just one line, you can omit the `{}` and write it directly after the `->`, like so:
```java
Person p -> System.out.println(p.getName());
```
This is a complete lambda expression. It accepts a `Person` object as argument and prints its name using the `getName()` getter.
### Stream API
The `Stream` API was also introduced in Java 8, and can be used to allow chaining of sequential and aggregate operations. Stream operations are either intermediate or terminal in nature.
Normally, the Stream API is used in conjunction with lambda expressions to produce concise code.
In this small example you can see that one of the utilities of a stream is to receive a certain property of all objects in a list and return it in another list using intermediate and terminal operations.
Assume you have a `Student` class like so:
```java
public class Student {
int studentId;
String studentName;
public String getStudentName() {
return this.studentName;
}
public int getStudentId() {
return this.studentId;
}
// setters
}
```
Now assume you're writing a method which has a list of all the students and you want to get a list of all the student names, which may look something like this:
```java
List<Student> students = /* some list of student objects */;
List<String> studentNames = new ArrayList<>();
for(Student student: students) {
studentNames.add(student.getStudentName());
}
```
While this isn't a bad idea, it can be simplified using streams into just one line of code:
```java
List<Student> students = /* some list of student objects */;
List<String> studentNames = students.stream().map(String::getStudentName).collect(Collectors.toList());
```
The `Stream` API goes over the list of students and uses the intermediate `map` function to return a new Stream using whatever method is on the right of the `::`.
The terminal `collect` operation collects the stream as a list of strings.
This is only one use of the Streams API used in Java 8. There are many other applications of streams utilizing other operations as seen here in the
[documentation](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html).
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
- [Lambda Expressions](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)
- [Java 8 Stream API](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)
- [Java 8 Double Colon Operator](https://www.baeldung.com/java-8-double-colon-operator)

View File

@ -0,0 +1,74 @@
---
title: Break Control Statement
---
# Break Control Statement
Terminates the loop and starts the execution of the code that immediately follows the loop. If you have nested loops, the `break` statement will only end the loop in which it is placed.
```java
// Loop 1
for (int i = 0; i < 10; i++)
{
// Loop 2
for (int j = 0; j < 10; j++)
{
if (i == 5 && j == 5)
{
break; // Will terminate Loop 2, but Loop 1 will keep going
}
}
}
```
But if you do want to break out of the outer loop too, you can use a label to exit:
```java
loop1: // This is a label
for (int i = 0; i < 10; i++)
{
// Loop 2
for (int j = 0; j < 10; j++)
{
if (i == 5 && j == 5)
{
break loop1; // Will break out of Loop 1, instead of Loop 2
}
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZA/0' target='_blank' rel='nofollow'>Run Code</a>
`break` statements can be particulary useful while searching for an element in an array. Using `break` in the following code improves efficiency as the loop stops as soon as the element we are looking for (`searchFor`) is found, instead of going on till the end of `arrayInts` is reached.
```java
int j = 0;
int[] arrayOfInts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int searchFor = 5;
for (int i : arrayOfInts)
{
if (arrayOfInts[j] == searchFor)
{
break;
}
j++;
}
System.out.println("j = " + j);
```
Break statement can also be used under while statement.
```java
int i = 0;
int[] arrayOfInts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int searchFor = 5;
while(i < 10){
System.out.println("i = " + j);
if(arrayOfInts[i] > 7){
break;
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZC/0' target='_blank' rel='nofollow'>Run Code</a>

View File

@ -0,0 +1,49 @@
---
title: Continue Control Statement
---
# Continue Control Statement
The `continue` statement makes a loop skip all the following lines after the continue and jump ahead to the beginning of the next iteration. In a `for` loop, control jumps to the update statement, and in a `while` or `do while` loop, control jumps to the boolean expression/condition.
```java
for (int j = 0; j < 10; j++)
{
if (j == 5)
{
continue;
}
System.out.print (j + " ");
}
```
The value of `j` will be printed for each iteration, except when it is equal to `5`. The print statement will get skipped because of the `continue` and the output will be:
0 1 2 3 4 6 7 8 9
Say you want to count the number of `i`s in a the word `mississippi`. Here you could use a loop with the `continue` statement, as follows:
```java
String searchWord = "mississippi";
// max stores the length of the string
int max = searchWord.length();
int numPs = 0;
for (int i = 0; i < max; i++)
{
// We only want to count i's - skip other letters
if (searchWord.charAt(i) != 'i')
{
continue;
}
// Increase count_i for each i encountered
numPs++;
}
System.out.println("numPs = " + numPs);
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJZH/0' target='_blank' rel='nofollow'>Run Code</a>
Additionally, you can use labels to choose a specific loop out of a nested set to skip to the next iteration.

View File

@ -0,0 +1,50 @@
---
title: Jump Statements
---
# Jump Statements
Jump statements are a type of <a href='https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html' target='_blank' rel='nofollow'><i>control flow</i></a> statements. Basically, you can use them to change the order in which statements are executed from the normal course of execution. In essence, these statements cause the program control to 'jump' away from the next expected point of execution to another place in the program.
The following jump statements are commonly used with loops:
* <a href='http://forum.freecodecamp.com/t/java-loops-break-control-statement' target='_blank' rel='nofollow'>break</a>
* <a href='http://forum.freecodecamp.com/t/java-loops-continue-control-statement' target='_blank' rel='nofollow'>continue</a>
The 'break' control statement breaks out of the loop when the condition is met. This means the rest of the loop will not run.
For example, in the loop below if i reaches 5, the loop breaks, so it does not continue on.
```java
for(int i=0;i<10;i++){
if(i == 5){ //if i is 5, break out of the loop.
break;
}
System.out.println(i);
}
```
Output:
```
0 1 2 3 4
```
The 'continue' control statement is the less intense version of 'break'. It only breaks out of the current instance of the loop and continues on. In the loop below, if i is 5, the loop continues, so it will skip over the print statement below and move on until i reaches 10 and the loop stops.
```java
for(int i=0;i<10;i++){
if(i == 5){ //if i is 5, break out of the current instance loop.
continue;
}
System.out.println(i);
}
```
Output:
```
0 1 2 3 4 6 7 8 9
```

View File

@ -0,0 +1,54 @@
---
title: Do...While Loop
---
# Do...While Loop
The `do while` is similar to the `while` loop, but the group of statements is guranteed to run at least once before checking for a given condition.
An important thing to note is 'while' loop is an exit control loop. while(it will not necessarily be executed), 'do while' is an entry controlled loop(it will be executed at least once , even if the conditon is not true).
```java
do
{
// Statements
}
while (condition);
```
## Example
```java
int iter_DoWhile = 20;
do
{
System.out.print (iter_DoWhile + " ");
// Increment the counter
iter_DoWhile++;
}
while (iter_DoWhile < 10);
System.out.println("iter_DoWhile Value: " + iter_DoWhile);
```
Output:
```
20
iter_DoWhile Value: 21
```
**Remember**: The condition of a `do-while` loop is checked after the code body is executed once.
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJYl/0' target='_blank' rel='nofollow'>Run Code</a>
## Exercise
Can you guess the output of the following code snippet?
```java
int i = 10;
do
{
System.out.println("The value of i is " + i);
i--;
}
while (i >= 10);
```

View File

@ -0,0 +1,87 @@
---
title: For Each Loop
---
# For Each Loop
Also called the enhanced `for` loop, it is an extremely useful and simple way to iterate over each item in a collection, array or any object that implements the `Iterable` interface.
```java
for (object : iterable)
{
// Statements
}
```
The loop is read as, "for each element in the `iterable` (could be an array, collectable etc.)". The `object` type must match the element type of the `iterable`.
```java
int[] number_list = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int numbers : number_list)
{
System.out.print(numbers + " ");
// Iterated 10 times, numbers 0,1,2...9
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
```
:rocket:<a href='https://repl.it/CJYs/0' target='_blank' rel='nofollow'>Run Code</a>
Comparing this with the traditional `for` loops :
```java
int[] number_list = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i=0;i < number_list.length;i++)
{
System.out.print(number_list[i]+" ");
// Iterated 10 times, numbers 0,1,2...9
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
```
:rocket:<a href='https://repl.it/NJfG/0' target='_blank' rel='nofollow'>Run Code</a>
Both the above pieces of code snippets do the same work , however , clearly, the for each loops offer advantages in making iteration through and accessing of elements of a collection(array,in our case) easier.
With the enhanced for loops we no longer need to mention starting and ending points for the loop,thus reducing OutofBounds errors.
The need for loop counters and manual indexing are removed, and readability of the code is improved.
It is important to note that making changes to the iterating variable for enhanced for loops within the loop causes no changes to the original collection elements.
Enhanced for loops can also be used with multidimensional arrays or other Java collections.
An example of it's usage with multidimenisonal arrays are shown below:
```java
int number_list_new[][]={ { 0, 1, 2},
{ 3, 4, 5},
{ 6, 7, 8} };
// Because 2d arrays are implemented as "arrays of arrays",the first iteration variable iterates
// through 3 such arrays(that is, the 3 rows of testarr[][])
for(int i[] : number_list_new)
{
for(int j : i){
System.out.print(j+" ");
}
}
```
Output:
```
0 1 2 3 4 5 6 7 8
```
:rocket: <a href='https://repl.it/NJhP/0' target='_blank' rel='nofollow'>Run Code</a>
In the above code snippets, `number_list` is an array. If you don't know what this is, don't worry about it. An array is a container object that holds a fixed number of values of a single type, but more on this later.

View File

@ -0,0 +1,73 @@
---
title: For Loop
---
# For Loop
The `for` loop gives you a compact way to iterate over a range of values.
A basic `for` statement has three parts: a variable initialization, a boolean expression, and an increment expression.
```java
for (variable initialization; boolean expression; increment expression)
{
// Statements
}
```
* `initialization` - Initializes the loop and is executed just once, at the beginning.
You can initialize more than one variable of the same type in the first part of the basic `for` loop declaration; each initialization must be separated by a comma.
* `expression` - Evaluated at the beginning of each iteration. If the `expression` evaluates to `true`, `Statements` will get executed.
* `increment` - Invoked after each iteration through the loop. You can increase/decrease the value of variables here. Be sure the increment is working towards the expression value, to avoid an infinite loop.
A common way the `for` loop is used is if you need to iterate your code a specific number of times. For example, if you wanted to output the numbers 0-10, you would initialize the variable for your counter to 0, then check if the value is less than 10, and add one to the counter after every iteration.
Notice that you would check if the value is less than 10, not less than or equal to 10, since you are starting your counter at 0.
```java
for (int iter_For = 0; iter_For < 10; iter_For++)
{
System.out.print(iter_For + " ");
// Iterated 10 times, iter_For 0,1,2...9
}
System.out.println("iter_For Value: " + iter_For);
```
Note: It is also acceptable to declare a variable within the for loop as a single statement.
```java
for (int iter_For = 0; iter_For < 10; iter_For++)
{
System.out.print (iter_For + " ");
// Iterated 10 times, iter_For 0,1,2...9
}
```
Output:
```
0 1 2 3 4 5 6 7 8 9
iter_For Value: 10
```
Another example of a for loop that adds the first 50 numbers would be like this.
i++ means i = i+1.
```java
int addUntil = 50;
int sum 0;
for (int i = 1; i <= addUntil; i++)
{
sum+=i
}
System.out.println("The sum of the first 50 numbers is: " + 50);
```
![:rocket:](https://forum.freecodecamp.org/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CJYr/0' target='_blank' rel='nofollow'>Run Code</a>
### Extras
You cannot use a number (old C-style language construct) or anything that does not evaluate to a boolean value as a condition for an if statement or looping construct. You can't, for example, say if(x), unless x is a boolean variable.
Also, it is important to keep in mind that the boolean expression must, at some point, evaluate to true. Otherwise, your program will be stuck in an infinite loop.

View File

@ -0,0 +1,21 @@
---
title: Loops
---
# Loops
Whenever you need to execute a block of code multiple times, a loop will often
come in handy.
Java has 4 types of loops:
* [While Loop](loops/while-loop)
* [Do...While Loop](loops/do-while-loop)
* [For Loop](loops/for-loop)
* [For Each Loop](loops/for-each-loop)
Loops behaviour can be customized using:
* [Control Statements](loops/control-statements)
* [Break Control Statement](loops/break-control-statement)
* [Continue Control Statement](loops/continue-control-statement)
A special case of loops:
* [Infinite Loops](loops/infinite-loops)

View File

@ -0,0 +1,65 @@
---
title: Infinite Loops
---
# Infinite Loops
An infinte loop is a loop statement (`for`, `while`, `do-while`) which does not end on its own.
The test condition of a looping statement decides whether the loop body will execute or not. So a test condition which is always true will keep on executing the body of the loop, forever. That's the case in an infinte loop.
Examples:
```java
// Infinite For Loop
for ( ; ; )
{
// some code here
}
// Infinite While Loop
while (true)
{
// some code here
}
// Infinite Do While Loop
do
{
// some code here
} while (true);
```
Normally, if your loop is running infinitely, it is an error that should not occur as an infinite loop does not stop and prevents the rest of the program from running.
```java
for(int i=0;i<100;i++){
if(i==49){
i=0;
}
}
```
The loop above runs infinitely because every time i approaches 49, it is set to be 0.This is to say that i never reaches 100 to terminate the loop, so the loop is an infinite loop.
But a program stuck in such a loop will keep using computer resources indefinitely. This is undesirable, and is a type of 'run-time error'.
To prevent the error, programmers use a break statement to break out of the loop. The break executes only under a particular condition. Use of a selection statement like if-else ensures the same.
```java
while (true)
{
// do something
if(conditionToEndLoop == true)
break;
// do more
}
```
The main advantage of using an infinite loop over a regular loop is readability.
Sometimes, the body of a loop is easier to understand if the loop ends in the middle, and not at the end/beginning. In such a situation, an infinite loop will be a better choice.

View File

@ -0,0 +1,40 @@
---
title: While Loop
---
# While Loop
The `while` loop repeatedly executes the block of statements until the condition specified within the parentheses evaluates to `false`. For instance:
```java
while (some_condition_is_true)
{
// do something
}
```
Each 'iteration' (of executing the block of statements) is preceeded by the evaluation of the condition specified within the parentheses - The statements are executed only if the condition evaluates to `true`. If it evaluates to `false`, the execution of the program resumes from the the statement just after the `while` block.
**Note**: For the `while` loop to start executing, you'd require the condition to be `true` initially. However, to exit the loop, you must do something within the block of statements to eventually reach an iteration when the condition evaluates to `false` (as done below). Otherwise the loop will execute forever. (In practice, it will run until the <a href='https://guide.freecodecamp.org/java/the-java-virtual-machine-jvm' target='_blank' rel='nofollow'>JVM</a> runs out of memory.)
## Example
In the following example, the `expression` is given by `iter_While < 10`. We increment `iter_While` by `1` each time the loop is executed. The `while`loop breaks when`iter_While`value reaches `10`.
```java
int iter_While = 0;
while (iter_While < 10)
{
System.out.print(iter_While + " ");
// Increment the counter
// Iterated 10 times, iter_While 0,1,2...9
iter_While++;
}
System.out.println("iter_While Value: " + iter_While);
```
Output:
```
0 1 2 3 4 5 6 7 8 9
iter_While Value: 10
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") [Run Code](https://repl.it/CJYj/0)

View File

@ -0,0 +1,108 @@
---
title: Methods
---
# Methods
The most recognizable method in Java is probably `public static void main(String[]args)` where `public` means that users have access to the method, `static` means that the method is based on a "class" rather than an "instance," `void` means that nothing will be returned from the method to another (higher level) method, and `main` which is the name of this particular method.
`getName()` and `getManufacturerName()` are two "Getter" methods we have used here. Generally, methods in Java consist of these parts -
* Access Modifer (Optional) - `public`, `private`, or `protected`. Defaults to package private if omitted
* Return Type - This is required, it denotes what value the method returns, or `void` if nothing is returned
* Method Name - follows camelCase convention
* Parameter List - List of parameters with their name and type, empty if no parameters are accepted
* Method body surrounded by `{ }`
Methods can also optionally have the `static` keyword, meaning it is associated with the class itself, rather than an instance of the class, ex - `public static void main()`.
Notice, unlike JavaScript, we **have** to define the return type of any method we write, otherwise it will fail at compile time. If you do not want a method to return anything, use `void` return type.
Each method has a signature, which is the combination of the data type, the name, and the number of arguments the method takes. In `public static void main` the method does not have a specified data type and instead uses `void` to declare that no data is returned. In a method named `public static double ave(double val, double val)` the data type is "double" (0.0), the name is "ave" (average) and the method takes 2 arguments. Each method **must** have a unique signature.
```java
public class Car {
private String name;
private String manufacturersName;
public void changeName() {
name = "Tesla";
}
public String getName(){
return name;
}
public String getManufacurername(){
return manufacturersName;
}
}
```
Parameters can be passed into methods. Parameters are declared just after the name of the method, inside brackets.
Syntax for parameter declaration is [Data Type] [Name].
```java
public class Car {
private String name;
public void changeName(String newName) {
name = newName;
}
}
```
If we not sure with the distinct number of parameters passed in a method then use 'Variable Arguments (Varargs) Method'
Initialize parameter with three dots and will have same dataType.
Passed arguments will store in an array and also accessible as array
```java
public class Main
{
public static void main(String[] args) {
Main p=new Main();
System.out.println(p.sum(5,5,5,5,5,5,5,5,5)); //can pass any number of argument.
}
int sum(int ...a) //decleration of variable argument method.
{int sum=0;
for(int i=0;i<a.length;i++)
sum=sum+a[i]; //getting the passed arguments in form of array
return sum;}
}
```
As with any other language, methods (or functions, if you are here from JS world) are used often for their modularity and reusability.
Methods often serve many purposes such as updating information in an object or providing data back to the caller. Here are some examples.
```java
public class Car {
private int numberOfWheels;
public void setNumberOfWheels(int newNumberOfWheels) {
numberOfWheels = newNumberOfWheels;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
}
```
In the case of `getNumberOfWheels()` the return type is `int` which is a whole number. The keyword `return` tells java to pass back the value of the instance variable `numberOfWheels`. `setNumberOfWheels(int newNumberOfWheels)` however has no return type as it is a setter method as previously seen. In this case though it takes in an argument of type `int` and makes the instance varible `numberOfWheels` equal to `newNumberOfWheels`.
There is also a special method called a constructor that allows for data to be set or operations to be performed when the class is instantiated. This constructor has no return type.
```java
public class Car {
private String model;
private int numberOfWheels;
public Car(String model, int numberOfWheels) {
this.model = model;
this.numberOfWheels = numberOfWheels;
}
}
```
The `Car` class and the `Car(String model, int numberOfWheels)` method have to have the same name in order for java to know that it is the constructor. Now anytime you instantiate a new `Car` instance with the `new` keyword you will need to call this constructor and pass in the needed data.

View File

@ -0,0 +1,53 @@
---
title: Multithreading
---
## Multithreading
Multithreading is a process of executing multiple processes simultaneously. Java starts the program with a main thread and further threads are added upon main thread whenever any user creates it. Main thread is the first user thread in any Java program. Also, JVM makes sure that all the user threads are closed before the program ends.
## Thread LifeCycle
A thread at any of point exists in any one of the following states:
1. New - When a new thread is created, it is in the new state. The thread has not started yet.
2. Runnable - A thread that is ready to run is moved to runnable state.
3. Running - The thread scheduler picks up a thread from runnable threads pool and ensures that each thread gets to run.
4. Waiting/Blocked - When a thread is temporarily inactive, then is in blocked/waiting state. Example - a thread waiting for I/O to complete.
5. Terminated - A thread can be terminated due to 2 reasons. Either it has completed the job and terminates normally or due to some unhandled exception or segmentation fault, etc.
For more info on thread states, refer :- https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/
A thread has both advantages and disadvantages.
## Advantages:
* Running code independently of other threads.
* Creation of a modular design.
## Disadvantages:
Race conditions and Deadlocks if threads are not syncrhronized properly.
Threads can further be divided into two classes:
* User Threads
* Daemon Threads
A thread can be created in 2 ways:
1. implementing Runnable interface:
There is only one method in Runnable interface i.e. public void run(). Implementing this method will make sure that whenever this thread starts the code inside run() executes.
2. extending thread class.
This class also contains public void run() which we need to override in order to run our own code. The disadvantage of using this method is that we have a superclass in Thread and cannot extend any other class which we may want to.
The code for both can be found here: http://ide.geeksforgeeks.org/k7GjcA.
You will notice that if this code is ran multiple times, the results may differ. and that is decided by the OS upon which it is run. The OS can pick any thread from a runnable state and can run it. We have NO CONTROL over that. If there are multiple threads in runnable state (ready to run), anyone can be picked. It even does not depend upon priority.

View File

@ -0,0 +1,34 @@
---
title: POJO
---
## POJO
POJO stands for "Plain Old Java Object". This is different from Plain Old _Javascript_ Objects.
A Plain Old Java Object refers to the Object Oriented Programming (OOP) paradigm that is used in the Java programming language. The [OOP model](https://en.wikipedia.org/wiki/Object-oriented_programming) treats data as 'objects'. Each 'object' is an instance of a 'Class', which represents the archetype or template from which all objects inherit their properties and attributes.
A POJO is therefore simply a Java Object. However, it must also satisfy the following additional criteria:
1. it must not extend prespecified Java Classes;
```java
public class Foo extends javax.servlet.http.HttpServlet {
...// body ...
}
```
2. it must not implement prespecified Interfaces;
```java
public class Bar implements javax.ejb.EntityBean {
... // body
}
```
3. it must not contain prespecified Annotations.
```java
@javax.persistence.Entity public class Baz {
... // body ...
}
```
Therefore a Java Object qualifies as a POJO only when it is free from the above modifications. It therefore follows that a POJO is not 'bound by any restrictions' other those prescribed by the formal Java language specification.
#### More Information:
[Wikipedia - POJOs](https://en.wikipedia.org/wiki/Plain_old_Java_object)

View File

@ -0,0 +1,53 @@
---
title: Regular Expressions
---
# Regular Expressions
### Introduction
Regular expressions in Java are useful for searching, editing and manipulating strings. Regular Expressions are also known as Regex.
### Java Regex provides three classes in java.util.regex package:
- Matcher
-- Used for defining the String pattern to match
- Pattern
-- Used for peforning math on given pattern
- PatternSyntaxException
-- Used for indicate exceptions in the pattern
### RegEx Example:
- Check that the string contains only characters and no numbers or special characters.
```
import java.util.regex.*;
public class RegExExample {
public static final String ARTICLE_STRING = "freecodecamp";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher match = pattern.matcher(ARTICLE_STRING);
boolean result = match.matches();
System.out.println("Result: " + result);
}
}
```
```
Result: true
```
### Understanding the pattern:
```"^[a-zA-Z]*$"```
^ - The beginning of a line
[a-zA-Z] - Match characters from a-z and A-Z
*$ - The end of the line
### RegEx Cheatsheet:
- Here is a very good link to [RegEx Cheatsheet](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
- [Class Pattern](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
- [Lesson on Regular Expression](https://docs.oracle.com/javase/tutorial/essential/regex/)

View File

@ -0,0 +1,54 @@
---
title: Resources
---
# Resources
Java is trademarked and licensed by Oracle. Most of the following are un-official resources, unless hosted by Oracle.
## Tutorials
* [Oracle Official Java Tutorial](http://docs.oracle.com/javase/tutorial/index.html)
* [Think Java](http://greenteapress.com/wp/think-java/)
* [Jenkov's Java Tutorials](http://tutorials.jenkov.com/java/index.html)
* [Mkyong's Java & Spring Tutorials](http://www.mkyong.com/)
* [Vogella's Java Tutorials](http://www.vogella.com/tutorials/java.html)
* [Java 8 Tutorial](https://github.com/winterbe/java8-tutorial)
* [Better Java](https://github.com/cxxr/better-java)
* [Java Programming notes by NTU](http://www3.ntu.edu.sg/home/ehchua/programming/index.html#Java)
* [HackerRank's 30 days of Code Challenge with video tutorials in Java<](https://www.hackerrank.com/domains/tutorials/30-days-of-code)
* [Princeton's Introduction to Programming in Java](http://introcs.cs.princeton.edu/java/home/)
* [Introduction to Programming Using Java](http://math.hws.edu/javanotes/)
* [Java Practices](http://javapractices.com/home/HomeAction.do)
* [Java Design Patterns](https://github.com/iluwatar/java-design-patterns/)
* [Algorithms in Java](https://github.com/pedrovgs/Algorithms)
* [Spring Official Guides](https://spring.io/guides)
* [TutorialsPoint - Java](http://www.tutorialspoint.com/java/)
* [Java for Small Teams](https://www.gitbook.com/book/ncrcoe/java-for-small-teams/details)
## Challenges
* [Java Koans](https://github.com/matyb/java-koans)
* [Coding Bat Java Challenges](http://codingbat.com/java)
* [Excercism Java Challenges](http://exercism.io/languages/java)
* [Project Euler](https://projecteuler.net/)
* [Practice It! - Java Challenges](http://practiceit.cs.washington.edu/)
* [Codewars - Java Katas](https://www.codewars.com/?language=java)
* [HackerRank Java Challenges](https://www.hackerrank.com/domains/java/java-introduction)
* [LeetCode](https://leetcode.com/)
* [CodeAbbey](http://www.codeabbey.com/)
## Community
* [Oracle Java Community](http://www.oracle.com/technetwork/java/community/index.html)
* [Awesome Java](https://github.com/akullpp/awesome-java)
* [/r/Java](https://www.reddit.com/r/Java)
* [/r/LearnJava](https://www.reddit.com/r/learnjava)
* [Java Ranch](http://www.javaranch.com/)
* [Java Code Geeks](https://www.javacodegeeks.com/)
* [Java 8 API Search](http://javasearch.org)
## Book Recommendations
* [Head First Java](https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208/ref=zg_bs_3608_3?_encoding=UTF8&psc=1&refRID=JEDGRF7Z6K22BRTNB4CQ)
* [Effective Java](https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997/ref=zg_bs_3608_2?_encoding=UTF8&psc=1&refRID=JEDGRF7Z6K22BRTNB4CQ)
* [Java A Beginner's Guide, 6th Edition](https://www.amazon.com/gp/product/0071809252/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&tag=whatpixel-20&camp=1789&creative=9325&linkCode=as2&creativeASIN=0071809252&linkId=38f3fc73ecefeb14992aec7dba2b0e19)

View File

@ -0,0 +1,117 @@
---
title: Static
---
# Static
When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects.
The static keyword can be used with variables, methods, code blocks and nested classes.
## Static Variables
***Example:***
```java
public class Counter {
public static int COUNT = 0;
Counter() {
COUNT++;
}
}
```
The `COUNT` variable will be shared by all objects of that class. When we create objects of our Counter class in main, and access the static variable.
```java
public class MyClass {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.COUNT);
}
}
// Outputs "2"
```
The outout is 2, because the `COUNT` variable is static and gets incremented by one each time a new object of the Counter class is created. You can also access the static variable using any object of that class, such as `c1.COUNT`.
## Static Methods
A static method belongs to the class rather than instances. Thus, it can be called without creating instance of class. It is used for altering static contents of the class. There are some restrictions of static methods :
1. Static method can not use non-static members (variables or functions) of the class.
2. Static method can not use `this` or `super` keywords.
***Example:***
```java
public class Counter {
public static int COUNT = 0;
Counter() {
COUNT++;
}
public static void increment(){
COUNT++;
}
}
```
Static methods can also be called from instance of the class.
```java
public class MyClass {
public static void main(String[] args) {
Counter.increment();
Counter.increment();
System.out.println(Counter.COUNT);
}
}
// Outputs "2"
```
The output is 2 because it gets incremented by static method `increament()`. Similar to static variables, static methods can also be accessed using instance variables.
## Static Blocks
Static code blocks are used to initialise static variables. These blocks are executed immediately after declaration of static variables.
***Example:***
```java
public class Saturn {
public static final int MOON_COUNT;
static {
MOON_COUNT = 62;
}
}
```
```java
public class Main {
public static void main(String[] args) {
System.out.println(Saturn.MOON_COUNT);
}
}
// Outputs "62"
```
The output is 62, because variable `MOON_COUNT` is assigned that value in the static block.
## Static Nested Classes
A class can have static nested class which can be accessed by using outer class name.
***Example:***
```java
public class Outer {
public Outer() {
}
public static class Inner {
public Inner() {
}
}
}
```
In above example, class `Inner` can be directly accessed as a static member of class `Outer`.
```java
public class Main {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
}
}
```
One of the use case of static nested classes in [Builder Pattern](https://en.wikipedia.org/wiki/Builder_pattern#Java) popularly used in java.

View File

@ -0,0 +1,92 @@
---
title: Streams
---
# Streams
In Java 8 Streams got added as a new feature the Java toolbox. Streams allow you to quickly and cleanly process Collections.
Please read the chapter about lambdas and functional programming before continuing.
## How it works
The Stream loops the elements of the collection for you.
Each intermediate and the terminal operation are called for each object.
Once all operations are finished for the first objects, then the second object is loaded.
## Important Methods
### Creation
- `Collection.stream()`: create a Stream from any object from any class implementing `Collection`
- `Arrays.stream(array)`: create a Stream from an Array
### Intermediate Operations
These operations convert the Stream Objects somehow.
- `Stream.map(Function<In,Out> function)`: apply a Function to convert In to Out
- `Stream.filter(Predicate<In> predicate)`: remove Objects from Stream for which the Predicate does not test true
- `Stream.distinct()`: remove Objects from Stream which are duplicates
- `Stream.sorted()`: sort the Objects in the Stream
- `Stream.limit(int n)`: end Stream after n Objects
### Terminal Operations
These operations receive the Stream Objects and end the Stream.
- `Stream.collect(Collector<In,?,Out> collector)`: collect all Objects in Stream into Object
- `Stream.forEach(Consumer<In> consumer)`: consume all Objects in Stream using the consumer function
- `Stream.count()`: count all Objects in Stream
- `Stream.findFirst()`: return the first Object of the Stream and stop
- `Stream.anyMatch(Predicate<In> predicate)`: return true if any Object in the Stream tests true for the Predicate
- `Stream.allMatch(Predicate<In> predicate)`: return true if all Object in the Stream test true for the Predicate
## Examples
```java
// print the length of all Strings in a List
for (String string : Arrays.asList("abc", "de", "f", "abc")) {
int length = string.length();
System.out.println(length);
}
Arrays.asList("abc", "de", "f", "abc")
.stream()
.map(String::length)
.forEach(System.out::println);
// output: 3 2 1 3
```
```java
// print all Strings in a List with a Length greater than 2
for (String string : Arrays.asList("abc", "de", "f", "abc")) {
if (string.length() > 2) {
System.out.println(string);
}
}
Arrays.asList("abc", "de", "f", "abc")
.stream()
.filter(string -> string.length() > 2)
.forEach(System.out::println);
// output: abc abc
```
```java
// create a sorted List with all unique Strings from another List which are longer than or requal 2
List<String> result = new ArrayList<>();
for (String string : Arrays.asList("de", "abc", "f", "abc")) {
if (string.length() >= 2
&& ! result.contains(string)) {
result.add(string);
}
}
Collections.sort(result);
List<String> result2 = Arrays.asList("de", "abc", "f", "abc")
.stream()
.filter(string -> string.length() >= 2)
.distinct()
.sorted()
.collect(Collectors.toList());
// result: abc de
```
### Sources
1. [Processing Data with Java SE 8 Streams, Part 1](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html)

View File

@ -0,0 +1,185 @@
---
title: Strings
---
# Strings
Strings are sequences of characters. In Java, a `String` is an `Object`. Strings should not be confused with `char` as characters are literally 1 value rather than a sequence of characters. You can still use 1 value within a String, however it is preferred to use `char` when you are checking for 1 character.
```java
String course = "FCC";
System.out.println(course instanceof Object);
```
Output:
```
true
```
You can create a String Object in the following ways:
1. `String str = "I am a String"; //as a String literal`
1. `String str = "I am a " + "String"; //as a constant expression`
1. `String str = new String("I am a String"); //as a String Object using the constructor`
You might be thinking: What's the difference between the three?
Well, using the `new` keyword guarantees that a new `String` object will be created and a new memory location will be allocated in the `Heap`
memory [(click here to learn more)](https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html). String
literals and constant String expressions are cached at compile time. The compiler puts them in the String Literal Pool to prevent duplicates
and improve memory consumption. Object allocation is expensive and this trick increases performance while instantiating Strings. If you use
the same literal again, the JVM uses the same object. Using the contructor like above is almost always a worse choice.
In this code snippet, how many String objects are created?
```java
String str = "This is a string";
String str2 = "This is a string";
String str3 = new String("This is a string");
```
The answer is: 2 String objects are created. `str` and `str2` both refer to the same object. `str3` has the same content but using `new` forced
the creation of a new, distinct, object.
When you create a String literal, the JVM internally checks, what is known as the `String pool`, to see if it can find a similar (content wise)
String object. If it finds it, it returns the same reference. Otherwise, it just goes ahead and creates a new String object in the pool so that
the same check can be performed in the future.
You can test this using the swallow, fast Object comparison `==` and the implemented `equals()`.
```java
System.out.println(str == str2); // This prints 'true'
System.out.println(str == str3); // This prints 'false'
System.out.println(str.equals(str3)); // This prints 'true'
```
Here's another example on how to create a string in Java using the different methods:
```java
public class StringExample{
public static void main(String args[]) {
String s1 = "java"; // creating string by Java string literal
char ch[] = {'s','t','r','i','n','g','s'};
String s2 = new String(ch); // converting char array to string
String s3 = new String("example"); // creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
```
#### Comparing Strings
If you want to compare the value of two String variables, you can't use ==. This is due to the fact that this will compare the references of the variables
and not the values that are linked to them. To compare the stored values of the Strings you use the method equals.
```java
boolean equals(Object obj)
```
It returns true if two objects are equal and false otherwise.
```java
String str = "Hello world";
String str2 = "Hello world";
System.out.println(str == str2); // This prints false
System.out.println(str.equals(str2); // This prints true
```
The first comparison is false because "==" looks at the references and they aren't the same.
The second comparison is true because the variables store the same values. In this case "Hello world".
We have several inbuilt methods in String. The following is an example of the String Length() method .
```java
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
```
This will result in - `String Length is : 17`
<B>The answer is: 2 </B> String objects are created.
**Notes**
1. String methods use zero-based indexes, except for the second argument of `substring()`.
2. The String class is final - it's methods can't be overridden.
3. When the String literal is found by JVM, it is added to string literal pool.
4. String class posses a method name `length()`, while arrays have an attribute naming length.
5. In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created.
String Length
The "length" of a string is just the number of chars in it. So "hi" is length 2 and "Hello" is length 5. The length() method on a string returns its length, like this:
```java
String a = "Hello";
int len = a.length(); // len is 5
```
#### Other comparison methods which can also be used on the String are :
1. equalsIgnoreCase() :- compares the string without taking into consideration the case sensitivity.
```java
String a = "HELLO";
String b = "hello";
System.out.println(a.equalsIgnoreCase(b)); // It will print true
```
2. compareTo :- compares the value lexicographically and returns an integer.
```java
String a = "Sam";
String b = "Sam";
String c = "Ram";
System.out.println(a.compareTo(b)); // 0
System.out.prinltn(a.compareTo(c)); // 1 since (a>b)
System.out.println(c.compareTo(a)); // -1 since (c<a)
```
#### Splitting Strings
If you want to split a string into multiple parts it can easily be done through ```.split()``` this creates an array of the split up parts of the string.
Example of using a delimiter (",") to split a string
```java
String text = "Hello, World";
String[] textParts = text.split(",");
System.out.println(textParts[0]);
System.out.println(textParts[1]);
```
The result will be:
```
Hello
World
```
We can also split the string by specifing the start and end index of the characters in the string. We will do this using the Java function called ```.substring()```.
The ```.substring()``` method can be used in two ways. One with only the starting index and one with both the start and end index. Take note that the index starts from 0.
Example:
```java
String text = "Hello,My name is Bob";
System.out.println(text.substring(6));
```
Will produce
```
My Name is Bob
```
To use it with an ending index take note that the actual ending index is -1 of the value passed into the method.
Now using ```.substring()``` with an ending index
Example:
```
String text = "Hello,My name is Bob";
System.out.println(text.substring(6,8));
```
The result will be:
```
My
```

View File

@ -0,0 +1,29 @@
---
title: Java Swing
---
## Java Swing
Let's explore the Java swing tutorial. Before making our hands all dirty with the Swing, it is recommended that you go through the [Abstract Window Toolkit(AWT)](https://www.studytonight.com/java/java-awt.php).Earlier, Swing was added as a part of [Java Foundation Classes(JFC)](https://en.wikipedia.org/wiki/Java_Foundation_Classes).However it was fully merged into Java from Java 1.2 onwards.
### Strikable features
1. Lightweight components- Since the Swing components are completely written in JAVA,they don't use platform specific resources as like AWT components do.
2. Pluggable Look and Feel(PLAF)- The Look and Feel of component is entirely determined by Swing itself. That makes it easier to distinguish between look and feel and the logic of component.
Swing GUI consists of two main pillars:-components and containers.The following part discusses about both of them thoroughly.
### Components
An Component is simply an independent visual control.Swing components are derived from JComponent class. Further JComponent inherits all its characteristics from AWT Containers and Components.For more information, please go through the hierarchy of [JComponent](https://docs.oracle.com/javase/tutorial/uiswing/components/jcomponent.html) class.
### Containers
All containers are also components. Containers may comprise of one or more components. Swing defines two types of containers
- inherits from JComponent- e.g. JFrame, JWindow, JApplet, JDialog
- does not inherits from JComponent- e.g. JPanel
### Packages
Swing comprises of numerous number of packages.Please go through the [official documentation](https://docs.oracle.com/javase/7/docs/api/javax/swing/package-use.html) for more information.
#### More Information:
- [Oracle docs](https://docs.oracle.com/javase/7/docs/api/javax/swing/package-use.html)
- [Wikipedia](https://en.wikipedia.org/wiki/Swing_(Java)

View File

@ -0,0 +1,12 @@
---
title: Java Virtual Machine
---
# The Java Virtual Machine (JVM)
Java belongs to a family of languages called <a href='https://en.wikipedia.org/wiki/Compiled_language' target='_blank' rel='nofollow'>**Compiled Languages**</a>. Any code written in such a language needs to be converted (compiled) to an intermediate form that can then be understood by the host platform (the OS/platform in which the code runs).
For Java, this intermediate form is called **Bytecode** which is then interpreted by a runtime called a Java Virtual Machine (JVM). Think of <a href='https://docs.oracle.com/javase/specs/jvms/se7/html/' target='_blank' rel='nofollow'>**JVM**</a> as a piece of software that does the hard work of running your Java code. It takes care of memory allocation, thread management, garbage collection and so much more. Apart from Java, it also supports (read: able to run) code written in languages such as Groovy, Scala etc.
In Java, code is written and saved as `.java` files. The compiler (javac) operates on the java files and generates the equivalent Bytecode (`.class`) files. The `java` command would now be able to execute the Bytecode stored in the `.class` files. More on this later.
The following sections describe some of the basic building blocks of coding in Java.

View File

@ -0,0 +1,16 @@
---
title: Throw
---
## throw
The Java throw keyword is used to explicitly throw an exception.You can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.
***Example:***
```java
throw new ArithmeticException("/ by zero not permitted");
```
##### More resources
[Geeks for Geeks](https://www.geeksforgeeks.org/throw-throws-java/)

View File

@ -0,0 +1,30 @@
---
title: Throws
---
## throws
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
***Example:***
```java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
```

View File

@ -0,0 +1,48 @@
---
title: tokens
---
# Tokens in Java
These are the fundamental building blocks of a program or the smallest unit of a program.
Java supports five types of tokens:
## 1. Keywords
These are the words which have their predefined definitions in the compiler and cannot be used as the names of the identifiers.There are 51 keywords and 2 reserved words in Java.
## 2. Identifiers
These are the various names given to different components of the program. These includes the names of variables, methods, class, etc. They must not begin with a digit but can contain digits, letters, underscore, currency symbols.
## 3. Literals
These provide a way to express specific values in a program.These are of following types:
### Numeric Literals
These are of three types in Java.
* #### Integer Literals
* #### Floating Point Literals
* #### Character Literals
### Boolean Literals
These are of two types
* #### true
* #### false
### String Literals
## 4. Operators
These are the special types of symbols used to perform certain operations. For example +, -, *, /, %
## 5. Seperators
These include tab, enter, space bar.
##### Now let us consider a program
```java
//Printing Hello World
public class Hello
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}
```
The source code contains tokens such as _public_, _class_, _Hello_, {, _public_, _static_, _void_, _main_, (, _String_, [], _args_, {, _System_, _out_, _println_, (, _"Hello World"_, }, }. The resulting tokens· are compiled into Java bytecodes that is capable of being run from within an interpreted java environment. Token are useful for compiler to detect errors. When tokens are not arranged in a particular sequence, the compiler generates an error message.

View File

@ -0,0 +1,32 @@
---
title: Typecasting
---
## Typecasting
Converting one data type to another data type is known as type casting. Since
Java is an Object Oriented programming language and supports both **Inheritance** and **Polymorphism**, Its easy that super class reference variable is pointing to subClass object.
When we assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then JVM will perform the conversion automatically known as automatic type conversion and if not then they need to be casted or converted explicitly.
### Types of Typecasting
Java, type casting is classified into two types.
***1. Implicit Typecasting***
Here, Automatic Type casting take place when the two types are compatible
the target type is larger than the source type.
eg.
``` java
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
```
***2. Explicit Typecasting***
When we assign a larger type value to a variable of smaller type, then we need to perform explicit type casting.
eg.
```java
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
```
#### More Information:
- [Oracle Java Docs :Typecasting](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html)

View File

@ -0,0 +1,55 @@
---
title: Variables
---
# Variables
Variables store values. They are the most basic entity used to store data such as text, numbers, etc. in a program.
In <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Java' target='_blank' rel='nofollow'>Java</a>, variables are <a href='https://en.wikipedia.org/wiki/Strong_and_weak_typing#Definitions_of_.22strong.22_or_.22weak.22' target='_blank' rel='nofollow'>_strongly typed_</a>, which means you have to define the type for each variable whenever you declare it. Otherwise, the compiler will throw an error at <a href='https://en.wikipedia.org/wiki/Compile_time' target='_blank' rel='nofollow'>compile time</a>. Therefore, each variable has an associated '<a href='https://guide.freecodecamp.org/java/data-types' target='_blank' rel='nofollow'>data-type</a>' of one of the following:
* Primitive Type: `int`, `short`, `char`, `long`, `boolean`, `byte`, `float`, `double`
* Wrapper Type: `Integer`, `Short`, `Char`, `Long`, `Boolean`, `Byte`, `Float`, `Double`
* Reference Type: `String`, `StringBuilder`, `Calendar`, `ArrayList`, etc.
You may have noticed that the **Wrapper Type** consists of types spelled exactly like the **Primitive Type**, except for the capitalised alphabet in the begining (like the **Reference Type**). This is because the Wrapper Types are actually a part of the more general Reference Types, but <i>closely linked</i> with their primitive counterparts via <a href='https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html' target='_blank' rel='nofollow'>autoboxing and unboxing</a>. For now, you just need to know that such a 'Wrapper Type' exists.
Typically, you can <i>declare</i> (i.e., create) variables as per the following syntax: <<i>data-type</i>> <<i>variableName</i>>;
```java
// Primitive Data Type
int i;
// Reference Data Type
Float myFloat;
```
You can <i>assign</i> a value to the variable either simultaneously when you are declaring it (which is called <i>initialisation</i>), or anywhere in the code after you have declared it. The symbol **=** is used for the same.
```java
// Initialise the variable of Primitive Data Type 'int' to store the value 10
int i = 10;
double amount = 10.0;
boolean isOpen = false;
char c = 'a'; // Note the single quotes
//Variables can also be declared in one statement, and assigned values later.
int j;
j = 10;
// initiates an Float object with value 1.0
// variable myFloat now points to the object
Float myFloat = new Float(1.0);
//Bytes are one of types in Java and can be
//represented with this code
int byteValue = 0B101;
byte anotherByte = (byte)0b00100001;
```
As evident from the above example, variables of Primitive type behave slightly differently from variables of Reference (& Wrapper) type - while Primitive variables <i>store</i> the actual value, Reference variables <i>refer to</i> an 'object' containing the actual value.
You can find out more in the sections linked below.
# Other Resources
* <a href='https://guide.freecodecamp.org/java/data-types' target='_blank' rel='nofollow'>Data Types</a>
* <a href='https://guide.freecodecamp.org/java/classes-and-objects' target='_blank' rel='nofollow'>Classes and Objects</a>