Software Engineer - Learn Java by Examples (2019)
Software Engineer - Learn Java by Examples (2019)
Portable − You can run java bytecode on any hardware that has a compliant
Java Virtual Machine installed without changing the source code.
Simple − Java’s conscise, cohesive set of features makes it easy to learn and
use.
Robust −The Java compiler detects many problems before showing up on run
time to eliminate error prone situations.
This will compile your code. If there are no errors in the code, the command
prompt will take you to the next line. Now, type "java ExampleClass" to run the
file:
C: path to where you save your file> java ExampleClass
The output:
Java is fun!
In Java, a source file is a text file that contains at least one class. Every line of
code must be inside in a class that always starts with an uppercase first letter.
The source file should end with the .java extention, and the name of the java
file must match the class name.
In Java, applications start execution by calling main() method. Every program
must contain main() method.
“public static void main(String[] args)” public is an access modifier which
determines how other parts of the program can access the members of the
class. static allows the main() method to be called before an object of the
class has been instantiated.
Java Variables
Variables are used to represent the values that may be changed in the
program.
Java uses four types for integers: byte, short, int, and long. For simplicity and
consistency, we will use int for integers in this book.
Java uses two types for floating-point numbers: float and double. The double
type is twice as big as float, so the double is known as double precision, and
float as single precision. We will use the double type, because it is more
accurate than the float type.
To create a variable, you must specify the type and assign it a value:
type variable = value
Where type is one of Java's types (such as float or boolean), and variable is
the name of the variable (such as count or employee). The equal sign is used
to assign values to the variable.
public class Variables {
public static void main(String[] args) {
System.out.println(year);
System.out.println(aFloat);
System.out.println(radius);
System.out.println(grade);
System.out.println(isTrue);
System.out.println(aText);
}
}
The output:
2019
7.14
9.73
A
false
It is worth learning Java
Identifiers
Identifiers are the names that identify different elements in a program.
The general rules the identifiers must obey are:
• Identifiers consist of digits, letters, underscores, and dollar sign ($)
• Identifiers can not start with a digit
• Identifiers can not be a reserved word
• Identifiers are case sensitive
• true, false, null can not be used as identifiers
Data Types
Data types are divided into two groups.
Assignment Operators
An assignment operator assigns a value to its left operand based on the value
of its right operand.
Operation Operator Description
Assignment x=y Assigns the value of y to x
Addition assignment x += y Assigns the x + y to x
Substraction assignment x -= y Assigns the x – y to x
Multiplication assignment x *= y Assigns the x * y to x
Division assignment x /= y Assigns the x / y to x
Remainder assignment x %= y Assigns the x % y to x
Left shift assignment x <<= y Assigns the x <<= y to x
Right shift assignment x >>= y Assigns the x >>= y to x
Bitwise AND assignment x &= y Assigns the x &= y to x
Bitwise OR assignment x |= y Assigns the x |= y to x
Bitwise XOR assignment x ^= y Assigns the x ^= y to x
Logical Operators
Logical operators are used to determine the logic between variables or values:
Operation Operator Description
Logical AND &&
Logical OR ||
Logical NOT !
Strings
A String is an object that represents sequence of chars. It is used for storing
text data. In Java, java.lang.String is a class used to represent strings. It
contains methods that can perform useful operations on strings. Any
instantiation of the class can use these methods to manipulate strings.
Method Description
charAt(index) Returns the char value at the specified index
concat() Concatenates the specified string to the end of
this string
length() Returns the length of the string
toUpperCase() Converts all of the chracters in the string to upper
case
toLowerCase() Converts all of the chracters in the string to
lowercase
trim() Returns a string whose value is this string, with
any leading and trailing whitespace removed.
equals() Tests two strings and returns true if they have the
same sequence of chracters Returns true if the
argument is an String object
format(String format object... args) Returns a formatted string using the specified
String format and arguments
compareTo() Contains two strings lexicographically
startsWith() Returns true if the string starts with the specified
prefix.
endsWith() Returns true if the string ends with the specified
suffix.
contains() Returns true if and only if this string contains
specified char values
substring(Start) Returns a string that is substring of this string
starting from the Start index to the end of the
string
substring(Start, End) Returns a string that is substring of this string The
substring begins at the start index and extends to
the character at the index End -1
indexOf() Returns the index within this string of the first
occurence of the specified value
In the example below, we create three different strings, and manipulate them
using their methods. Since a string in java is actually an object we can
invoke(activate) its pre-defined methods to manipulate string objects.
StringMethods.java
public class StringMethods {
public static void main(String[] args) {
String string1 = "JAVA";
// An alternative way of creating strings in Java
String string2 = new String("python");
// Create an empty string
String string3 = new String();
The output:
string1 is JAVA
string1.toLowerCase() is java
string2 is python
string2.toLUpperCase() is PYTHON
Length of string3 is 10
In this example we use the index of method to find the first occurence of the
string2 in string3
Example
string3 = string1.concat(string2);
// The variable index will hold
// the first occurrence of the string2 in string3
int index = string3.indexOf(string2);
System.out.println("string1: " + string1);
System.out.println("string2: " + string2);
System.out.println("string3: " + string3);
System.out.println("string2 found in string3 at index " +
index);
}
}
The output:
string1: JAVA
string2: python
string3: JAVApython
string2 found in string3 at index 4
Math Class
The Java Math class has many methods that allows you to perform
mathematical tasks on numbers. The class resides in the java.lang package. In
Java, java.lang is imported by default, so you don’t need to import it.
A detailed list of math methods in the class.
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
cbrt(x) Returns the cube root of x
ceil(x) Returns the value of x rounded up to its nearest integer
copySign(x, y) Returns the first floating point x with the sign of the second floating point y
cos(x) Returns the cosine of x (x is in radians)
cosh(x) Returns the hyperbolic cosine of a double value
exp(x) Returns the value of Ex
expm1(x) Returns ex -1
floor(x) Returns the value of x rounded down to its nearest integer
getExponent(x) Returns the unbiased exponent used in x
hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
Computes the remainder operation on x and y as prescribed by the IEEE 754
IEEEremainder(x, y)
standard
log(x) Returns the natural logarithm (base E) of x
log10(x) Returns the base 10 logarithm of x
log1p(x) Returns the natural logarithm (base E) of the sum of x and 1
max(x, y) Returns the number with the highest value
min(x, y) Returns the number with the lowest value
nextAfter(x, y) Returns the floating point number adjacent to x in the direction of y
Returns the floating point value adjacent to x in the direction of positive
nextUp(x)
infinity
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
Returns the double value that is closest to x and equal to a mathematical
rint()
integer
signum(x) Returns the sign of x
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
tanh(x) Returns the hyperbolic tangent of a double value
Converts an angle measured in radians to an approx. equivalent angle
toDegrees(x)
measured in degrees
Converts an angle measured in degrees to an approx. angle measured in
toRadians(x)
radians
ulp(x) Returns the size of the unit of least precision (ulp) of x
In the example below we declare four variables of type integer num1, num2,
maximum and minimum. We initialize num1 to 20 , num2 to 40, maximum to
the return value of max() method and minimum to the return value of min()
method. In java, we use the following syntax to use the static methods
provided by a class. If you have no idea of what a static method is, don’t
worry. I will explain it in later chapters.
Example
public class MathMethods {
public static void main(String[] args) {
int num1 = 20;
int num2 = 40;
int maximum;
int minimum;
The output:
Largest number is 40
Smallest number is 20
In this example, we use abs() method to find the absolute value of the
variable initial and and sqrt() methos to find the square root of the
absolute value of the initial.
Example
public class MathMethods2 {
public static void main(String[] args) {
double initial = -225;
double absoluteValue;
double squareRoot;
absoluteValue = Math.abs(initial);
squareRoot = Math.sqrt(absoluteValue);
}
}
The output:
Initial value is -225.0
Absolute value of the initial is 225.0
Square root of the absoluteValue is 15.0
Example
public class MathMethods3 {
public static void main(String[] args) {
The output:
sin^2(x) + cos^2(x) = 1.0
Booleans
In java, a boolean is a data type that has either true or false value. It is used to
resresent the truth values of logic and Boolean algebra. A boolean type is declared
with the keyword boolean.
Boolean Expression
A Boolean expression is an expression that produces a Boolean value when
evaluated. It has two literal constants true and false. You can test the data if
it is equal to, greater than or less than other data.
Example
public class Booleans {
public static void main(String[] args) {
int number = -10;
boolean isNegative;
The output:
-10 is negative: true
The output:
37 is multiple of three: false
The if Statement
The if statement is used to specify that a block of code will get executed when
the condition is true.
Example
public class If {
public static void main(String[] args) {
int number = -10;
if(number < 0) {
System.out.println(
"You entered a negative number");
}
System.out.println("You entered " + number);
}
}
The output:
You entered a negative number
You entered -10
When we change the number to a positive integer, the block of code within
the if statement won’t get executed.
Example
public class If2 {
public static void main(String[] args) {
int number = 10;
if(number < 0) {
System.out.println(
"You entered a negative number");
}
System.out.println("You entered " + number);
}
}
The output:
You entered 10
The If statement may have optional else block. If the test condition
evaluates to true, the block of code within the If statement will get
executed, otherwise inside the body of the else statement will get
executed.
Example
public class IfElse {
public static void main(String[] args) {
int number = 10;
if(number == 0) {
System.out.println("You entered 0");
}
if(number < 0) {
System.out.println(
"You entered a negative number");
}
else {
System.out.println("You entered a positive number");
}
}
}
The output:
You entered a positive number
We could write the code above using nested if else statement.
Example
public class IfElseif {
public static void main(String[] args) {
int number = -10;
if(number == 0) {
System.out.println("You entered 0");
}else if(number < 0) {
System.out.println(
"You entered a negative number");
}
else {
System.out.println("You entered a positive number");
}
}
}
The output:
You entered a negative number
Example
public class Conditionals {
public static void main(String[] args) {
int number = 23;
if(number == 0) {
System.out.println("0 is unsigned even number");
}
else if(number > 0) { // check if it is positive or negative
if(number % 2 == 0) {
System.out.println("It's a positive even number");
}
else {
System.out.println("It's a positive odd number");
}
}
else {
if(number % 2 == 0) {
System.out.println("It's a negative even number");
}
else {
System.out.println("It's a positive odd number");
}
}
}
}
The expression in the paranteses is called the condition. Because the
first condition is false, the flow of execution will skip over the block
of the code in braces. Since 23 is greater than 0, the second if
statement will get executed. It has two possibilites indicated by if and
else. If the condition is true the first statement will get executed. If
it is false the second statement will get executed. Since the expression
“number % 2 == 0” is false.The second statement will get executed. The
program will output “It is a positive odd number”.
Example
public class FindMaximumNumber {
public static void main(String[] args) {
int x, y, z;
x = 19;
y = 23;
z = 37;
int max = x;
max = (max < y) ? y : max;
max = (max < z) ? z : max;
System.out.println("The largest number is " + max);
}
}
The output:
The largest number is 37
Switch Statement
The switch statement performs different actions based on a value or
expression. Every case ends with a break statement. When a break statement
is reached, the switch statement terminates. There is also an optional default
case which is used to perform a task when there is no case match.
We can use multiple cases when we want to perform the same action.
Example
public class Switch {
public static void main(String[] args) {
String month = "october";
switch(month) {
case "december":
case "january":
case "february":
System.out.println("WINTER");
break;
case "november":
case "october":
case "september":
System.out.println("FALL");
break;
case "june":
case "july":
case "august":
System.out.println("SUMMER");
break;
case "march":
case "aprill":
case "may":
System.out.println("SPRING");
break;
default:
System.out.println("Enter a valid month");
}
}
}
The output:
FALL
In the example below, since there is no case match, default case will get
executed.
Example
public class Switch2 {
public static void main(String[] args) {
String month = "invalid month";
switch(month) {
case "december":
case "january":
case "february":
System.out.println("WINTER");
break;
case "november":
case "october":
case "september":
System.out.println("FALL");
break;
case "june":
case "july":
case "august":
System.out.println("SUMMER");
break;
case "march":
case "aprill":
case "may":
System.out.println("SPRING");
break;
default:
System.out.println("Enter a valid month");
}
The output:
Enter a valid month
While Loop
The while loop loops through a block of code as long as a specified condition is
true.
Example
//This program calculates the sum of the odd numbers smaller 10
public class WhileExample {
public static void main(String[] args) {
int i = 1;
int sum = 0;
//while the condition is true increase the sum by the value of i
while (i < 10) {
sum += i;
i += 2;
}
System.out.println(sum);
}
}
The output:
25
The Do/While Loop
Do-while loop executes a block of code at least once, then repeatedly executes
the block of code, or not depending on the return value of test condition. Use it
when you need to execute the body of the loop at least once.
The examples below uses a do-while loop.
Example
public class DoWhile {
public static void main(String[] args) {
boolean shouldContinue = false;
do {
System.out.println("I got the chance of"
+ " getting executed!");
}while(shouldContinue);
}
}
The output:
I got the chance of getting executed!
Example
public class DoWhile2 {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i *= 3;
}while(i < 100);
}
The output:
1
3
9
27
81
For Loop
For loop is used to execute a block of code known number of times. It has the
following syntax:
for (initialization; condition; increment){
//nested-statements
}
• Initialization is evaluated first.
• Condition is tested before each iteration of the loop.
• Increment is evaluated at the end of each iteration.
The example below will display the integers between 0 and 10.
Example
public class ForLoop {
public static void main(String[] args) {
int iterationCount = 0;
for(int number = 0; number < 10; number += 2) {
iterationCount++;
System.out.println(iterationCount + ". iteration " +
number);
}
}
}
The output:
1. iteration 0
2. iteration 2
3. iteration 4
4. iteration 6
5. iteration 8
Example
public class ForLoop {
public static void main(String[] args) {
// don't define the variable as an int
// remember that long has a greater range
long fact = 1;
for(int i = 1; i <= 10; i++) {
fact *= i;
}
System.out.println(fact);
}
}
The output:
3628800
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements. It has the following syntax:
for (type variable : array)
{
//statements using variable;
}
In the following example we find the maximum value of an array using for-
each loop. We assume that the first element has the largest value, then loop
through the elements in array comparing them to find the largest value in the
array.
Example
public class ForEach {
public static void main(String[] args) {
int[] values = {37, 43, 68, 91, 17, 22, 77};
The output:
Maximum value in the array: 91
Break
Break statement is used to terminate the execution of the statements in a
loop. When the flow of control reaches to the break statement. The execution
proceeds to the statement that follows the enclosing loop.
Example
public class BreakInFor {
public static void main(String[] args) {
for(int i = 1; i < 100; i *= 3) {
System.out.println(i);
if(i == 9) {
break;
}
}
}
}
The output:
1
3
9
In the example above, the loop will terminates after third iteration.
Continue
Continue statement is different from the if statement. breaks one iteration in
the loop when the specified condition occurs, and continues with the next
iteration in the loop.
The axample below doesn’t display the value of 9.
Example
public class ContinueInFor {
public static void main(String[] args) {
for(int i = 1; i < 100; i *= 3) {
if(i == 9) {
continue;
}
System.out.println(i);
}
}
}
The output:
1
3
27
81
Example
public class BreakInWhile {
public static void main(String[] args) {
int i = 1;
while(i < 100) {
System.out.println(i);
i *= 3;
if(i == 27) {break;}
}
}
}
The output:
1
3
9
Example
public class ContinueInWhile {
public static void main(String[] args) {
int i = 1;
The output:
1
3
9
81
Arrays
An array is a sequence of values of the same type. Values in the array can’t
have different types. To create an array, you declare a variable with a type
which is followed by square brackets. To access the elements of an array, we
use indexes which are used to identify different locations in the array.
In this example, we create an array of type int to hold the integer values. We
then iterate through the array to find the indexes of 100s and their count.
Example
public class ArrayExample {
public static void main(String[] args) {
int [] grades = {34, 57, 62, 18, 46, 100, 100};
int count = 0;
// indexes start from 0 not 1
int index = 0;
The output:
Clever student found at index 5
Clever student found at index 6
There are total 2
Example
public class ArrayExample2 {
public static void main(String[] args) {
int [] numbers = new int[7];
System.out.print("numbers: ");
display(numbers);
System.out.print("evenNumbers: ");
display(evenNumbers);
changeArray(evenNumbers);
System.out.print("Changed numbers: ");
display(numbers);
}
The output:
numbers: {0, 2, 4, 6, 8, 10, 12}
evenNumbers: {0, 2, 4, 6, 8, 10, 12}
Changed numbers: {2, 4, 6, 8, 10, 12, 14}
Example
import java.util.Arrays;
public class ArrayManipulation{
public static void main(String[] args){
if (index >= 0)
System.out.printf("Found 7 at element %d in primes%n",
index);
else
System.out.println("7 is not in primes");
if (index >= 0) {
System.out.printf("Found 567 at element %d in primes%n",
index);
}
else {
System.out.println("567 is not in primes");
}
// sort doubleNums into ascending order
double[] decimalNums = { 11.4, 7.1, 5.3, 2.8, 9.6 };
Arrays.sort(decimalNums);
The output:
8 8 8 8 8 8
1 2 3 5 7 11
1 2 3 5 7 11
Is primes equal to primesCopy: yes
Is primes equal to primesFilled: no
Found 7 at element 4 in primes
567 is not in primes
Sorted decimalNums: 2.8 5.3 7.1 9.6 11.4
Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).
We can use try and catch to catch the error and execute the code within the
catch to handle it
Example
public class Exceptions {
public static void main(String args[]){
int number1 = 10;
int number2 = 0;
catch(ArithmeticException e) {
// getMessage() returns the detail message string
System.out.println(e.getMessage());
}
}
// It throws the Exception(ArithmeticException).
static int divide(int num1, int num2){
int result = num1 / num2;
return result;
}
catch(NumberFormatException e) {
System.out.println("NumberFormatException");
}
return res;
}
}
The output:
/ by zero
Finally
finally keyword is used to gurantee that a code block will be executed in any
condition. finally block is executed whether or not an exception occur, as you
can see in the example below.
Example
public class TestFinallyBlock{
public static void main(String args[]){
try{
int divide = 100 / 10;
System.out.println("division completed: "
+ "result is " + divide);
}
//Since there is no exception
//catch block won't get executed
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block gets "
+ "always executed");
}
Example
import java.util.Scanner;
public class Throw {
public static void main(String[] args) {
System.out.print("Give me an integer: ");
try{
if (integer < 0) {
throw new RuntimeException();
}
// if not less then zero
System.out.println("Square root of the number is " +
Math.sqrt(integer));
}
catch (Exception e) {
System.out.println("Number should not be less than 0");
throw e;
}
}
}
The output:
Give me an integer: -5
Number should not be less than 0
Exception in thread "main" java.lang.RuntimeException
at Throw.main(Throw.java:11)
Methods
// method body
}
methodName is the name of the method
modifier determines the access level of the method I will access modifiers later
in the book.
returnType keyword defines the value method returns .For example a void
would indicate that the method doesn’t not return a value. If you want the
method to return a value, you can use a primitive data type such as int, char,
boolean instead of void, and use the return keyword inside the method.
Calling a methods executes the code in the method. Write the method's name
followed by two parantheses () and a semicolon. Inside the parantheses can be
empty or the method can take any number of optional parameters. Parameters
are used to pass information to methods. Parameters are specified after the
method name, inside the parentheses. You can add as many parameters as
you want, separate them with a comma.
In the example below, we define four static methods inside the class, but
outside of the main method, and call them on the main.
Example
public class Methods {
public static void main(String[] args) {
System.out.println("Is 7 divisible by 3? " +
(isDivisible(7, 3) ? "yes": "no" ));
System.out.println("Is 2019 odd or even? " +
oddOrEven(2019));
System.out.println("Absolute value of -8 is " +
absoluteValue(-8));
System.out.println("The largest value of [3,7,17] is " +
maximum(3, 7, 17));
}
The output:
Is 7 divisible by 3? no
Is 2019 odd or even? Odd
Absolute value of -8 is 8
The largest value of [3,7,17] is 17
Example
public class VariableLengthArguments {
public static void main(String[] args) {
System.out.println("maximum(10) = " +
maximum(10));
System.out.println("maximum(10, 20) = " +
maximum(10, 20));
System.out.println("maximum(10, 20, 30, 40) = " +
maximum(10, 20, 30, 40));
}
The output:
Number of arguments given: 1
maximum(10) = 10
Number of arguments given: 2
maximum(10, 20) = 20
Number of arguments given: 4
maximum(10, 20, 30, 40) = 40
Create a Class
A class is a template which specifies what attributes the objects have and what
methods are able to operate on them. Every class you create is a new type
with the same name. Objects are instantiated from classes.
Syntax
class ClassName{
// fields declaration
// methods declaration
}
Example
public class Time {
// A simple class
}
Create an Object
To create an object of Time, specify the class name, followed by the object
name, and use the keyword new.
Example
The output:
This is our first class :)
Example
public class Time {
int hour = 13;
int minute = 47;
public static void main(String[] args) {
Time time1 = new Time();
Time time2 = new Time();
The output:
time1.hour: 13
time1.minute: 47
time2.hour: 13
time2.minute: 47
As you can see both of the objects can access the instance variables in
the class.
It is also possible to crate an object of a class and access it in another class.
Class Attributes
Attributes are variables declared inside a class. Attributes are also called
instance variables, because each instance has its own copy of variables. In this
example we create a class and access its attributes using dot notation.
Example
public class Point {
double xCoordinate = 4.4;
double yCoordinate = 5.3;
public static void main(String[] args) {
Point point1 = new Point();
The output:
x: 4.4
y: 5.3
Modifing Attributes
An objects data is accessed usind dot notation, and It can be modified.
Example
public class Point {
double xCoordinate = 4.4;
double yCoordinate = 5.3;
public static void main(String[] args) {
Point point1 = new Point();
point1.xCoordinate = 6.1;
point1.yCoordinate = 7.4;
}
}
The output:
x after modified: 6.1
y after modified: 7.4
If you don't want the ability to change existing values, you should declare the
attribute as final
In the example below, we see that an exception occurs when we try to access
an attributed declared by the keyword final
Example
public class Point {
final double xCoordinate = 4.4;
final double yCoordinate = 5.3;
public static void main(String[] args) {
Point point1 = new Point();
point1.xCoordinate = 6.1;
point1.yCoordinate = 7.4;
}
}
The output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
The final field Point.xCoordinate cannot be assigned
The final field Point.yCoordinate cannot be assigned
at Point.main(Point.java:11)
Class Methods
An object’s methods can get invoked(activated) by sending messages.
In the example below, we activate the calculateDistance() method declared
with the Point class by using dot notation.
Example
public class Point {
double xCoordinate;
double yCoordinate;
public static void main(String[] args) {
Point point1 = new Point();
Point point2 = new Point();
The output:
Distance between two points is: 5.0
Static
Static variables that can be accessed without creating objects of a class. You
should define a variable as static when you want to create a variable common
to all instances of a class.
In the example above, we created two static methods that can be accessed
without creating an object of the class.
Example
}
// This method is used to calculate the distance between two points
//It takes two objects as parameters, and returns a double value
public static double calculateDistance(Point po1, Point po2) {
double deltaX = po2.xCoordinate - po1.xCoordinate;
double deltaY = po2.yCoordinate - po1.yCoordinate;
The output:
Example
The output:
point1 is (1.0,2.0)
point2 is (6.0,14.0)
Distance between two points is 13.0
Number of objects of type Point is 2
Modifiers
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
Modifiers are divided into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers – instead of controlling access level , they provide other
functionality
Non-Access Modifiers
• final: The classes declared final can’t be inherited by other classes, and the attributes and
methods cannot be modified.
• Static: Attributes and methods declared static belong specifically to the class, rather than
instances of that class.
• abstract: It is used in abstract classes. Abstact classes The method does not have a body, for
Final
If an instance variable should not be modified, declare as final to prevent any
erroneous modification.
In the example below, I declare PI as a final to prevent any erroneous
modification.
Example
public class Circle {
private double radius;
public final double PI = 3.14;
The output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
The final field Circle.PI cannot be assigned
at Circle.main(Circle.java:14)
Encapsulation
Four fundamental concepts that define object oriented programming are
abstraction, encapsulation, inheritance and polymorphysm. Users of a class
don’t need to know the actual implementation of a class, and also they
should’nt be allowed the change the data in the class. Encapsulation let us hide
the actual implementation from the users of a class. Encapsulation are
achieved by:
• declaring class variables as private to let them be only accessible within a
class.
• providing public setter and getter methods to access and update the value of
private variables.
Example
The output:
The current date is (13-1--2019)
The new date is (13-1--2020)
Java was released in 1995
Encapsulation let us have a better control of class attributes and methods. It
gives us the ability of changing one part of the code without affecting other
parts. We can make class attributes read-only or write-only by omitting the
corresponding set and get methods to increase the security
Built-in Packages
The Java API consists of prewritten classes ncluded in the Java Development
Environment for managing input/output, database programming, networking
etc.
The Java API is divided into packages and classes. You can either import a
single class along with its methods and attributes, or a whole package that
contain all the classes that belong to the specified package.
To include a class or a package in the library to your, you need to import it as
shown below.
import package.name.class;
import package.name.*;
Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code In the example below, java.util
is a package, while Scanner is a class of the java.util package.
In the example below we use the Scanner class, we create an object of the
class and use the nextLine() method to read a complete line, available in the
Scanner class.
Example
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
The output:
Please type something
something
You typed: something
Import a Package
The class we used in the previous example resides in the java.util package.
This package contains utility classes you can import to your program.
To import a whole package, end the sentence with an asterisk sign (*). The
following example will import ALL the classes in the java.security package
import java.security.*;
// Provides the classes and interfaces for the security framework
User-defined Packages
Package name tells compiler path name for directory containing classes of
package To create your own package, you should use the keyword package.
└── root
└── package
└── packageClass.java
Example
package UserDefinedMathPackage;
Example
import UserDefinedMathPackage.Mathematics;
public class PackageTest {
public static void main(String[] args) {
}
}
The output:
25.2 + 44.3 = 69.5
1 + 1 = 2
Inheritance
Inheritance is a way of software reuse in which a new class is created by
absorbing an existing class’s attributes and methods and modifing them to add
new capabilities. Inheritance lets us base our new classes (subclass) on
existing classes (super class).
Subclass is the class that inherits from another class on the other hand
superclass is the class being inherited from.
The subclass can inherit the behaviors of its superclass and can add new
behaviors specific to the subclass, but constructors are not inhereted.
To inherit from a class, use the extends keyword.
In the example below, the Calculator class (subclass) inherits the members of
the Functions class (superclass):
Example
public class Functions {
double result;
public void add(double num1, double num2) {
result = num1 + num2;
System.out.println("Sum is " + result);
}
calculator1.add(num1, num2);
calculator1.subtract(num1, num2);
calculator1.multiply(num1, num2);
calculator1.divide(num1, num2);
}
}
The output:
Sum is 28.0
Difference is 20.0
Product is 96.0
Quotient is 0.0
Polymorphism
Polymorphism enables you to write programs that process objects that share
the same superclass as if they’re all objects of the superclass; this can simplify
programming.
Inheritance lets us inherit attributes and methods from another class.
Polymorphism uses those methods to perform different tasks. This allows us to
perform a single action in different ways.
In the example below, we create a class called Geometric object that has two
subclasses. Its subclasses RightTriangle and Square also have their own
implementation of the calculatePerimeter() method. Polymorphism enables us
to define new RightTriangle and Square objects as if they were objects of
GeometricObject class.
Example
class GeometricObject{
protected int numberOfSides;
protected int sideLength;
}
}
System.out.println(pentagon.calculatePerimeter());
System.out.println(square.calculatePerimeter());
System.out.println(triangle.calculatePerimeter());
}
}
The output:
Object perimeter: 50
Square perimeter: 40
Triangle perimeter: 30
Interface
An interface is an contract that guarantees that the system will have certain
functionalities. An interface is an abstract type that is used to specify a
behavior that classes must implement. When a class implemets an interface, It
inherits the methods of the interface. Methods in an interface must be public
and abstract but these keywords can be omitted
In this example, We have an interface and a class that implements the
interface. Any class that implements an interface must implement all methods
of the interface with the implements keyword.
Example
public interface Drawable {
void info();
void draw(int length);
The output:
*
***
*****
*******
It has 3 sides
Multiple Interfaces
In Java It is allowed for a class to implement multiple interfaces. You should
separate them with a comma to implemet multiple interfaces.
Example
public class RightTriangle implements Drawable, Informable{
int sides;
int length;
The output:
*
***
*****
*******
It has 3 sides
Enum
An enum is a special "class" that represents a group of constants which are
unchangeable variables.
To create an enum, use the enum keyword, and separate the constants with a
comma. Connstants in the enum should be uppercase.
In this example, we create an enum outsite of the class to represent the suits
in a deck.
Example
public class EnumExample {
public static void main(String[] args) {
Suits suit1 = Suits.CLUB;
Suits suit2 = Suits.DIAMOND;
enum Suits{
CLUB,
DIAMOND,
HEART,
SPADE
}
The output:
suit1: CLUB
suit2: DIAMOND
Example
public class EnumExample {
//As you can see
//It is possible to have an enum inside a class
enum Suits{
CLUB,
DIAMOND,
HEART,
SPADE
}
public static void main(String[] args) {
Suits suit1 = Suits.CLUB;
Suits suit2 = Suits.DIAMOND;
The output:
suit1: CLUB
suit2: DIAMOND
Example
public class EnumExample {
//As you can see
//It is possible to have an enum inside a class
enum Suits{
CLUB,
DIAMOND,
HEART,
SPADE
}
public static void main(String[] args) {
User input
Java.util.Scanner class is used to get input from the user.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class. In the example below, we will
use the nextLine() method, which is used to read Strings.
Example
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
The output:
Are you Optimistic or Pessimistic ?
optimistic
So, you are optimistic
Input Types
Example
import java.util.Scanner;
int total = 0;
int count = 0;
The output:
75
68
90
56
23
47
just a non-integer value to terminate the program
6 grades entered
The average is 59.0
string1: JAVA
string2: python
string3: JAVApython
string2 found in string3 at index 4
Example
import java.time.LocalDate;
public class DateAndTime {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate tomorrow = LocalDate.now().plusDays(1);
LocalDate yesterday = LocalDate.now().minusDays(1);
The output:
Current date is 2019-01-15
Tomorrow will be 2019-01-16
Yesterday was 2019-01-14
Current Time
In this example, we import the java.time.LocalTime class and use its now() to
display the current time in hour, minute, second, and microsecond.
Example
import java.time.LocalTime;
public class DateAndTime {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
LocalTime twoHoursAgo = currentTime.minusHours(2);
LocalTime twoHoursLater = LocalTime.now().plusHours(1);
LocalTime wokeUp = LocalTime.of(6, 15);
The output:
Current time: 16:11:08.767
2 hours ago : 14:11:08.767
2 hours later: 17:11:08.768
I woke up at 6:15
Current Date and Time
In this example, we use the now() method of java.time.LocalDateTime class to
display the current date and time.
Example
import java.time.LocalDateTime;
import java.time.Month;
public class DateAndTimeExample {
public static void main(String[] args) {
The ofPattern() method accepts all sorts of values, if you want to display the
date and time in a different format. For example
Example
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
The output:
Unformatted: 2019-01-15T17:01:16.650
Formatted: 01/15/2019-05:01 PM
Collections
We can keep group of objects in an array, but arrays are not feasible when
number of objects increase or decrease during the execution of the program.
The Java Collections Framework is a collection of interfaces and classes that
are used to manipulate groups of objects The classes implemented in the Java
Collections Framework are used as reusable data structures, and they include
algorithms for common tasks such as sorting or searching The Collections
define two major types of data structures:
ArrayList
An ArrayList provided by java.util.ArrayList class is an implementation of List
interface (java.util.List). Group of objects can be kept in an array, but arrays
don’t give us the ability of increasing or decreasing the number of objects
during execution of the program. An ArrayList gives us this ability.
In the example below, we create an ArrayList called progLanguages and
manipulate it. Instead of writing “ArrayList<String> progLanguages = new
ArrayList<String>();” We could write “List<String> progLanguages = new
ArayList<String>();”. Remember polymorphism.
Example
import java.util.ArrayList;
public class ExampleArrayList{
public static void main(String[] args){
// create a new ArrayList of Strings
ArrayList<String> progLanguages = new ArrayList<String>();
The output:
ArrayList content: JAVA PHP JAVA PHP
JAVA PHP Python PHP
JAVA Python PHP
JAVA PHP
Does the list contain C not
Size: 2
HashSet
A Set is a collection that has no duplicate elements. A hashSet is one of the
Set implementations in the collections framework.
Don’t let the notation “<>” confuse you. It is used to specify parameter type.
In the following example we create two major Sets called primes and odds,
and four additional Sets to show mathematical set operations. And we use
addAll() method which is used to add all of the elements in a specified
collection. asList() method returns a fixed size list backed by the specified
array. We pass the list returned by asList() method to the addAll() method as
argument.
Example
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class SetExample {
public static void main(String args[]){
Set<Integer> primes = new HashSet<Integer>();
primes.addAll(Arrays.asList(1, 2, 3, 5, 7, 11, 11));
// Difference
Set<Integer> difference = new HashSet<Integer>();
difference.addAll(primes);
difference.removeAll(odds);
// Complement
Set<Integer> complement = new HashSet<Integer>();
complement.addAll(primes);
complement.removeAll(odds);
The output:
odds: [1, 3, 5, 7, 9, 11]
Union: [1, 2, 3, 5, 7, 9, 11]
Intersection: [1, 3, 5, 7, 11]
Difference: [2]
Complement: [2]
HashMap
Maps are used to associate keys to values and cannot contain duplicate keys.
Maps differ from Sets in that Maps contain keys and values, whereas Sets
contain only value. A HashMap is an implementation of the Map interface.
HashMap is used to instantiate objects that stores collection of key-value
pairs. Items in the HashMap are unordered. Keys and values in a HashMap
are actually objects.
In the examples below, we used keys of type String and values of type
Integer. AString in Java is an object which is not a primitive type. To use other
types, such as int, you must specify an equivalent wrapper class: Integer. For
other primitive types, use: Boolean for boolean, Character for char, Double for
double.
Add Items
put() method associates the specified value with the specified key in this map.
Use it to add items to the hashMap.
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
The output:
Entries in the HashMap:
{Warren Bufet=88, Elon Musk=47, Jeff Bezos=55, Bill Gates=63}
Access an Item
get() methods return the value to which the specified key is mapped. In the
example below, we access the age of Elon Musk.
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
The output:
Elon Musk is 47 years old.
Removing an Item
remove() method removes the item specified by its key.
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
billionaires.remove("Elon Musk");
System.out.println("New HasMap");
System.out.println(billionaires);
}
}
The output:
New HasMap:
{Warren Bufet=88, Jeff Bezos=55, Bill Gates=63}
In this example, we use clear() method to delete all of the items in the
hashMap.
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
billionaires.clear();
System.out.println("Empty HasMap:");
System.out.println(billionaires);
}
}
The output:
Empty HasMap:
{}
HashMap Size
To find out how many items in the hashMap, use its pre-defined size() method.
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
The output:
There are total 4 billionaires in our HashMap
Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();
int total = 0;
The output:
Warren Buffet: 88
Elon Musk: 47
Jeff Bezos: 55
Bill Gates: 63
Total age is 253
Files
Files are vieved as sequential stream of bytes in Java. Because data stored in
variables is temporary, It is lost when the program terminates. Files are used
to permanenly store the data in the program.
java.io.File Description
File(pathname: String) Creates a File object for the specied path name.
File(parent: String, child: String) Creates a File object for the subclass under the
directory parent.
exists(): boolean Returns true if the file represented by the File
object exists.
canRead(): boolean Returns true if the file represented by the File
object exists and can be read.
Example
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File fileObject = new File("learnJavaByExamples.txt");
if(fileObject.exists()) {
System.out.println(fileObject.isDirectory() ?
"It is a directory" : "It is not a directory");
System.out.println(fileObject.isAbsolute() ?
"It is a absolute path name" : "It is a relative
path name" );
System.out.println("Last modified on " +
new java.util.Date(fileObject.lastModified()));
System.out.println("The file's length is " +
fileObject.length() + " bytes");
System.out.println(fileObject.isFile() ?
"It is a file" : "It is not a file");
System.out.println(fileObject.isHidden() ?
"It is hidden" : "It is not hidden");
System.out.println(fileObject.canWrite() ?
"It can be written" : "It can not be written");
System.out.println(fileObject.canRead() ?
"It can be read" : "It can not be read" );
System.out.println("Absolute path is " +
fileObject.getAbsolutePath());
}
}
}
Write To a File
We will use java.io.PrintWriter class to write to a file.
In the following example, we use the PrintWriter class together with its print()
method to write some text to the file we created in the example above. Note
that when you are done writing to the file, you should close it with the close()
method:
Example
import java.io.PrintWriter;
import java.io.File;
public class WriteToFile {
public static void main(String[] args) throws java.io.IOException
{
File fileObject = new File("students.txt");
if (fileObject.exists()) {
System.out.println("It already exists");
System.exit(1);
}
// Creates a file
PrintWriter output = new PrintWriter(fileObject);
Read a File
java.io.Scanner Description
Scanner(source: File) Creates a Scanner that produces values scanned
from the specied le.
Scanner(source: String) Creates a Scanner that produces values scanned
from the specied string.
close() Closes this scanner.
hasNext() Returns true if this scanner has more data to be
read.
next() Returns next token as a string from this scanner.
nextLine() Returns a line ending with the line separator from
this scanner.
nextByte() Returns next token as a byte from this scanner.
nextShort() Returns next token as a short from this scanner.
nextInt() Returns next token as an int from this scanner.
nextLong() Returns next token as a long from this scanner.
nextFloat() Returns next token as a float from this scanner.
nextDouble() Returns next token as a double from this scanner.
useDelimeter() Sets this scanner’s delimiting pattern and returns
this scanner.
In the following example, we use the Scanner class to read the contents of the
text file.
Example
import java.io.File;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws Exception {
// Create an instance of File class
File fileObject = new File("students.txt");