Mark As Completed Discussion

What is Java?

Java is an object-oriented programming language developed by James Gosling and his colleagues at Suns Microsystems in the early 1990s. Java was designed to be a programming language for highly efficient applications that emphasize reliability and reusability. The language itself borrows most of its syntax from C and C++ but has a simpler object model and fewer low-level facilities.

Since it is a well-structured, object-oriented language, Java code is relatively easy to maintain and modify. The only requirement is having JRE or Java Runtime Environment installed on the system. It runs on multiple platforms such as Windows, Mac, and Linux(irrespective of the operating system or architecture of the device).

According to The Java Language Environment, There were five main goals in mind in the creation of Java:

  1. It should allow the same program to be executed on multiple operating systems.
  2. It should be easy to use by selecting what was considered the good parts of other object-oriented languages
  3. It should follow the object-oriented programming methodology 4) It should be designed to run code from remote sources securely 5) It should contain built-in support for using computer networks

With that being said, Java is one of the most useful programming languages for any new developer to learn. Not only it is highly in-demand among employers and larger organizations but it is one of two primary programming languages used for Android development.

In contrast to languages such as Python or R, Java is one of the harder programming languages to pick up, especially if you're learning it for the first time. Java does a few things that make it tricky for example object-oriented structure is often unintuitive and syntax requirements can be rigid. However, learning Java is a masterclass in programming.

Primitive Data Types

Let's start by diving into the primitive data types that Java offers.

The primitive data types include byte, short, int, long, float, double, boolean, and char. The primitive data type specifies the size and type of variable values.

byte

A Byte data type is used to save space in larger arrays in the place of integers. A byte is four times smaller than an integer. The default value of a byte is 0.

byte b = 90 ;

short

A short data type can be used to save memory similar to a byte data type. A short is two times smaller than an integer. The default value of a short is 0.

short s = 1200;

int

An integer is the conventionally used default data type for values unless there is a concern about memory. The default value of an integer is 0.

int var = 5;

long

A long is a type used when a wider range than an int is needed. The default value of a long is 0L.

long l = 1000l;

float

A float is mainly used to save memory in large data structures of floating point numbers or to represent a collection of floating point numbers. The default value of a float is 0.0f.

float f = 3.14f

boolean

A boolean data type is used for flags that examine true or false conditions. There are only two possible values: true and false. The default value is false.

boolean var = true;

double

A double is generally used as the default data type for decimal values. It can be used to represent both floating point and decimal numbers. The default value is 0.0d.

double d = 1000.2;

char

A char is used to store any character.

char ch= 'A';

Referential or Non Primitive types

The referential types include Strings, Classes, and Objects. They are called referential types because they refer to objects. Most of the time they are types created by the programmer and not defined by Java except for Strings. The default value of any referential type is null.

SNIPPET
1Employee employee = new Employee("David Johnson");
2
3String str = "AlgoDaily";

Variables

A variable in Java is a name that is associated with a value that can be changed.

Variables in Java refers to the name of the reserved area in memory. The variable name is a reference to the value stored in memory.

There are 3 types of variables in Java:

  1. Local variables
  2. Instance variables
  3. Static variables

Local variables

Local variables are declared in a method within a class. The scope is limited to the method which means you can't their values and access them outside of the method.

In this example, the instance variable and local variable have the same name. If I had not declared the instance variable and only declared the local variable then the print statement would have thrown an error. Even if they have the same name, you cannot change and access local variables outside the method.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Instance Variables

Instance variables are declared inside a class but outside a method, constructor, or block. Each instantiated object of a class has a separate copy of that variable. When you create a new object of a class you create an instance.

Let's look at this Vehicle Class. We have two instance variables vehicleName and numWheels.

TEXT/X-JAVA
1public class Vehicle {
2
3    private String vehicleName;
4
5    private int numWheels;
6}

If we were to create two Vehicle objects

TEXT/X-JAVA
1Vehicle car = new Vehicle();
2Vehicle van = new Vehicle();

Then each vehicle would have its own number of wheels and name. So the value stored inside vehicleName and numWheels would vary for different vehicles.

Static Variables

