JAVA FUNDAMENTALS

Mercy Jemosop
38 min readApr 29, 2022

--

Understanding java basics and algorithms

INTRODUCTION

Having a basic understanding of a language is very important in problem-solving which is an underrated skill some developers ignore. Learning a framework is good but learning the fundamentals of a language will make your learning journey much easier since you are already familiar with most of its syntax. This will come in handy when you need to solve a problem and you know all the possible workaround to find a solution.

N.B This is my w3school course summary.

N.B with knowledge of java you can build Desktop Applications, Web Applications, Enterprise Applications, Mobile, Embedded systems, Smart Card, Robotics, Games, Database connection, Web servers, application servers, and many others.

  1. What is java?
  • Object-oriented programming(OOP) language, java organizes software design around objects. An object can be defined as a data field that has unique attributes and behavior.
  • Class-based programming is a style of OOP in which inheritance occurs via defining classes of objects instead of inheritance occurring via objects alone. A Class in OOP is a blueprint or prototype that defines the variables and the methods or functions common to all Java Objects of a certain kind.

OOP STRUCTURE

i. Classes are templates or blueprints or prototypes in which objects are created. It is used to take all the properties and behaviors of an object in your program, and combine them into a single template.

ii. Objects is an instance(member ) of a class. It has identity, behavior, and state. The state of an object is stored in fields(variables) while methods(functions) display the object's behavior.

Example

A phone is an object, it has attributes such as color, size, weight etc, and methods(functions) such as calling, sending messages, taking pictures, etc.

iii. Methods are functions defined inside a class that describe the behavior of an object.

iv. Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attribute field.

Variable in Java is a data container that saves the data values during Java program execution.

Example of OOP Structure

// Class Declaration
public class Person {
// Instance Variables
String name;
int age;


// method
public String getInfo() {
return ("Name is: "+name+" Age is:"+age);
}


public static void main(String[] args) {
Person per = new Person();
per.name="Tom";
per.age=2;
System.out.println(per.getInfo());
}
}

Here are some resources to get more understanding of java w3school and javatpoint.

System.out.println()…This method is used to print data to the console.

With that overview of java definitions, we now have a better understanding of what java is.

Let’s dive into some basics with examples.

Basic class definition. You need the main method or function to execute(run) a class. System.out.println() is used to print data in the console/terminal of your editor/IDE.

public class Main {
public static void main(String[] args) {
System.out.println("Basic programming language");
}
}
///output
Basic programming language

Let’s add a variable and call the variables from the main method.

i. We have declared two variables name and color. Example String name;

ii. We then initialize the variable with the values example main.name=”Mercy”;

iii. Create an object/instance of a class to be able to do step 2.

N.B you cannot directly call/access variables in the main method, you need to create an instance of the class.

public class Main {
String name;
String color;
public static void main(String[] args) {
Main main=new Main();
main.name="Mercy";
main.color="Black";
System.out.println("name "+main.name+" color "+main.color);
}
}
//outpu
name Mercy color Black

Important terms you need to grasp as we go along

  • Declaration − A variable declaration involves declaring data type and name. example String name.
  • Initialization − assigning value to a variable example main.name=”Mercy”.
  • Instantiation − creating an object using the 'new' keyword. example Main main=new Main();

Static Keyword

If you do not need to instantiate a class to access a variable, you can declare the variables using a static keyword. With this, you can call the variables in the main method directly.

public class Main {
static String name;
static String color;
public static void main(String[] args) {
name="Mercy";
color="Black";
System.out.println("name "+name+" color "+color);
}
}
///output
name Mercy color Black

N.B

A static keyword may seem to be easy to implement but you should know one of the disadvantage of using a static variable is:

Static members are always part of the memory whether they are in use or not. This means you have no control of the variable creation and destruction(garbage collection). The static variable will persist for the lifetime of the application. This is mainly referred as a memory leak. Read on memory leak and garbage collection.

I found this article on static variable,method and class read for a better understanding of static keyword.

2. Comment

These are used to explain code, they are not compiled during program execution. Comments are important especially when working with a team since it makes it easier for another member to understand the code better. You can also use comments when writing complex programs in case you forget what some lines do.

Types of comments

single line comment //

example

//declare variable name
String name;

multi-line comments /* */

/**
This is mainly used for long description or comment out multiple lines of code
**/

3.Variables

We have covered about variables above but let’s get a deep dive into it.

Variables are containers for storing data values. Variables have different data types e.g String, int, float, char, boolean.

Declaring a variable and assigning value

String name=”Mercy”;

int age=19;

float amount=12.2;

boolean isActive=true;

char value=’A’;

4.Data types

This is an attribute associated with a piece of data that tells the computer how to inter-prate its value. Data types are divided into primitive and non-primitive data types.

Primitive data types are predefined in java. It specifies the type and size of variable values. e.g byte, short, int, long, float, double, boolean and char.

. Byte Stores whole numbers from -128 to 127

.Short Stores whole numbers from -32,768 to 32,767

.Int Stores whole numbers from -2,147,483,648 to 2,147,483,647

. long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

. Float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

. Double Stores fractional numbers. Sufficient for storing 15 decimal digits.

. Boolean Stores true or false values char 2 bytes Stores a single character/letter or ASCII values

N.B

-The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

-Primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.

