Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Software Engineer - Learn Java by Examples (2019)

Java is a programming language and platform that was originally developed by Sun Microsystems and is now owned by Oracle. It allows software to be written once and run on any device without modification. The Java Development Kit contains tools for developing Java applications and the Java Runtime Environment runs Java applications. Common uses of Java include mobile apps, web apps, servers, and more.

Uploaded by

Руслан
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Software Engineer - Learn Java by Examples (2019)

Java is a programming language and platform that was originally developed by Sun Microsystems and is now owned by Oracle. It allows software to be written once and run on any device without modification. The Java Development Kit contains tools for developing Java applications and the Java Runtime Environment runs Java applications. Common uses of Java include mobile apps, web apps, servers, and more.

Uploaded by

Руслан
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

What is Java?

Java is a technology which is both a programming language and a platform,


developed by a team led by James Gosling at Sun Microsystems for use in
embedded chips in comsumer electronics. It was redesigned for web
applications in 1995.
Sun Microsystems was purchased by Oracle in 2010. Java is owned by Oracle
since then. According to Oracle more than 3 billion devices run Java.

How Java Works?


In java, all source code is first written in plain text files ending with the .java
extension. The source files are then compiled into .class files by the javac
compiler. A .class file contains bytecodes intead of containig code native to
your processor. The java launcher tool then runs your application with an
instance of the Java Virtual Machine Your program is run by Java Virtual
machine.

How to Start Development with Java?


The Java Development Kit (JDK) is a software development environment used for
developing Java applications. The Java Runtime Environment(JRE) provides the minimum
requirements for executing a Java application. JRE is a subset of the JDK. To be able to
develop java applications you need JDK to be installed on your computer. Go to
https://www.oracle.com/technetwork/java/javase/downloads to download JDK.

Where Is Java used?


Today Java is mainly used for:
• Mobile applications
• Desktop applications
• Web applications
• Servers applications at Financial Services Industry
• Database connection
• Big Data technologies
• Scientific Computing
Java Buzzwords
Object Oriented − Because everything is an Object in Java, It is an ideal
platform to produce object oriented software.

Platform Independent − Because applications written in the Java


programming language are compiled into machine-independent bytecodes,
they run consistently on any Java platform.

Architecture-neutral − Java generates code for a virtual machine.


architecture-neutral object file format generated by the Java compiler makes
the compiled code executable on many systems, with the presence of Java
runtime system.

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.

Secure − Because Java is intented to be used in networked/distributed


environments, a lot of emphasis has been placed on security. Java enables to
develop virus-free, tamper-free systems.

Robust −The Java compiler detects many problems before showing up on run
time to eliminate error prone situations.

Multithreaded −This design feature allows developers to write programs that


can perform many tasks simultaneously.

Compiled and Interpreted − Source code written in Java is compiled to an


intermediate representation called Java Bytecode. Bytecode is then interpreted
by a Java Virtual Machine to produce machine code that can be executed by
the machine.

High Performance − The Just-In-Time compilers improve the performance of


Java applications by compiling Bytecodes to machine code at run time.

Distributed − A distributed application is run on multiple computers across


the internet. Java is designed for the distributed environment of the internet
with the help of extensive library of routines for dealing with TCP/IP protocols.

Dynamic − Anything that happens at run time is considered as dynamic. Java