Static variables are also known as class variables because they are associated with the class. They are declared with the static keyword in a class but outside of a method, block or constructor. There would only be one copy of each static variable per class regardless of how many objects are created from it.

As you can see, the var variable above was declared with the keyword static and within class scope. The variable was accessed and modified by the exam and exam2 variables. Notice that once the value of the var variable was changed using exam2, both objects accessing the var variable now had the same value.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

User Input

In Java, there are three ways to take in user input:

Using Scanner

TEXT/X-JAVA
1import java.util.Scanner;
2
3public class Example {
4
5    public static void main(String[] args) {
6
7        Scanner scan = new Scanner(System.in);
8
9        //Reads a String value from the user
10        String str = scan.nextLine();
11
12        //Reads a double value from the user
13        double db = scan.nextDouble();
14
15        //Reads a boolean value from the user
16        boolean bool = scan.nextBoolean();
17
18        //Reads a float value from the user
19        float fl = scan.nextFloat();
20    }
21}

Using the Console class

TEXT/X-JAVA
1import java.io.Console;
2
3public class Example {
4
5    public static void main(String[] args) {
6
7        Console c = System.console();
8
9        System.out.println("What's your favorite language and why is it java?:");
10
11        String n = c.readLine();
12
13        System.out.println(n);
14
15
16    }
17
18}

Using the BufferedReader class

TEXT/X-JAVA
1import java.io.BufferedReader;
2import java.io.InputStreamReader;
3
4public class Example {
5
6    public static void main(String[] args) {
7
8        InputStreamReader input = new InputStreamReader(System.in);
9
10        BufferedReader bf = new BufferedReader(input);
11
12        System.out.println("What is your name?");
13
14        String name = bf.readLine();
15
16        System.out.println(name);
17    }
18
19
20
21}

A Basic Program in Java

A basic program in Java will have at least the following components:

  1. Classes and Objects
  2. Variables
  3. Methods
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Compiling a Java program

In order to compile a Java program, you must save the program by using the name of the class and .java as the extension.

Compilation

Then the compiler must be called using the javac command.

Compilation

Then the java program is executed using java classname

Compilation

Iterative Statements

Iterative statements are used when you need to keep repeating statements until the condition for termination is not met. These types of statements are normally exhibited in:

1) for loops

  • For loops are used for definite loops where the number of iterations is known.

  • A for loop starts with an initialization followed by a condition and increment/decrement.

Consider a simple for loop that prints numbers from 1 to 10.

Iteration

The FizzBuzz problem as explained on our AlgoDaily Youtube channel(https://youtu.be/giS2G3TCmWI) is a classic example of using for loops to solve a problem.

TEXT/X-JAVA
1public class fizzbuzz {
2
3    public static void main(String[] args) {
4        for (int i = 1; i <= 100; i++) {
5
6            if (i % 3 == 0 && i % 5 == 0) {
7
8                System.out.println("FizzBuzz");
9            } else if (i % 3 == 0) {
10
11                System.out.println("Fizz");
12            } else if (i % 5 == 0) {
13
14                System.out.println("Buzz");
15
16            } else {
17
18                System.out.println(i);
19            }
20
21        }
22    }
23}

In this program, the statements are repeated until the conditions are met. The fizz buzz program details what numbers are divisible by 3, 5, and both 3 and 5. However, as aforementioned, see a more detailed explanation from the AlgoDaily youtube channel.

2) While loops

  • While loops are used when the number of iterations is not known.

  • In contrast to for loops, there is no built-in loop control variable.

TEXT/X-JAVA
1public class Example {
2
3    public static void main(String[] args) {
4        int i = 0;
5
6        while (i < 11) {
7
8            System.out.println(i);
9            i++;
10
11        }
12
13    }
14
15}

The above example shows the condition specified within the loop. While the number i is less than 11 then the print statement is continuously executed. The i is used as a built in control variable.

3) Do while loops

  • Do while loops follow a similar structure as while loops however the statement is executed first before evaluating the condition.

In the example attached, we are printing the value of the i and incrementing first. Then check the condition in the while looking to see if the number i is less than 11.

Decisive Statements