.Non-primitive data types are created by the programmer and not defined by java. eg Strings, Arrays, Classes, Interface.

. A String variable contains a collection of characters surrounded by double quotes. example String greeting = "Hello";

. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

N.B read more on the different data types and when to use them.

. A Class is like an object constructor or a “blueprint” for creating objects.

Java Type Casting

Assigning the value of one primitive type to another type. It’s divided into wide and narrow casting.

Widening Casting (automatically) — converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

int myInt = 9;
double myDouble = myInt;

Narrowing Casting (manually) — converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

Java Math Functions

  • The Math.max(x,y) method can be used to find the highest value of x and y: Math.max(5, 10)=10;
  • The Math.min(x,y) method can be used to find the lowest value of x and y:Math.min(5, 10)=5
  • The Math.sqrt(x) method returns the square root of x: Math.sqrt(64)=8
  • The Math.abs(x) method returns the absolute (positive) value of x: Math.abs(-4.7)=4.7
  • Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive): examples of sample results 0.5333739691750525, 0.2161708001091066 etc

only want a random number between 0 and 100, you can use the following formula: int randomNum = (int)(Math.random() * 101)= 77,60,20

Java Booleans

Data type that can only have one of two values.(YES/NO),(TRUE/FALSE),(ON/OFF). (Read on operators)

boolean isJavaFun = true; value is true

boolean isJavaFun = false; value is false

Comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true.

int x = 20;
int y = 6;
System.out.println(x > y); //true
System.out.println(x < y); //false
System.out.println(x ==20); //true

Java Conditions and If Statements

Java has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
if (20 > 18) {
System.out.println("20 is greater than 18");
}
//if the condition is true it will print the message if not no message will be printed
//output
20 is greater than 18
  • Use else to specify a block of code to be executed, if the same condition is false
if (20 < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
///this condition is false hence the else block will be executed
///output
Good evening.
  • Use else if to specify a new condition to test, if the first condition is false. You can have more than one else if condition
int age = 22;
if (age < 10) {
System.out.println("Good morning.");
} else if (age > 22) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
///in this case the condition that it true is the else if block
//ouput
Good day.
  • Use switch to select one of many code blocks to be executed

The switch expression is evaluated once, the value of the expression is compared in each value of each case. If there is a match the block associated with that case is executed.

syntax:

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

example

int test = 4;
switch (test) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
}
///The output is the case whose condition is true
//output
Thursday

The break keyword, when java reaches a break keyword it breaks out of the switch block bringing the execution of block of code to a stop.

The default keyword specifies some code to run if there is no case match:

int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
/// in this case the default

Java While Loop

Loop executes a block of code as long as a condition is met. It reduces errors, make code readable and saves on time.

1.While Loop

It loops through a block of code as long as a specified condition is true. It loops unknown number of times until a condition is met.

syntax

while (condition) {
// code block to be executed
}

example

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
//output
0
1
2
3
4

This code will be executed repeatedly until the condition is met which is i being less than 5

2.The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.It will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

syntax:

do {
// code block to be executed
}
while (condition);

example

int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);

3. For Loop

This is used when you know exact number of times you need to loop through a piece of code.

syntax

for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

example

for (int i = 0; i < 5; i++) {
System.out.println(i);
}

4. For Each-Loop

It is used exclusively to loop through elements in an array.

syntax

for (type variableName : arrayName) {
// code block to be executed
}

Example

System.out.println("For Each loop executed");
String[] fruits={"java","python","c++", "Javascript","Dart"};
for (String i : fruits) {
System.out.println(i);
}
//output
java
python
c++
Javascript
Dart

5.For-Loop with break

Break statement is used to jump a loop. When the condition is met the loop stops.

for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
//output
0
1
2
3
Process finished with exit code 0

6. For-Loop with continue

Continue statement causes a loop to jump to the next iteration of the loop. This loop will run but when the condition is reached( i ==4), it will skip printing(4) and continue with the loop.