is considered dynamic, since Java programs can carry extensive amount of
run-time information that can be used to verify and resolve accesses to objects
on run-time.
Java Syntax
ExampleClass.java
/*
* Name this file ExampleClass.java
*
* What it is capable of doing is to display a text on the screen :)
*/
public class ExampleClass {
public static void main(String[] args) {
System.out.println("Java is fun!"); // Prints the text on the
console
}

Save the code in your text editor as "ExampleClass.java". Open Command


Prompt (cmd.exe), go to the directory where you saved your file, and type
"javac ExampleClass.java”:
C: path to where you saved your file> javac ExampleClass.java

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.

"System.out.println("Java is fun!")”; This is the line that does the actual


work. It simply displays the text “Java is fun!” with the help of println()
method. System is a predefined class that provides access to the system, and
out is the output stream that is connected to the console.

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) {

int year = 2019;


// do not forget to put the "f" at the end of the number
float aFloat = 7.14f;
// floating point numbers are treated as doubles by default in
Java.
double radius = 9.73;
//Use only single quotes for variables of type char
char grade = 'A';
boolean isTrue = false;
String aText = "It is worth learning Java";

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.

Primitive Data Types


These are predefined by the Java programming language and named by
reserved keywords listed below.
Type Size Range
• Byte 1 byte -128 to 127
• short 2 bytes -32,768 to 32,767
• int 4 bytes -2,147,483,648 to 2,147,483,647
• long 8 bytes 9,223.372,036.854,775.808 to
9,223.372,036,854,775,808
• float 4 bytes 3.4e−038 to 3.4e+038
• double 8 bytes 1.7e−308 to 1.7e+038
• boolean 1 byte true or false
• char 2 bytes Stores a single character/letter

Non-Primitive Data Types


Non-primitive data types reference a memory location where data is stored.
Non-primitive data types are not predefined in the language. They are created
by the programmer. Strings, Arrays, Classes, Interfaces are examples to
non-primitive data types.
Operators
Arithmetic Operators
Arithmetic operators are used to represent mathematical computations like
addition subtraction, multiplication and division.
Operation Operator Description
Addition + Finds the sum of numeric
operands
Subraction - Subtracts two operands
Multiplication * Finds the product of
operands
Division / Divides one value by
another
Modulus % Finds the remainder left
over when one operand
divided by another operand
Increment ++ Adds one to its operand
Decrement -- Substacts one from its
operand.

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

Equality and Relational Operators


Comparison operators are used to compare two values:
Operation Operator Description
Equality == Returns true if both
operands are equal
Inequality != Returns false if both
operands are equal
Greater than > Returns true if the first
operand is greater than the
secons operand
Less than < Returns false if the first
operand is greater than the
second operand
Greater than or equal to >= Returns true if the first
operand is greater than or
equal to the second
operand
Less than or equal to <= Returns false if the first
operand is greater then or
equal to the second
operand

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();

// Invoking toLowerCase() and toUpperCase()


// doesn’t change the string1 and string2
// these methods return new strings
string1.toLowerCase();
string2.toUpperCase();
// string3 = string1 + sintring2
string3 = string1.concat(string2);

System.out.println("string1 is " + string1);


System.out.println("string1.toLowerCase() is " +
string1.toLowerCase());
System.out.println("string2 is " + string2);
System.out.println("string2.toLUpperCase() is " +
string2.toUpperCase());
System.out.println("Length of string3 is " +
string3.length());
}
}

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

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();

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;

maximum = Math.max(num1, num2);


minimum = Math.min(num1, num2);

System.out.println("Largest number is " + maximum);


System.out.println("Smallest number is " + 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);

System.out.println("Initial value is " + initial);


System.out.println("Absolute value of the initial is " +
absoluteValue);
System.out.println("Square root of the absoluteValue is " +
squareRoot);

}
}
The output:
Initial value is -225.0
Absolute value of the initial is 225.0
Square root of the absoluteValue is 15.0

In this example, I want to proove that sin^2(x) + cos^2(x) = 1 using


Java’s pre-defined trigonometric functions.

Example
public class MathMethods3 {
public static void main(String[] args) {

// Give whatever value you want to the angle


// The result will not change
int angle = 60;
double cos = Math.cos(angle);
double sin = Math.sin(angle);
// A famous trigonometric equation
// sin^2(x) + cos^2(x) = 1
double result = Math.pow(cos, 2) + Math.pow(sin, 2);

System.out.println("sin^2(x) + cos^2(x) = " + result);


}
}

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;

// Check if it is smaller than 0


isNegative = (number < 0); //true

System.out.println("-10 is negative: " + isNegative);


}
}

The output:
-10 is negative: true

In the example below, The expression (number % 3 == 0) returns a boolean


value which is either true or false. We assign that value to the variable
isMultipleOfThree and display it on the console.
Example
public class Booleans2 {
public static void main(String[] args) {
int number = 37;
boolean isMultipleOfThree;

// Check if the remainder of 37 divide 3 is 0


isMultipleOfThree = (number % 3 == 0); //false

System.out.println("37 is multiple of three: " +


isMultipleOfThree);
}
}

The output:
37 is multiple of three: false

Conditions and If Statements


Conditional statements let us check for conditions and react accordingly. Java
supports the usual logical conditions from mathematics:
•x == y // x is equal to y
•x != y // x is not equal to y
•x > y // x is greater than y
•x < y // x is less than y
•x >= y // x is greater than or equal to y
•x <= y // x is less than or equal to y
The conditional statements in java are if, else, else if and switch.

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”.

Short Hand If...Else (Ternary Operator)


Ternary operator takes three operands, and It is used as a shortcut for if
statement.
In this example, we assign max to the largest value and min to the smallest
value. To decide which value is the largest, we first assume that the x has the
largest value and assign it to the max, then we use the ternary operator to
check if x is less then y. If the condition evaluates true, then max will be
assigned to y, otherwise max will stay unchanged. Because x is less than y,
max will be assigned to y. In the next line we use ternary operator again to see
if max is less than z. Since max is less than z. max will get assigned to z.

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

In this example, we calculate the factorial of 10 using for-loop. In every


iteration, fact gets multiplied by the loop initial variable which is incremented
by one in every iteration. 10! = 1*2*3*4*5*6*7*8*9*10 = 3628800

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};