These statements are used when you need to decide between alternative actions during the execution of a program. They allow you to control the flow of execution depending on the conditions known only during runtime

1) if statements

  • An if statement is the most simple decision making a statement in Java.

  • We can use this to decide whether a certain statement or block of statements will be executed or not.

  • Simply, if a condition is true then the block statement will be executed otherwise it is not.

Conditionals

In the example below, we are checking to see the given grade is enough to pass.

TEXT/X-JAVA
1public class Example {
2
3    public static void main(String[] args) {
4        int grade = 85;
5
6        //condition
7        if (grade > 50) {
8
9            System.out.println("You have passed the final exam!");
10        }
11
12    }
13}

The value of grade is 85. Since 85 is greater than 50, then the condition is true and we print the statement.

2) else/ if else/ statements

Combining an else and an if to make an else if statement creates a whole range of mutually exclusive possibilities.

Conditionals

In the example below, we are checking to see the age given is proper drinking age.

As you can see, the conditions in both the if and else if statements were false, so we automatically executed what is inside the else after checking.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Arrays

Arrays

Arrays in Java are the most primitive way of aggregating elements of the same datatypes.

So how does an array work?

TEXT/X-JAVA
1String [] lang = {"Java", "C++", "Python"};

Array types are signalized using the brackets [] and created using the curly brackets. Looking at the snippet, you can see that declaring and assigning values to an array in java is different from the way we do with single value variables.

  1. The data type of the array, String is declared followed by square brackets, [], which is the symbol for arrays in java that is used to represent an index in an array.

  2. This is followed by the name of the array,lang.

  3. The assignment operator, =.

  4. And finally the values to be stored in the array which is surrounded by a set of curly braces, {"Java", "C++", "Python"};

We use curly braces to write out a series of related values to be stored in an array in java. However, curly braces are not the only way to store values in an array.

TEXT/X-JAVA
1String [] lang = new String[5];
2
3lang[0] = "Java";
4
5lang[1] = "C++";
6
7lang[2] = "Python";

Notice how on the right hand side, we used the keyword new. This keyword is used to create objects in java.

More about arrays

  • Arrays are very useful when you have a large number of variables and you have to initialize them.

  • Arrays index starting from 0 which means that if there n numbers present in the array then the index of the last element of the array is n-1.

  • The size of the array must be initialized by an int value.

Single Dimensional(1-D array)

A Single Dimensional array is a type of linear array in which elements are stored in a continuous row.