for (int i = 0; i < 6; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
//output
0
1
2
3
5

Java Arrays

Arrays are used to store multiple values in a single variable. The variable type is declared with square brackets e.g

String[] fruits;

We use curly bracket{} to define an array. The curly brackets contains values to populate an array.

String[] fruits={"mango","orange","banana","apples"}

To get/access a specific items in an array we use the item index

N.B index in an array starts from 0 not 1, in this case mango will be index 0.

public class Arrays {

public static void main(String[] args) {
String[] fruits = {"mango","orange","banana","apples"};
System.out.println(fruits[0]);
}
}
///output
mango

Change an array element

We use index number to change a specific element in an array.example to replace the first index with another value

public class Arrays {

public static void main(String[] args) {
String[] fruits = {"mango","orange","banana","apples"};
fruits[0] = "pineapples";
System.out.println(fruits[0]);
}
}
//output
pineapples

Get array length,to get the number of elements in an array we use the length property.

public class Arrays {

public static void main(String[] args) {
String[] fruits = {"mango","orange","banana","apples"};
System.out.println(fruits.length);//number of elements in an array
}
}
//output
4

Loop through an array

We apply the knowledge we learnt on loops(for and for-each loops) to get items in an array

public class Arrays {
static String[] fruits = {"mango","orange","banana","apples"};

void loopArrayFor(){
System.out.println("print items using a For loop");
for(int i=0; i< fruits.length; i++){
System.out.println(fruits[i]);
}
}

void loopArrayForEach(){
System.out.println("print all items using a For Each loop");
for(String i:fruits){
System.out.println(i);
}
}

public static void main(String[] args) {
Arrays arr=new Arrays();
arr.loopArrayFor();//for loop
arr.loopArrayForEach();//for each loop

}
}
//output
print all items in an array using a For loop
mango
orange
banana
apples
print all items in an array using a For Each loop
mango
orange
banana
apples

Multidimensional Arrays

This is an array of arrays,each array contains its own set of curly braces.

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

Access item in a multidimensional array, you need to specify two indexes:

one for the array and one for the element inside the array.

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[0][2];
int y = myNumbers[1][2];
System.out.println(x); // Outputs 3
System.out.println(y); // Outputs 7

We use for loop inside a for loop to to get elements of a two dimensional array.

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };for (int i = 0; i < myNumbers.length; ++i) {    for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
//output
1
2
3
4
5
6
7

Java Methods

A method is a block of code that performs a certain function. This block of code runs only when it’s called.A method is also know as a function.

A method should be declared within a class.

syntax: name of method followed by parenthesis

nameOfMethod()

Advantage of using a method: code reuse,define the code once, and use it many times, this makes your code readable and reduces chances of introducing errors to a code.

Parameter are variables that are listed as part of method declaration, it acts as a variable inside a method.When a parameter is passed to a method it’s called an argument.

Example

public class Methods {
static void bioData(String name) {
System.out.println( name+ " Mercy");
}

public static void main(String[] args) {
bioData("jemosop");
}
}
///output
jemosop Mercy

From the example above,”jemosop” is an argument while name is a parameter

The Void keyword is used in a method to indicate that the method is not expected to return anything/value.

Return a value from a method

public class Methods {
static int bioData(int age) {
return age+2;
}

public static void main(String[] args) {
System.out.println(bioData(3));
}
}
//output
5

you can also store the value of a method inside a variable.

public class Methods {

static int bioData(int age) {
return age+2;
}

public static void main(String[] args) {
System.out.println(bioData(3));
int y=bioData(3);
System.out.println(y);
}
//output
5
5

Method Overloading

This is a feature that allows more than one method to have same name with different parameters. Instead of defining two methods that do the same thing it’s better to overload one.

Ways of overloading a method:

  1. Number of parameters.
add(int, int)
add(int, int, int)

2. Data type of parameters.

add(int, int)
add(int, float)

3. Sequence of Data type of parameters.

int add(int, int)
float add(int, int)

Java Scope

Scope is a region where a certain variable or method is accessible in a program. Code declared inside {} is refereed to as block of code. Variables declared inside a block of code{} is only accessible inside that block of code.

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x
System.out.println(x);

} // The block ends here

// Code here CANNOT use x

Java Recursion

This is a technique of making a function call itself. It’s important when it comes to breaking down complex problems into simpler problems.

example

public class Recursion {

public static void main(String[] args) {

int result = sum(10);
System.out.println(result);
}
//function to add all of the numbers up to 10.
public static int sum(int k) {
System.out.println("K 1:: "+k);
if (k > 0) {
// System.out.println("K :: "+ k + sum(k - 1));

return k + sum(k - 1);
} else {
return 0;
}
}
}

The case above, sum() function calls itself until the condition if(k>0) is met:

To break that code down you will get something like :

k + sum(k - 1)

where K is 10

10+sum(10–1)+sum(9–1)+sum(8–1)+sum(7–1)++sum(6–1)+sum(5–1)+sum(4–1)+sum(3–1)++sum(2–1)++sum(1–1)

10+9+8+7+6+5+4+3+2+1+0=55

after the point sum(1–1) the value of k will be zero and it will return a zero.

Java Object-Oriented Programming(OOP)

OOP creates objects that contain both data and methods. The advantages of using OOP as a programmer include:

  1. Faster and easier to implement
  2. It provides a clear structure for your program
  3. Code reuse makes it easy to maintain,modify and debug without repeating same code.

checkout this blog for other advantages

Difference between classes and objects in java

Class is a blueprint/template in which objects are created while an object is an instance/member of a class. It has identity, behavior, and state. The state of an object is stored in fields(variables) while methods(functions) display the object’s behavior.

N.B class name is case sensitive and should start with uppercase

example

Class

Fruit,

Object

Apple, Banana, Mango

To create an object of a class we use new keyword

Second myObj = new Second()

You can access attributes by creating an object of the class, and by using the dot syntax (.)

myObj.x

Example

class Second {//class
Int x=5; //attributes
public static void main(String[] args) {//method
Second myObj = new Second();//object
System.out.println(myObj.x);
}
}

Java Class Attributes

Class attributes are variables within a class, also know as field.

Final keyword used when you want a variable to store same value, also know as a modifier.

Static attributes/methods can be accessed without creating an object of the class.

Java Constructors

A constructor is a special method used to initialize objects. This method is called when a class is created and is used to initialize objects.It can be used to set the initial value for object attributes.

public class ClassObject {
int x;// class attribute
// a class constructor for the ClassObject class
public ClassObject(){
x=5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {
// Create an object of class ClassObject
//(This will call the constructor)
ClassObject myObj = new ClassObject();
System.out.println(myObj.x); // Print the value of x
}
}

N.B

  • constructor name must be the same as class name and does not have a return type like void.
  • constructor is called when an object is created .
  • All classes have constructors by default, if you do not create a constructor java will create one for you.

A constructor can also take parameters which are used to initialize attributes. You can have as many parameters as you like.

public class Main {
int x;// class attribute
// a class constructor for the Main class with parameter
public Main(int y) {
x = y; // Set the initial value for the class attribute x
}

public static void main(String[] args) {
// Create an object of class Main
//(This will call the constructor)
Main myObj = new Main(5);
System.out.println(myObj.x); // Print the value of x
}
}

Java Modifiers

Modifiers are divided into access modifiers which control the level of access and Non-access modifiers which do not control the level of access but provide other functionality.

Access Modifiers

  • For classes you can have public or default access modifier.

Public modifier indicates that a class can be accessed by any other class while default modifier indicates that a class is only accessed by other classes in the same package, it is normally used when you don’t specify modifier.

  • For attributes, methods and constructors you have public,private,default alland protected access modifier.

public modifier indicates that the code is accessible to all classes. Private modifier indicates that code is only accessible within the declared class.Protected modifier indicates that code is accessible to same package and sub-classes.default modifier indicates that code is only accessible to same package.

Non-Access Modifiers

  • For classes, you can use either final or abstract:

final modifier indicates that a class cannot be inherited by other classes while abstract indicates that a class cannot be used to create objects.

  • For attributes and methods, you can use final,abstract,static,transient,synchronized,volatile

final indicates that Attributes and methods cannot be overridden/modified.

abstract indicates that it can only be used in an abstract class, and can only be used on methods, this method does not have a body, for example abstract void run();.

Static indicates that Attributes and methods belongs to the class, rather than an object.

Transient indicates that Attributes and methods are skipped when serializing the object containing them.

Synchronized Methods can only be accessed by one thread at a time.

Volatile the value of an attribute is not cached thread-locally, and is always read from the “main memory”.

Java Encapsulation

Encapsulation is making sure that sensitive data is “hidden” from users. This is achieved by:

  • declaring class attributes/variables as private
  • provide public get and set methods to access and update the value of a private variable.

N.B previously we learned that private variables can only be accessed within same class where it was declared but it’s possible to access them if we provide public get and set methods.

Get methods returns the variable value while set methods sets the value.

The this keyword is used to refer to the current object.

public class Encapsulation {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}

Access private variables

public class Main {  public static void main(String[] args) {    Encapsulation myObj = new Encapsulation();
myObj.name = "John"; // error
System.out.println(myObj.name); // error

myObj.setName("John");
// Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

Advantage encapsulation

  1. Better control of class attributes and method
  2. Class attributes can be made read-only if you only use get method or write only if you use set method
  3. Flexible, you can change one part of code without affecting other parts.
  4. Increase security of data.

Java Packages

A package is used to group related classes, it’s used to avoid name conflict and write a better maintenance code. It’s divided into:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)

Java Inheritance (Subclass and Superclass)

Inheritance in java involves inheriting attributes and methods from one class to another. Inheritance is divided into:

subclass(child)-the class that inherits from another class.

superclass(parent)-the class being inherited from

Extend keyword is used when you need to inherit from a class.

Example of a Parent class

public class Person {
protected String name = "Mercy"; //Person attribute
public void bioData() { // Vehicle method
System.out.println("Name, Age!");
}
}

Example of a child class inheriting features of a parent class

public class Inheritance extends Person{
public static void main(String[] args) {
//create a Inheritance class object
Inheritance obj=new Inheritance();
//call the bioData() method from Person class
obj.bioData();
System.out.println(obj.name);
}
}

N.B you can use the final keyword if you don’t want other classes to inherit from a class.

final class Person{}

Adavantage

  • code reuseability

Java Polymorphism

Polymorphism is the ability to process objects differently on the basis of their class and data types.Types of polymorphism:

  • compile time polymorphism
  • run time polymorphism

Polymorphism is implemented on method/function unlike inheritance is implemented on classes.

Java Inner Classes

These are nested classes or classes within a class.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

class InnerOuterClass {
int x = 10;

class InnerClass {
int y = 5;
}
}

public class Main {
public static void main(String[] args) {
InnerOuterClass myOuter = new InnerOuterClass();
InnerOuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}

Private Inner Class

Inner class can be private or protected. If you don’t want outside objects to access inner class, declare the class as private.

Java Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.It can be achieved by abstract classes or interfaces. The abstract keyword is a non-access modifier used for classes and methods.

Abstract class is a restricted class that cannot be used to create objects, to access.it must be inherited from another class.

Abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

N.B you cannot create an object from an abstract class.This will result in an error. Example

Animal myObj = new Animal(); // will generate an error

To access an abstract class, you need to inherit from another class.

// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}

// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Abstract classes and methods are used to achieve security, hide certain details and only show the important details of an object.

Java Interface

Interfaces is another way of achieving abstraction. An interface is a completely “abstract class” that is used to group related methods with empty bodies.

// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, implementation keyword is used.Just like in inheritance we use extends to access parent class we can access interface method using implementation.

// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

N.B Interfaces cannot be used to create objects. It’s methods do not have a body, the body is provided by the implemented class.On implementation of an interface, you must override all methods.Interface methods are by default abstract and public. Interface attributes are by default public,static and final.

Interface cannot contain a contractor.

Advantage

  • To achieve security, hide certain details and only show the important details of an object (interface).
  • A class can implement multiple interfaces separated by a coma.

example

class DemoClass implements FirstInterface, SecondInterface {}

Java Enums

Enum is a special class that represents a group of constants, these are unchangeable variables.

The enum keyword is used to create an enum and seperate the constant with a coma.N.B they should be in uppercase

enum Gender{
MALE,
FEMALE
}

Use the dot(.) syntax to access an enum

Gender myVar=Gender.MALE;

Enum inside a class

public class Enum {
enum Gender{
MALE,
FEMALE
}
public static void main(String[] args) {
Gender myVar = Gender.MALE;
System.out.println(myVar);
}
}

Enum in a Switch Statement

enum Gender{
MALE,
FEMALE
}

public class Enumcondition {
public static void main(String[] args) {
//switch
System.out.println("Switch enum");
Gender gender=Gender.FEMALE;
switch(gender) {
case FEMALE:
System.out.println("Female");
break;
case MALE:
System.out.println("Male");
break;
}
}
}

Loop Through an Enum

Enum type has a values() method, which returns an array of all enum constant.

enum Gender{
MALE,
FEMALE
}

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

System.out.println("Loop enum");
for (Gender myVar : Gender.values()) {
System.out.println(myVar);
}

}
}

N.B enum cannot be used to create objects and cannot extend other classes but can be implemented

Adv: enum is used when you have values that are not going to change.

Java User Input (Scanner)

Scanner is used to get user input, we use the nextLine() method which is used to read strings.

public class UserInput {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your name");
String userName = myObj.nextLine(); // Read user input
System.out.println("Your name is: " + userName); // Output user input
}
}
///output
Enter your name
Mercy Jemosop
Your name is: Mercy Jemosop

nextLine() is used to read strings to read other types:

  • nextBoolean(), reads a boolean value from the user.
  • nextByte(), reads a byte value from the user.
  • nextDouble(), reads a double value from the user
  • nextFloat(), reads a float value from the user
  • nextInt(), reads a int value from 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

N.B if you enter wrong input you will get an exception error.

Java Date and Time

Java does not have a built in dates, but we can import the java.time package to work with the date and time api.

LocalDate, represents a date (year, month, day (yyyy-MM-dd)).
LocalTime, represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)).
LocalDateTime, represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns).
DateTimeFormatter, formatter for displaying and parsing date-time objects.