int maximum = values[0];

for(int value : values) {


if(value > maximum) {
maximum = value;
}
}

System.out.println("Maximum value in the array: " +


maximum);
}
}

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

Break and Continue in While Loop


There is no difference in the use of break and continue in the while loop.

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;

while(i < 100) {


System.out.println(i);
i *= 3;
if(i == 27) {
i *= 3;
continue;
}
}
}
}

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;

for(int grade : grades) {


if(grade == 100) {
count++;
System.out.println("Clever student found at index”+
index);
}
// It is important where we place this statement
index++;
}
System.out.println("There are total " + count);
}
}

The output:
Clever student found at index 5
Clever student found at index 6
There are total 2

In the example below, We create an array, and we let two different


variables (numbers, evenNumbers) refer to the same array. Variable names
are just references to the array itself. In Java, an array is an object.
An object is a collection of data, also called attribute, that provides
methods acting on the data. length is an attribute of the array object
numbers. It holds the count of the items in an array.

Example
public class ArrayExample2 {
public static void main(String[] args) {
int [] numbers = new int[7];

for(int index = 0; index < numbers.length; index++) {


numbers[index] = index * 2;
}

int [] evenNumbers = numbers;

System.out.print("numbers: ");
display(numbers);

System.out.print("evenNumbers: ");
display(evenNumbers);

changeArray(evenNumbers);
System.out.print("Changed numbers: ");
display(numbers);
}

//This method displays the elements of the given array


//We could also define its return type as String
//and return a string value
public static void display(int[] array) {
System.out.print("{" + array[0]);
for (int index = 1; index < array.length; index++) {
System.out.print(", " + array[index]);
}
System.out.println("}");
}
// We define these methods outside of the main method
// They should be inside of the class
public static void changeArray(int[] array) {
for(int index = 0; index < array.length; index++) {
array[index] = index * 2 + 2;
}
}
}

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}

java.util.Arrays class contains static methods to crate and manipulate


arrays in the following example, we will create and manipulate arrays
using methods provided by java.util.Arrays class.

Example
import java.util.Arrays;
public class ArrayManipulation{
public static void main(String[] args){

// fill 6-element array with 8s


int[] primesFilled = new int[6];
Arrays.fill(primesFilled, 8);
display(primesFilled);

// copy array intArray into array intArrayCopy


int[] primes = { 1, 2, 3, 5, 7, 11 };
int[] primesCopy = new int[primes.length];
System.arraycopy(primes, 0, primesCopy, 0, primes.length);
display(primes);
display(primesCopy);

// compare primes and primesCopy for equality


boolean isEqual = Arrays.equals(primes, primesCopy);
System.out.println("Is primes equal to primesCopy: " +
(isEqual ? "yes" : "no"));
//check if primes and filledIntArray are equal
isEqual = Arrays.equals(primes, primesFilled);
System.out.println("Is primes equal to primesFilled: " +
(isEqual ? "yes" : "no"));

// search the given array for a specific value


int index = Arrays.binarySearch(primes, 7);

if (index >= 0)
System.out.printf("Found 7 at element %d in primes%n",
index);
else
System.out.println("7 is not in primes");

// search primes for the value 567


index = Arrays.binarySearch(primes, 567);

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);

System.out.print("Sorted decimalNums: ");

for (double number : decimalNums) {


System.out.print(" " + number);}

// display the array


public static void display(int[] array){
for (int number : array)
System.out.print(number + " ");
System.out.println();
}
}

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).

Try and catch


A try block contains statements where an exception can occur. be tested for
errors while it is being executed. The catch statement is used to define a block
of code to get executed, if an eexception occurs in the try block. A catch block
always follows a try block.
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

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;

try{ int result = divideCheck(number1, number2); }

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;
}

static int divideCheck(int num1, int num2) {


int res = 0;
try{ res = divide(num1, num2); }

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");
}

System.out.println("No exception was caught");


}
}
The output:
division completed: result is 10
finally block gets always executed
No exception was caught

The throw keyword


The throw statement is used to create a custom error. It is used together with
an exception type. Some of the exception types in Java are
ArithmaticException, ClassNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException, etc
In the following example, we simply create a RunTime exception and throw it
in the try block, we catch the exception in the following catch stament and
display it on the screen.