Single dimensional arrays have two components: data type of the array(int, char, float, etc) and name(int [] arr or int arr [].

The declaration establishes the variable arr is an array variable but no array actually exists. It simply tells the compiler that the arr variable will hold an array of type integer. To link arr to an actual physical array of integers, we would have to instantiate the array.

TEXT/X-JAVA
1//Creating and Initializing an array of size 5
2
3int [] arr; // array declaration
4
5arr = new int [5]; //allocating memory to array
6
7int [] arr = new int [5]; //declaring and instantiating array at the same time
8
9
10int [] arr2 = new int []{1,2,3,4,5}; //initializing array

The elements in the array allocated by the keyword new will automatically be initialized to zero for number times, null for referential types, and false for boolean types.

Accessing a Specific Element in an Array

As mentioned before, we can access the specific element by its index within square brackets. Let's say we want to print the month May from the example below.

TEXT/X-JAVA
1public class Example {
2    public static void main(String[] args) {
3        String[] months = new String[] {
4            "January",
5            "February",
6            "March",
7            "April",
8            "May",
9            "June",
10            "July",
11            "August",
12            "September",
13            "October",
14            "November",
15            "December"
16        };
17
18        System.out.println(months[4]);
19    }
20}

Since May is at the 4th index, then having months[4] inside the print, statement would output May.

But what if we wanted to access all the elements of the array? Well, we could use a for loop to traverse all the elements in the array.

TEXT/X-JAVA
1for( int i = 0; i<months.length; i++){
2
3  System.out.println(" Month in " + i + "index is " + months[i]);
4}

The for loop starts at 0 and ends at months.length-1 since we use i<months.length, which shows that we want to stop at one less than the actual length of the array. If we write i ≤ months.length, then the JVM(Java Virtual Machine) would throw an ArrayOutOfBoundException, which shows that the index of an array is negative or greater than or equal to the length of an array which is known as the illegal index of an array.

Multidimensional or 2-D array is an array where elements are stored in rows and columns.

Strings

Strings in Java are objects that represent a sequence of char values. A String can be created in two ways:

  1. Using a literal

  2. Using new keyword

TEXT/X-JAVA
1String str = "Hello World"; //using literal
2
3String website = new String("AlgoDaily"); //using new keyword

Note that the java.lang.String class implements Serializable, Comparable, and CharSequence interfaces. Since the String object is immutable(unable to be changed) in nature Java provides 2 utility classes:

  1. StringBuilder, which is a mutable class that is not thread-safe but is faster and used in single-threaded

  2. StringBuffer, which is a mutable class that is thread-safe and synchronized.

Below are some of the most useful String methods:

Object-Oriented Programming

Java is an OO language as it is modeled and organized around objects rather than actions and data rather than logic. OOP in java aims to implement real-world entities such as objects, classes, abstractions, inheritance, and so on.

Java classes

A class in Java is a blueprint that includes all your data. A class contains variables and methods that describe the behavior of an object.

TEXT/X-JAVA
1class Vehicle {
2
3    //variables
4    private int numWheels;
5    private String name;
6
7    //methods
8    public String getName() {
9        return name;
10    }
11
12    public void setNumWheels(int numWheels) {
13        this.numWheels = numWheels;
14    }
15
16
17}

Objects

An object is an instance of a class that can access your data. The keyword new is used to create the object.

TEXT/X-JAVA
1//Declaring and initializing an object
2Vehicle v = new Vehicle();

Java Constructors

A constructor is a block of code that initializes a newly created object. It is basically a method but doesn't have any return type and has the same name as it's class. There are two types of constructors in Java:

1) Default Constructor

The default constructor is created by default by the java compiler at class creation if no other constructor is declared in the class. It doesn't contain any parameters which is why it is sometimes referred to as the no-argument constructor.

TEXT/X-JAVA
1public class Vehicle {
2
3    //default constructor
4    public Vehicle() {}
5
6}
7
8public class Driver {
9
10    public static void main(String[] args) {
11
12        //creating vehicle object using default constructor
13        Vehicle vehicle = new Vehicle();
14    }
15
16}

2) Overloaded Constructor

The overloaded constructor contains one or more parameters. It is used to provide different values to the distinct objects at the time of their creation.

TEXT/X-JAVA
1public class Vehicle {
2    int numWheels;
3    String color;
4    int numDoors;
5
6    //overloaded constructor
7    public Vehicle(int numWheels, String color, int numDoors) {
8
9        //keyword this points to current object
10
11        this.numWheels = numWheels;
12        this.color = color;
13        this.numDoors = numDoors;
14    }
15
16    //toString() method used get value of instance variables
17    public String toString() {
18
19        String s = "number of wheels" + numWheels +
20            "color:" + color + "number of doors:" + numDoors;
21
22        return s;
23    }
24}
25public class Driver {
26
27    public static void main(String[] args) {
28
29        Vehicle car = new Vehicle(4, "red", 4);
30        Vehicle truck = new Vehicle(12, "black", 2);
31
32        System.out.println(car.toString());
33        System.out.println(truck.toString());
34    }
35
36}

The 4 basic principles of Object-Oriented Programming

Object Oriented Programming

1) Polymorphism is the ability of a variable, function, or object to take multiple forms. It allows you to define one interface or method and have multiple implementations. Polymorphism is characterized by the method overloading and method overriding.

Method Overloading

Method Overloading is the act of having the same function name but differs in number and type of arguments within the same class.

TEXT/X-JAVA
1public class Example {
2
3    public int sum(int a, int b) {
4        return a + b;
5
6    }
7
8    public int add(int a, int b, int c) {
9        return a + b + c;
10    }
11
12
13}

Method Overriding

Method Overriding is the specific implementation of a method in a child class which is already defined in the parent class.