Display Current Date

We use the now() method to get the current date.

public class DateJava {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
//output
2022-04-23

Display Current Time

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:

public class DateJava {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);
}
}
//output
10:12:18.942993223

Display Current Date and Time

public class DateJava {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println(currentDateTime);
}
}
//output
2022-04-23T10:15:35.475339148

Formatting Date and Time

We use ofPattern() method from the DateTimeFormatter class to format dates. In the output above(2022–04–23T10:15:35.475339148), “T” is used to separate date from time.

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

System.out.println("Formatting date");
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
}
}
//output
Formatting date
Before formatting: 2022-04-23T10:20:09.295332859
After formatting: 23-04-2022 10:20:09

Different formats supported by ofPattern() method in java.

yyyy-MM-dd “1988–09–29”
dd/MM/yyyy “29/09/1988”
dd-MMM-yyyy “29-Sep-1988”
E, MMM dd yyyy “Thu, Sep 29 1988”

Java ArrayList

This is a class of resizable array. The difference between an array and arraylist is that an array cannot be modified, you have to create a new one to add or remove an item.

We use add() method to add items to an array.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
}
}
//output
[mango, apple, orange, pineapple]

Access an Item

We use get() method to access item in an array. N.B indexes start from 0.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
System.out.println("index 0 :: "+ fruits.get(0));
}
}
//output
[mango, apple, orange, pineapple]
index 0 :: mango