Example
import java.util.Scanner;
public class Throw {
public static void main(String[] args) {
System.out.print("Give me an integer: ");

Scanner input = new Scanner(System.in);


int integer = input.nextInt();

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)

When we give the integer 5:


Give me an integer: 5
Square root of the number is 2.23606797749979

Methods

A method packages up and names a computation to re-use of the computation.


Methods enable us write easier to understand and less error-prone code.
Methods must be declared within a class. It is defined with the name of the
method, followed by parantheses (). In Java, you can create your own
methods to perform certain actions. It has the followimg syntax.
Modifier returnType methodName(Parameter list){

// 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));
}

//check whether num1 modulo num2 = 0 will evaluate a true or false


static boolean isDivisible(int num1, int num2) {
return (num1 % num2 == 0);
}

static String oddOrEven(int num) {


//remember ternary operator
return (num % 2 == 0 ? "Even" : "Odd");
}

static int absoluteValue(int num) {


return num < 0 ? -(num) : num;
}

static int maximum(int num1, int num2, int num3) {


int max = num1 < num2 ? num2 : num1;
max = num2 < num3 ? num3: num2;
return max;
}
}

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

Variable Length Arguments


We use variable length arguments when we want a function to handle variable
number of variables according to requirement. It is a feature that allows a
function to receive any number of arguments. A variable length argument is
specified by three periods(...).
In the example below, we define maximum() that takeks variablenumber of
arguments. ... rest means that arguments given to the function will be stored
in an array referenced by the variable rest. Since, rest is actually a reference
to an array we can use index notation to acces the first element in the
array(rest[0]). We can use length(rest.length) property to get the length of the
array.

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));
}

public static int maximum(int... rest) {


int largest = rest[0];
for(int number : rest) {
if(number > largest) {
largest = number;
}
}

System.out.println("Number of arguments given: " +


rest.length);
return largest;
}
}

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

Classes and Objects


An object is a collection of data that provides a set of methods acting on them.
Java is an object-oriented programming language, which means that it uses
objects to represent data and provides methods that operate on that data.
Everything in Java is associated with classes and objects, along with its
attributes and methods. In, object oriented programming a class is a blueprint
for creating objects. Attributes are variables declared in the class also called
fields or instance variables. Every object has its own copy of these instance
variables.

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

public class Time {


String message = "This is our first class :)";
public static void main(String[] args) {
Time time = new Time();
System.out.println(time.message);
}
}

The output:
This is our first class :)

In the example above we created an instance of the Time class, and we


accessed the class’ instance variable using dot notation. It is also
possible to create multiple objects of a class.
In the example below, we create two objects of type Time, and access their
own copy of instance methods using dot notation. You should think a class as a
type. In this example, we simply define two variables of type Time.

Example
public class Time {
int hour = 13;
int minute = 47;
public static void main(String[] args) {
Time time1 = new Time();
Time time2 = new Time();

System.out.println("time1.hour: " + time1.hour);


System.out.println("time1.minute: " + time1.minute);
System.out.println("time2.hour: " + time2.hour);
System.out.println("time2.minute: " + time2.minute);
}
}

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();

System.out.println("x: " + point1.xCoordinate);


System.out.println("y " + point1.yCoordinate);
}
}

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();

System.out.println("x: " + point1.xCoordinate);


System.out.println("y: " + point1.yCoordinate);

point1.xCoordinate = 6.1;
point1.yCoordinate = 7.4;

System.out.println("x after modified: " + point1.xCoordinate);


System.out.println("y after modified: " + point1.yCoordinate);

}
}

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();

System.out.println("x: " + point1.xCoordinate);


System.out.println("y: " + point1.yCoordinate);

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();

point1.xCoordinate = 1.0; // set the x coordinate of point1


point1.yCoordinate = 2.0; // set the y coordinate of point1

point2.xCoordinate = 4.0; // set the x coordinate of point2


point2.yCoordinate = 6.0; // set the y coordinate of point2

System.out.println("Distance between two points is: " +


calculateDistance(point1, point2));
}
// 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;

return Math.sqrt(deltaX * deltaX + deltaY * deltaY);


}
}

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

public class Point {


double xCoordinate;
double yCoordinate;
public static void main(String[] args) {
Point point1 = new Point();
Point point2 = new Point();

point1.xCoordinate = 1.0; // set the x coordinate of point1


point1.yCoordinate = 2.0; // set the y coordinate of point1

point2.xCoordinate = 4.0; // set the x coordinate of point2


point2.yCoordinate = 6.0; // set the y coordinate of point2

System.out.println("Distance between two points is: " +


calculateDistance(point1, point2));
System.out.println("Before swap operation");
System.out.println(point1.toString());
swapCoordinates(point1);
System.out.println("After swap Operation");
System.out.println(point1.toString());

}
// 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;

return Math.sqrt(deltaX * deltaX + deltaY * deltaY);


}

public static void swapCoordinates(Point point) {


double temp;
temp = point.xCoordinate;
point.xCoordinate = point.yCoordinate;
point.yCoordinate = temp;
}

public String toString() {


return "(" + xCoordinate + "," + yCoordinate + ")";
}
}

The output:

Distance between two points is: 5.0