TEXT/X-JAVA
1public class Vehicle {
2
3    //Overriden method
4
5    public void drive() {
6
7        System.out.println("Vehicle is driving");
8
9    }
10}
11
12public class Car extends Vehicle {
13
14    //Overriden Method
15
16    public void drive() {
17
18        System.out.println("Car is driving");
19
20    }
21
22}

As you can see, the child class Car inherited the drive method from its parent class Vehicle. However, we can change the functionality of the method while keeping the same method signature.

2) Abstraction is a concept of hiding the details and showing only the necessary things to the user. We use an abstract class/Interface to express the intent of the class rather than the actual implementation.

An Abstract class is a class which is declared with an abstract keyword and cannot be instantiated.

TEXT/X-JAVA
1public abstract class Example{
2
3  public void display();
4
5  public int sum(int a, int b);
6
7}

An interface is a blueprint that contains static constants and abstract methods.

TEXT/X-JAVA
1public Interface VehicleInterface {
2
3    //methods in an interface does not have a body
4    public void displayVehicle();
5    public boolean isAutomatic();
6
7}
8
9public class Vehicle implements VehicleInterface {
10
11    public void displayVehicle() {
12
13        //The body of displayVehicle goes here
14
15        System.out.println("This is a car");
16
17
18    }
19
20    public boolean isAutomatic() {
21
22        //The body of isAutomatic goes here
23
24        return true;
25    }
26}

3) Inheritance

Inheritance is a concept where the properties of one class can be inherited by the other. It helps with reusability and establishes a relationship between different classes. The relationship is established in code using the keyword extends.

TEXT/X-JAVA
1public class Person {
2
3    private int pID;
4    private String name;
5
6    Person() {
7        pID = 4;
8        name = "Brian";
9    }
10
11    Person(int pID, String name) {
12
13        this.pID = pID;
14        this.name = name;
15    }
16
17}
18
19public class Student extends Person {
20
21    public void displayName() {
22
23        System.out.println(super.name);
24    }
25
26
27}

In this example, the child class Student inherits attributes from it's parent class, Person. As stated above the relationship is established using the keyword extends. The super keyword in java acts as a reference variable that is used to refer to parent class objects.

The displayName() method would print the value of name that is inherited from the Person class.

4) Encapsulation

Encapsulation is a process of hiding data implementation by restricting access to public methods. The instance variables are kept private and the accessor methods(getters and setters) are made public.

One Pager Cheat Sheet

  • Java is a highly efficient, object-oriented programming language developed by James Gosling at Sun Microsystems that is designed for reliability, reusability, and security.
  • Java offers 8 primitive data types: byte, short, int, long, float, double, boolean, and char that are used to store values of various sizes and types.
  • Referential types like Strings, Classes, and Objects, which are created by the programmer, have a default value of null and refer to objects.
  • Variables in Java are references to memory which are declared in different scopes (Local, Instance, Static) and cannot be accessed beyond their scope.
  • Instance variables are declared inside classes and have different values for each instantiated object, while static variables are shared among all instances of a class.
  • In Java, user input can be taken in three ways: Using Scanner, Console class, and BufferedReader class.
  • A Java program consists of Classes, Objects, Variables and Methods.
  • In order to compile a Java program, you must save it as a .java file and then call the compiler with the javac command before running it with the java command.
  • Iterative statements, such as for and while loops, allow us to repeat statements until a certain condition is met, such as in the classic Fizz Buzz problem.
  • Decisive Statements in Java, such as if and else if statements, allow you to control the flow of execution depending on conditions known only during runtime.
  • Arrays in Java are the most primitive way of aggregating elements of the same datatypes and can be declared and initialized either with curly braces or the new keyword.
  • Strings in Java are immutable objects represented by the java.lang.String class, which implements the Serializable, Comparable, and CharSequence interfaces, and Java offers two mutable utility classes: StringBuilder and StringBuffer, with the latter being thread-safe.
  • Java is an Object-Oriented programming (OOP) language with classes, objects, constructors, and methods used to implement the four basic principles of OOP, namely polymorphism, abstraction, inheritance, and encapsulation.