Change an Item

To modify an element use the set() method and refer to the index. Rename mango to mango modified.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
}
}
///out put
[mango, apple, orange, pineapple]
index 0 :: mango
index 0 :: mango modified

Remove an Item

To remove an item use the remove() method and refer to the index being removed from the array list. To remove all items use clear.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
//remove
fruits.remove(0);
//get
System.out.println("index 0 after remove :: "+ fruits.get(0));
}
}
///output
index 0 :: mango
index 0 :: mango modified
index 0 after remove :: apple

ArrayList Size

To get the number of items in an arraylist use the size() method. Notice the size changes.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//remove
fruits.remove(0);
//get
System.out.println("index 0 after remove :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
}
}
///output
[mango, apple, orange, pineapple]
index 0 :: mango
index 0 :: mango modified
Array Size :: 4
index 0 after remove :: apple
Array Size :: 3

Loop Through an ArrayList

Loop through an arraylist with a for loop and use the size().

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//remove
fruits.remove(0);
//get
System.out.println("index 0 after remove :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());

//for loop
for(int i=0; i< fruits.size(); i++){
System.out.println(fruits.get(i));
}
}
}
///output
[mango, apple, orange, pineapple]
index 0 :: mango
index 0 :: mango modified
Array Size :: 4
index 0 after remove :: apple
Array Size :: 3
apple
orange
pineapple