Before swap operation
(1.0,2.0)
After swap Operation
(2.0,1.0)
Constructors
A constractor is a special method that initialize the instance variables. A
constructor gets invoked “automatically” at the time of object creation. this
keyword is generally used for accessing class members from its own methods
when they have the same name as those passed as arguments. It is used to
refer to the object itself.

In the example below, we create a constructor, and we use it to initialize


xCoordinate and yCoordinate. To count the number of objects of type Point we
increment the static variable numberOfPoint.

Example

public class Point {


double xCoordinate;
double yCoordinate;
static int numberOfPoints;

public Point(double xCoordinate, double yCoordinate){


this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
// Don't be confused at this point :)
// I just want this variable to get incremented
// when this constructor gets activated
numberOfPoints++;
}

public static void main(String[] args) {


Point point1 = new Point(1.0, 2.0);
Point point2 = new Point(6.0, 14.0);

System.out.println("point1 is " + point1.toString());


System.out.println("point2 is " + point2.toString());
System.out.println("Distance between two points is " +
calculateDistance(point1, point2));
System.out.println("Number of objects of type Point is "+
numberOfPoints);
}

// 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;

return Math.sqrt(deltaX * deltaX + deltaY * deltaY);


}
public String toString() {
return "(" + xCoordinate + "," + yCoordinate + ")";
}

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

Access Control Modifiers


You can only use public for classes. When you don’t specify a class, It’s access
modifier is public by default.

• public: The code is accessible by any other class.


• private: Attributes, methods and construtors declared private can only be
accessed within the declared class.
• protected: Attributes, methods and constructors declared private are
accessible in the same package and subclasses.
• Default: When no access modifier is specified for a class, attribute, method
and constructor, It is said to be having the default access modifier. Classes,
attributes, methods, constructors are accessible only within the same class.

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;

public Circle(double radius) {


this.radius = radius;
}

public static void main(String[] args) {


// Initialize circle1 with a radius of 10.0
// Every object has its own copy of instance variables
// circle1 has its own copy of radius and PI
Circle circle1 = new Circle(10.0);
circle1.PI = 3.0;
// It is possible to use methods in other methods
System.out.println("The perimeter is: " +
Math.round(circle1.perimeter()));
System.out.println("The area is: " +
Math.round(circle1.area()));

// We could declare these methods as public or default


// Notice that these are not static methods
// These methods belong the object instead of class
private double perimeter() {
return 2 * PI * radius;

private double area() {


return 2 * PI * radius * radius;
}
}

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.

Accessor and Mutator Methods


An accessor method is a public method that returns data from a private
instance variable, also called an accessor method, a get method, or a getter.
A public method that changes the data stored in private instance variables is
called a mutator method, a set method, or a setter.
Syntax for both is that they start with either get or set, followed by the name
of the variable, with the first letter in upper case.
In the following example, we create a Date class that has three private
instance variables, and provide accessor and mutator methods to manipulate
them.

Example

public class Date {


private int year;
private int month;
private int day;
// It is possible to have multiple constructors in a class
public Date() {

public Date(int year, int month, int day) {


this.year = year ;
this.month = month;
this.day = day;
}

public void setYear(int year) {


this.year = year;
}

public void setMonth(int month) {


this.month = month;
}

public void setDay(int day) {


this.day = day;
}

public int getYear() {


return year;
}

public int getMonth() {


return month;
}

public int getDay() {


return day;
}

public String toString() {


return "(" + day + "-" + month + "-" + "-" + year + ")";
}

public static void main(String[] args) {


//Don’t forget
//every object has its own copy of the class variables
Date currentDate = new Date(2019, 1, 13);
Date releaseDate = new Date();
System.out.println("The current date is " +
currentDate.toString());
currentDate.setYear(2020);
System.out.println("The new date is " +
currentDate.toString());
releaseDate.setYear(1995);
System.out.println("Java was released in " +
releaseDate.getYear());
}
}

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

Packages and API


A package is a collection of classes grouped together into a folder. Name of the
folder is name of the package. Think of it as a folder in a file directory.
Packages enable us avoid name conflicts, and to write a better maintainable
code. Packages are divided into two categories:
• Built-in Packages (pre-written packages)
• User-defined Packages (packages created by the programmer)

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);

System.out.println("Please, type something");

String answer = input.nextLine();


System.out.println("You typed: " + answer);
}
}

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

In the example below, we declare a public class Mathematics and add a


package decleration.

Example
package UserDefinedMathPackage;

public class Mathematics {


public static int sum(int integer1, int integer2) {
return integer1 + integer2;
}
public static double sum(double double1, double double2) {
return double1 + double2;
}
}

In this example, we import the package we created in a different file to


PackageTest class.

Example
import UserDefinedMathPackage.Mathematics;
public class PackageTest {
public static void main(String[] args) {

System.out.println("25.2 + 44.3 = " +


Mathematics.sum(25.2, 44.3));
System.out.println("1 + 1 = " +
Mathematics.sum(1, 1));

}
}

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);
}