for each

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//remove
fruits.remove(0);
//get
System.out.println("index 0 after remove :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());

//for loop
System.out.println("for loop :: ");
for(int i=0; i< fruits.size(); i++){
System.out.println(fruits.get(i));
}
//for-each loop
System.out.println("for-each loop :: ");
for(String i:fruits){
System.out.println(i);
}
}
}
///output
[mango, apple, orange, pineapple]
index 0 :: mango
index 0 :: mango modified
Array Size :: 4
index 0 after remove :: apple
Array Size :: 3
for loop ::
apple
orange
pineapple
for-each loop ::
apple
orange
pineapple

Sort an ArrayList

Collection class has a sort() method that sorts lists alphabetically or numerically.

public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//set
fruits.set(0, "mango modified");
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//remove
fruits.remove(0);
//get
System.out.println("index 0 after remove :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());

//for loop
System.out.println("for loop :: ");
for(int i=0; i< fruits.size(); i++){
System.out.println(fruits.get(i));
}
//for-each loop
System.out.println("for-each loop :: ");
for(String i:fruits){
System.out.println(i);
}
//sort numbers
Collections.sort(fruits);
System.out.println("for-each loop after sort :: ");
for(String i:fruits){
System.out.println(i);
}
}
}
///output
[mango, apple, orange, pineapple]
index 0 :: mango
index 0 :: mango modified
Array Size :: 4
index 0 after remove :: apple
Array Size :: 3
for loop ::
apple
orange
pineapple
for-each loop ::
apple
orange
pineapple
for-each loop after sort ::
apple
orange
pineapple

Java LinkedList

This is identical to an array list.

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

LinkedList<String> fruits = new LinkedList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
}

}
//output
[mango, apple, orange, pineapple]

N.B the difference between an arrayList and an linkedList is that:

An arraylist has a regular array in it, when an element is added, it is placed into the array. If the array is not big enough a new array is created to replace the old array and the old one is removed.

A linkedList stores its items in a container, it has a link to the first container and each container has a link to the next container.To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.

Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.

Linked list methods:

addFirst() Adds an item to the beginning of the list.

addLast() Add an item to the end of the list.

removeFirst() Remove an item from the beginning of the list.

removeLast() Remove an item from the end of the list.

getFirst() Get the item at the beginning of the list.

getLast() Get the item at the end of the list

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

LinkedList<String> fruits = new LinkedList<>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
System.out.println(fruits);
//sort numbers
Collections.sort(fruits);
System.out.println("for-each loop after sort :: ");
for(String i:fruits){
System.out.println(i);
}
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//remove
fruits.remove(0);
//get
System.out.println("index 0 :: "+ fruits.get(0));
//size
System.out.println("Array Size :: "+ fruits.size());
//add first
fruits.addFirst("lemon");
//add last
fruits.addLast("watermelon");
System.out.println("for-each loop after sort :: ");
for(String i:fruits){
System.out.println(i);
}
System.out.println("get first :: "+ fruits.getFirst());
System.out.println("get first :: "+ fruits.getLast());
}

}
///output
[mango, apple, orange, pineapple]
for-each loop after sort ::
apple
mango
orange
pineapple
index 0 :: apple
Array Size :: 4
index 0 :: mango
Array Size :: 3
for-each loop after sort ::
lemon
mango
orange
pineapple
watermelon
get first :: lemon
get first :: watermelon

Java HashMap

It stores values in a “key/value” pairs and you can access them by index of another type.

Add items to hashmap

We use the put method to add items to a hashmap

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country ", "Kenya");
System.out.println(person);
}
}
///output
{FirstName=Mercy, Country =Kenya, LastName=Jemosop, Gender=Female}

Access an Item

To access a value in the HashMap, use the get() method and refer to its key:

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
System.out.println(person);
System.out.println("Get item with key country :: " + person.get("Country"));
}
}
//output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}
Get item with key country :: Kenya

Remove an Item

To remove an item, use the remove() method and refer to the key:

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);
//get a single item
System.out.println("Get item with key country :: " + person.get("Country"));
//remove an item
person.remove("Gender");
//get the removed item remove
System.out.println("Get item with key gender :: " + person.get("Gender"));
//get all items
System.out.println(person);
}
}
///output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}
Get item with key country :: Kenya
Get item with key gender :: null
{FirstName=Mercy, Country=Kenya, LastName=Jemosop}

Remove all items

Use the clear() method to remove all items .

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);
//get a single item
System.out.println("Get item with key country :: " + person.get("Country"));
//remove an item
person.remove("Gender");
//get the removed item remove
System.out.println("Get item with key gender :: " + person.get("Gender"));
//get all items
System.out.println(person);
//remove all items
person.clear();
//get all items
System.out.println(person);
}
}
//output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}
Get item with key country :: Kenya
Get item with key gender :: null
{FirstName=Mercy, Country=Kenya, LastName=Jemosop}
{}

HashMap Size

To get the number of items use the size() method.

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);

//get number of items
System.out.println("Get the number of items :: " + person.size());
}
}
///output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}
Get the number of items :: 3

Loop Through a HashMap

for-each loop.Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:

Get Keys from a hashmap

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);

///loop through to get all items
for (String i: person.keySet()) {
System.out.println(i);
}
}
}
///output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}

FirstName
Country
LastName
Gender

Get values from a hashmap

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);