public void subtract(double num1, double num2) {


result = num1 - num2;
System.out.println("Difference is " + result);
}

public void multiply(double num1, double num2) {


result = num1 * num2;
System.out.println("Product is " + result);
}

public void divide(double num1, double num2) {


result = num1 % num2;
System.out.println("Quotient is " + result);
}

public void square(double num) {


result = num * num;
System.out.println("Square is " + result);
}

public void squareRoot(double num) {


result = Math.sqrt(num);
System.out.println("Square root is " + result);
}

public void setResult(double result) {


this.result = result;
}

Don’t forget to declare class Calculator in a seperate file.

public class Calculator extends Functions{


static double num1 = 24.0;
static double num2 = 4.0;

public static void main(String[] args) {


Calculator calculator1 = new Calculator();

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;

public GeometricObject(int numberOfSides, int sideLength){


this.numberOfSides = numberOfSides;
this.sideLength = sideLength;
}

public void setNumberOfSides(int numberOfSides){


this.numberOfSides = numberOfSides;
}

public int getNumberOfSides() {


return numberOfSides;
}

public void setSideLength(int sideLength) {


this.sideLength = sideLength;
}
public int getSideLength() {
return sideLength;
}

public int calculatePerimeter() {


System.out.print("Object perimeter: ");
return sideLength * numberOfSides;
}
}

class Triangle extends GeometricObject{


Triangle(int numberOfSides, int sideLength) {
super(numberOfSides, sideLength);
}

public int calculatePerimeter() {


System.out.print("Triangle perimeter: ");
return numberOfSides * sideLength ;

}
}

class Square extends GeometricObject{


Square(int numberOfSides, int sideLength) {
super(numberOfSides, sideLength);
}

public int calculatePerimeter() {


System.out.print("Square perimeter: ");
return numberOfSides * sideLength;
}
}

public class Test{


public static void main(String[] args) {
GeometricObject pentagon = new GeometricObject(5, 10);
GeometricObject square = new Square(4, 10);
GeometricObject triangle = new Triangle(3, 10);

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);

public class RightTriangle implements Drawable{


int sides;
int length;

public RightTriangle(int numberOfSides, int sideLength) {


this.sides = numberOfSides;
this.length = sideLength;
}

public void info() {


System.out.println("It has " + sides + " sides");
}

public void draw(int length) {


for(int i = 1, star = 1; i <= length; i++, star +=2){
for(int space = length; space > i; space--)
System.out.print(" ");
for(int j = 1; j <=star ; j++)
System.out.print("*");
System.out.println();
}

public static void main(String[] args) {


RightTriangle tri = new RightTriangle(3, 4);
tri.draw(tri.length);
tri.info();
}
}

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;

public RightTriangle(int numberOfSides, int sideLength) {


this.sides = numberOfSides;
this.length = sideLength;
}

public void info() {


System.out.println("It has " + sides + " sides");
}

public void draw(int length) {


for(int i = 1, star = 1; i <= length; i++, star +=2){
for(int space = length; space > i; space--)
System.out.print(" ");
for(int j = 1; j <=star ; j++)
System.out.print("*");
System.out.println();
}
}

public static void main(String[] args) {


RightTriangle tri = new RightTriangle(3, 4);
tri.draw(tri.length);
tri.info();
}
}

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;

System.out.println("suit1: " + suit1);


System.out.println("suit2: " + suit2);
}
}
// Enum is outside of the class

enum Suits{
CLUB,
DIAMOND,
HEART,
SPADE
}

The output:
suit1: CLUB
suit2: DIAMOND

Enum inside a Class


It is also possible to have an enum inside a class.
In this exampe, we create an enum inside a class and access its variables
using dot notation.

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;

System.out.println("suit1: " + suit1);


System.out.println("suit2: " + suit2);
}
}

The output:
suit1: CLUB
suit2: DIAMOND

In the example below, we use enums in a switch statement to check for


corresponding values.

Loop Through an Enum


The enum type has a values() method, which returns an array of all enum
constants. This method is useful when you want to loop through the constants
of an enum

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) {

for(Suits suit : Suits.values()) {


System.out.println(suit);
}
}
}
The output:
CLUB
DIAMOND
HEART
SPADE

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);

System.out.println("Are you Optimistic or Pessimistic ?");

String answer = input.nextLine();


System.out.println("So, you are " + answer);
}
}

The output:
Are you Optimistic or Pessimistic ?
optimistic
So, you are optimistic

Input Types

• nextBoolean() reads a boolean value from the user


• nextByte() reads a byte value from the user
• nextDouble() reads a double alue from the user
• nextFloat() reads a float value from the user
• nextInt() reads a int rom the user
• nextLine() reads a String value from the user
• nextLong() reads a long value from the user
• nextShort() reads a short value from the user