///loop through to get values from a hashmap
System.out.println("Get values :: ");
for (String i: person.values()) {
System.out.println(i);
}
}
}
///output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}
Get values ::
Mercy
Kenya
Jemosop
Female

Get both keys and values

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

HashMap<String, String> person = new HashMap<String, String>();
//Add Items
person.put("FirstName", "Mercy");
person.put("LastName", "Jemosop");
person.put("Gender", "Female");
person.put("Country", "Kenya");
//get all items
System.out.println(person);

System.out.println("Get keys and value :: ");
for (String i: person.keySet()) {
System.out.println("key :: " +i +" value :: " +person.get(i));
}

}
}
///output
{FirstName=Mercy, Country=Kenya, LastName=Jemosop, Gender=Female}

Get keys and value ::
key :: FirstName value :: Mercy
key :: Country value :: Kenya
key :: LastName value :: Jemosop
key :: Gender value :: Female

Java HashSet

This is a collection of items where every item is unique.

Add Items

The HashSet class has many useful methods. For example, to add items to it, use the add() method:

public class JavaHashSet {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<String>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
fruits.add("pineapple");
System.out.println(fruits);
}
}
///output
[orange, apple, pineapple, mango]

N.B though pineapple is added twice it only appears once in the set because every item in a set has to be unique.

Check If an Item Exists

use the contains() method to check if an item exists

public class JavaHashSet {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<String>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("orange");
fruits.add("pineapple");
fruits.add("pineapple");
System.out.println(fruits);
System.out.println("Check if hashset contains :: "+ fruits.contains("orange"));
System.out.println("Check if hashset contains :: "+ fruits.contains("banana"));
}
}
//output
[orange, apple, pineapple, mango]
Check if hashset contains :: true
Check if hashset contains :: false

Remove item

use the remove() method.

fruits.remove("mango")

Remove all items

use the clear() method

fruits.clear()

HashSet Size

Find out how many items there are in a set

fruits.size()

Java Iterator

This is an object that is used to loop through a collection.Iterating is a general term for looping.

Getting an Iterator

The iterator() method is used Iterator for any collection.

public class IteratorClass {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<String>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("pineapple");
fruits.add("orange");

// Get the iterator
Iterator<String> it = fruits.iterator();
// Print the first item
System.out.println(it.next());

}
}
//output
orange

Looping Through a Collection

To loop through a collection, use the hasNext() and next() methods of the Iterator:

public class IteratorClass {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<String>();
//add
fruits.add("mango");
fruits.add("apple");
fruits.add("pineapple");
fruits.add("orange");

// Get the iterator
Iterator<String> it = fruits.iterator();

//loop through a collection
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
//output
orange
apple
pineapple
mango

Remove an item from a loop

it.remove()

Iterator methods

hasNext()- Returns true if the iteration has more elements

next()- Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.

remove()- Removes the next element in the iteration. This method can be called only once per call to next().

read more on this

Java Wrapper Classes

They provide a way to use primitive types as objects.

example

//invalid
ArrayList<int> myNumbers = new ArrayList<int>();
//valid
ArrayList<Integer> myNumbers = new ArrayList<Integer>();

Creating Wrapper Objects

To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object:

Primitive Data — — — — — — — — Type Wrapper Class

byte — — — — — — — — — — — — — Byte

short — — — — — — — — — — — — — Short

int — — — — — — — — — — — — — — Integer

long — — — — — — — — — — — — — — Long

float — — — — — — — — — — — — — — Float

double — — — — — — — — — — — — — — Double

boolean — — — — — — — — — — — — — — Boolean

char — — — — — — — — — — — — — — Character

We use wrapper classes in instances where primitive types cannot to used.

To create a wrapper object, use the wrapper class instead of the primitive type. The following methods are used to get the value associated with the corresponding wrapper object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue().toString()

public class WrapperClass {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);

System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
///output
5
5.99
A
5
5.99
A

Java Exceptions

Java will normally stop and generate an error message resulting from coding errors made by the programmer, errors due to wrong input, or other unforeseeable thing.

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The try and catch keywords come in pairs:

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Example

The code below will result in an error. Exception will come in handy when handling instances like this

public class ExceptionsClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
//outputException in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
at com.example.JavaFundermentals.JavaFundermentals.ExceptionsClass.main(ExceptionsClass.java:6)
Process finished with exit code 1

Handle the error

public class ExceptionsClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}catch (Exception e){
System.out.println("System error occurred");
}
}
}
///output
System error occurred
Process finished with exit code 0

To get the exact error from exception, use the printStackTrace() method

public class ExceptionsClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}catch (Exception e){
e.printStackTrace();
System.out.println("System error occurred");
}
}
}
//output
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
at com.example.JavaFundermentals.JavaFundermentals.ExceptionsClass.main(ExceptionsClass.java:7)
System error occurred

Finally

This enables you to execute a code after try…catch regardless of the result.

public class ExceptionsClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[2]); // error!
}catch (Exception e){
e.printStackTrace();
System.out.println("System error occurred");
}finally {
System.out.println("The 'try catch' is finished.");
}
}
}
///output
3
The 'try catch' is finished.

The throw keyword

Throw statement allows you to create a custom error. It’s used together with an exception type e.g arithmeticException, FileException, ArrayIndexOutOfBoundsException, SecurityException

public class ExceptionsClass {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[ ] args) {
checkAge(16);
}
//output
Connected to the target VM, address: '127.0.0.1:56735', transport: 'socket'
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at com.example.JavaFundermentals.JavaFundermentals.ExceptionsClass.checkAge(ExceptionsClass.java:6)
at com.example.JavaFundermentals.JavaFundermentals.ExceptionsClass.main(ExceptionsClass.java:13)
Disconnected from the target VM, address: '127.0.0.1:56735', transport: 'socket'

Java Regular Expressions

This are sequence of characters that form a search pattern, it can be a single character or a more complicated pattern. It can be used to perform all types of text search and text replace operation.

You can import a regex package to work with regular expression in java. It includes the following packages: Pattern, Matcher and PatternSyntaxException

Example

Find out if there are any occurrences of the word “w3schools” in a sentence:

public class RegExClass {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
///output
Match found

The pattern is created using the Pattern.compile() method.The first parameter indicates which pattern is being searched for and the second parameter has a flag to indicates that the search should be case-insensitive. N.B The second parameter is optional.The matcher() method is used to search for the pattern in a string. It returns a Matcher object which contains information about the search that was performed.The find() method returns true if the pattern was found in the string and false if it was not found.

Flags

They change how search is performed in the compile() method.

Pattern.CASE_INSENSITIVE - The case of letters will be ignored when performing a search.

Pattern.LITERAL - Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.

Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to also ignore the case of letters outside of the English alphabet.

Regular Expression Patterns

Metacharacters

Metacharacters are characters with a special meaning:

| -Find a match for any one of the patterns separated by | as in: cat|dog|fish

. -Find just one instance of any character

^- Finds a match as the beginning of a string as in: ^Hello

$ -Finds a match at the end of the string as in: World$

\d -Find a digit

\s -Find a whitespace character

\b -Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

\uxxxx -Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

it defines quantities

n+ -Matches any string that contains at least one n

n* -Matches any string that contains zero or more occurrences of n

n? -Matches any string that contains zero or one occurrences of n

n{x} Matches any string that contains a sequence of X n’s

n{x,y} Matches any string that contains a sequence of X to Y n’s

n{x,} Matches any string that contains a sequence of at least X n’s

Java Files

File class allows us to work with files. To use the file class, create an object of the class and specify the filename or directory.

import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

Methods used in file class

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

Create a File

The createNewFile() method is used to create a file in java. It returns true for successs and false if file exists. This method is enclosed inside a try…catch block which throws an IOException if an error occurs.

N.B specify path

File myObj = new File("/home/mercy.jemosop/filename.txt"); // Specify the filename

Example

public class FileClass {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt"); // Specify the filename
if(myObj.createNewFile()){
System.out.println("File created :: "+ myObj.getName());
}else {
System.out.println("File already exists.");
}
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
///output
File created :: filename.txt

if you run the same command with the same name you will get file already exists.

Write To a File

We use FileWriter class with write() method to write some text on a file.N.B You can close a file with close method.

public class FileClass {
public static void main(String[] args) {
try {
File myObj = new File("/home/mercy.jemosop/filename.txt"); // Specify the filename
if(myObj.createNewFile()){
System.out.println("File created :: "+ myObj.getName());
}else {
System.out.println("File already exists.");
}
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
try{
FileWriter myObj = new FileWriter("/home/mercy.jemosop/filename.txt"); // Specify the filename
myObj.write("Hello World");
myObj.close();
System.out.println("Successfully wrote to the file.");
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
//output
File already exists.
Successfully wrote to the file.

“Hello world” will be printed inside filename.txt

Java Read Files

We use the Scanner class to read the contents of a file. This file contains the general flow create file, write to a file and read contents of a file.

public class FileClass {
public static void main(String[] args) {
//create a file
try {
File myObj = new File("ilename.txt"); // Specify the filename
if(myObj.createNewFile()){
System.out.println("File created :: "+ myObj.getName());
}else {
System.out.println("File already exists.");
}
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
//write to a file
try{
FileWriter myObj = new FileWriter("filename.txt"); // Specify the filename
myObj.write("Hello World");
myObj.close();
System.out.println("Successfully wrote to the file.");
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
//read contents of a file
try{
File myObj=new File("filename.txt");
Scanner myReader=new Scanner(myObj);
while (myReader.hasNext()){
String data=myReader.nextLine();
System.out.println(data);
}
myReader.close();
}catch (FileNotFoundException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
//output
File created :: yourfile.txt
Successfully wrote to the file.
Hello World

Get File Information

We use the File methods to get more information about a file.

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

File myObj = new File("yourfile.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
//output
File name: yourfile.txt
Absolute path: /home/mercy.jemosop/Tutorial/JavaFundermentals/yourfile.txt
Writeable: true
Readable true
File size in bytes 0

Delete a File

We use the delete() method

public class FileClass {
public static void main(String[] args) {
//delete a file
File file = new File("ilename.txt");
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
//output
Deleted the file: ilename.txt

Delete a Folder

public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}

N.B to delete a folder it must be empty.

This marks the completion of my w3school java tutorial. If you are new to java and want to improve your skills, search for w3schools or any other courses. This was a free course.

Go take that course of your choice and learn those fundermental concepts. Happy coding!!!!!!!!!!!!

source

--

--

Mercy Jemosop
Mercy Jemosop

Written by Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy

No responses yet