Example
import java.util.Scanner;

public class AverageGrade {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int total = 0;
int count = 0;

// check if there is input of type it


// enter a non-integer value to stop the loop
while(input.hasNextInt()) {
int grade = input.nextInt();
total += grade;
count++;
}
System.out.println("The average is " + average(total, count));

static double average(int total, int count) {


return total / count;
}
}

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

Date and Time


Java does not have a built-in Date class, but we can import the java.time
package to work with the date and time API. The package includes many date
and time classes.
Class Description
Clock A clock providing access to the current
instant, date and time using a time-
zone.
Duration A time-based amount of time, such as
'34.5 seconds'.
Instant An instantaneous point on the time-
line.
LocalDate A date without a time-zone in the ISO-
8601 calendar system, such as 2007-
12-03.
LocalDateTime A date-time without a time-zone in the
ISO-8601 calendar system, such
as 2007-12-03T10:15:30.
LocalTime A time without a time-zone in the ISO-
8601 calendar system, such
as 10:15:30.
MonthDate A month-day in the ISO-8601 calendar
system, such as --12-03.
OffsetDateTime A date-time with an offset from
UTC/Greenwich in the ISO-8601
calendar system, such as 2007-12-
03T10:15:30+01:00.
OffsetTime A time with an offset from
UTC/Greenwich in the ISO-8601
calendar system, such as
10:15:30+01:00.
Period A date-based amount of time in the
ISO-8601 calendar system, such as '2
years, 3 months and 4 days'.
Year A year in the ISO-8601 calendar
system, such as 2007.
YearMonth A year-month in the ISO-8601
calendar system, such as 2007-12.
ZonedDateTime A date-time with a time-zone in the
ISO-8601 calendar system, such as
2007-12-03T10:15:30+01:00
Europe/Paris.
ZoneId A time-zone ID, such as
Europe/Paris.
ZoneOffset
Current Date
In this example, we import java.time.LocalDate class and use its now() method
to display the current date.

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);

// now() obtains the current date from system clock


// plusDays() returns a copy of LocalDate
// with the specified number of days subtracted
// minusDays() returns a copy of LocalDate
// with the specified number of days subtracted

System.out.println("Current date is " + currentDate);


System.out.println("Tomorrow will be " + tomorrow);
System.out.println("Yesterday was " + yesterday);
}
}

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);

// getHour() returns the hour of the date


// getMinute() returns the minute of the date
int hour = wokeUp.getHour();
int minute = wokeUp.getMinute();

// now() obtains the current time from system clock


// plusHours() returns a copy of LocalTime
// with the specified number of Hours added
// minusHours() returns a copy of LocalTime
// with the specified number of hours subtracted

System.out.println("Current time: " + currentTime);


System.out.println("2 hours ago : " + twoHoursAgo);
System.out.println("2 hours later: " + twoHoursLater);
System.out.println("I woke up at " +
hour + ":" + minute);
}
}

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) {

// getMonth() gets the month of the year using enum Month


// returns the enum Month
// that's why we declared the type of the currentMonth as
Month
LocalDateTime currentDateTime = LocalDateTime.now();
Month currentMonth = currentDateTime.getMonth();

int dayOfTheMonth = currentDateTime.getDayOfMonth();


int dayOfTheYear = currentDateTime.getDayOfYear();

System.out.println("Current date and time: ");


System.out.println(currentDateTime);
System.out.println("Month: " +
currentMonth);
System.out.println("Day of the month: " +
dayOfTheMonth);
System.out.println("Day of the year: " +
dayOfTheYear);
}
}
The output:
Current date and time:
2019-01-15T16:25:35.902
Month: JANUARY
Day of the month: 15
Day of the year: 15

Formatting Date and Time


The "T" in the example above is used to separate the date from the time. You
can use the DateTimeFormatter class with the ofPattern()method in the same
package to format or parse date-time objects. The following example will
remove both the "T" and microseconds from the date-ti
import java.time.LocalDateTime;

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;

public class Formatting {


public static void main(String[] args) {

LocalDateTime currentDateTime = LocalDateTime.now();

// create formatter for printing and parsing date time objects


// ofPattern() creates a formatter using the specified pattern
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("MM/dd/yyyy-hh:mm a");

//Get formatted String


String formatted = formatter.format(currentDateTime);

System.out.println("Unformatted: " + currentDateTime);


System.out.println("Formatted: " + formatted);
}
}

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:

• A Collection is a grouping of objects. Java.util.Collection interface is the is the


highest level of Java’s framework for collection classes. Two major
implementation of java.util.Collection interface are List and Set.

• A map is a set of associations between objects.

Common methods provided by Collection interface:


Operation Description
add() Adds the suplied object to the collection
remove() Emoves the specified object from colection
contains() Returns true if the collection contains the
specified object
size() Finds the number of elements in the collection
isEmpthy() Returns true if the collection doesn’t have any
elements
iterator()

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>();

progLanguages.add("JAVA"); // append "JAVA" to the list


progLanguages.add(1, "PHP"); // insert "PHP" at index 0

System.out.print(" ArrayList content: ");

// display the programming languages in the list


for (int i = 0; i < progLanguages.size(); i++)
System.out.printf(" %s", progLanguages.get(i));

// user defined method


display(progLanguages);
// add "Python" at the end of the list
progLanguages.add("Python");
// add "PHP" at the end of the list
progLanguages.add("PHP");
display(progLanguages);
// remove the first occurrence of "PHP"
progLanguages.remove("PHP");
display(progLanguages);
// remove item at index 1
progLanguages.remove(1);
display(progLanguages);

// check if a value is in the List


System.out.println(" Does the list contain C " +
(progLanguages.contains("C") ? "": "not "));

// display number of elements in the List


System.out.println(" Size: " + progLanguages.size());
}

// display the ArrayList's elements on the console


public static void display(ArrayList<String> items){

// display each element in items


for (String item : items) {
System.out.printf(" %s ", item);
}
System.out.println();
}
}

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));

Set<Integer> odds = new HashSet<Integer>();


odds.addAll(Arrays.asList(1, 3, 5, 7, 9, 11, 11));

// Union of the sets


Set<Integer> union = new HashSet<Integer>();
union.addAll(primes);
union.addAll(odds);

// Intersection of the sets


Set<Integer> intersection = new HashSet<Integer>();
intersection.addAll(primes);
intersection.retainAll(odds);

// 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);

System.out.println("primes: " + primes);


System.out.println("odds: " + odds);
System.out.println("Union: " + union);
System.out.println("Intersection: " + intersection);
System.out.println("Difference: " + difference);
System.out.println("Complement: " + complement);
}
}

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<>();

billionaires.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

System.out.println("Entries in the HashMap:");


System.out.println(billionaires);
}
}

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<>();

billionaires.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

System.out.println("Elon Musk is "+


billionaires.get("Elon Musk") + " years old.");
}
}

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.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

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.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

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<>();

billionaires.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

int count = billionaires.size();

System.out.println("There are total " +


count + " billionaires in our HashMap");
}
}

The output:
There are total 4 billionaires in our HashMap

Iterate Through a HashMap


In this example, we loop through the items of the billionaires. We use the
keySet() method to get an array of the keys, and use the values() method to
get the array of values.

Example
import java.util.*;
public class HashData {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> billionaires = new HashMap<>();

billionaires.put("Jeff Bezos", 55);


billionaires.put("Bill Gates", 63);
billionaires.put("Elon Musk", 47);
billionaires.put("Warren Buffet", 88);

int total = 0;

for(String billionair : billionaires.keySet()) {


System.out.println(billionair +
": " + billionaires.get(billionair));
}

for(int age : billionaires.values()) {


total += age;
}

System.out.println("Total age is " + total);


}
}

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.

canWrite(): boolean Returns true if the file represented by the File


object exists and can be written.

isDirectory(): boolean Returns true if the File object represents a


directory.
isFile(): boolean Returns true if the File object represents a file.
isAbsolute(): boolean Returns true if the File object is created using an
absolute path name.
+isHidden(): boolean Returns true if the file represented in the File
object is hidden.
+getAbsolutePath(): String Returns the complete absolute file or directory
name represented by the File
+getCanonicalPath(): String Returns the same as getAbsolutePath() except
+getName(): String Returns the last name of the complete directory
and file name represented by
the File object.
+getPath(): String Returns the complete directory and le name
represented by the File object.
+getParent(): String Returns the complete parent directory of the
current directory or the file.
+lastModied(): long Returns the time that the file was last modied
+lastModied(): long Returns the time that the file was last modied.
+length(): long Returns the size of the file, or 0 if it does not exist
or if it is a directory.
+listFile(): File[] Returns the files under the directory for a
directory File object.
+delete(): boolean Deletes the le or directory represented by this File
object.
+delete(): boolean Deletes the le or directory represented by this File
object.
+renameTo(dest: File): boolean Renames the file or directory represented by this
File object to the specied name
mkdir() Creates a directory represented in this File object.

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);

// Writes formatted output to the file


output.print("Richard Smith ");
output.println(75);
output.print("Lisa Johnson ");
output.println(82);

// Closes the file


output.close();
}
}

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");

// Create an instance of Scanner class


Scanner input = new Scanner(fileObject);
// Read data from a file
while (input.hasNext()) {
String firstName = input.next();
String lastName = input.next();
int score = input.nextInt();
System.out.println(
firstName + " " + lastName + " " + score);
}
// Do not forget to close the file
input.close();
}
}

You might also like