Java - I

aigle-levant · August 9, 2024

Here’s my revision notes for Java…

Characteristics of Java

alt text

  • Platform independent : Programs are compiled into bytecode and can be run on any platform using a virtual machine.
  • Object-oriented : Java is one of the most recommended languages for learning OOP.
  • Simplicity : Simple and easy to use.
  • Familiarity : Familiar to C++, C programmers
  • Robustness : Has features like automatic garbage collection and exception handling
  • Security : Built-in security features and private and public classes.

Robustness : The ability of a system, model, etc. to perform effectively and without failure when its variables are altered.

Bytecode

Bytecode is a set of instructions for Java Virtual Machine [JVM] received after the compiler compiles a program.

This appears in form of the .class file next to a Java program [we can’t open it as it IS technically machine code]. JVM tells the processor how much resources are to be allocated to it for calling the program.

After that, bytecode is interpreted into actual machine code [binary] and then program is executed.

Principles of OOP

  • Encapsulation : Bundle data and methods into a single unit called class; hide the inner workings of a class and show only what is necessary to the end user
  • Inheritance : A class [child] can re-use attributes and methods from another class [parent or super-class]
  • Polymorphism : Objects of different classes can share a method or two; can be treated as members of a common super-class; supports method overloading
  • Abstraction : Hiding the program’s complexities from the user; show only what’s necessary

Benefits

  • Modularity : Program is split into separate modules
  • Re-usability : Classes and objects can be re-used across different programs
  • Maintainability : Code’s more organised and easier to modify
  • Scalability : Applications can scale up or down according to system

Class fundamentals

A class is a blueprint for creating an object.

public class coffee
{
    private String brand;
    private double price;

    public coffee(String brand, double price)
    {
        this.brand = brand;
        this.price = price;
    }

    //object reference variables or getters
    public String getBrand()
    {
        return this.brand;
    }
    public double getPrice()
    {
        return this.price;
    }
    public void setBrand(String brandName)
    {
        this.brand = brandName;
    }

    public String toString()
    {
        return (getBrand() + " -- " + getPrice());
    }
}

An object is an instance of an class [or rather, a way to implement features of a class into our program]. Its state, type and actions are determined by its class.

An object is brought into life using a constructor, a special method that creates an object out of its instance variables.

public class coffee
{
    private String brand;
    private double price;

    public coffee(String brand, double price)
    {
        this.brand = brand;
        this.price = price;
    }
}

this is a keyword that refers to an object’s instance.

Attributes are the properties of an object. They’re also called its instance variables.

Actions are defined by the methods in the class. Methods are named literals acting like functions inside a class that can be called using an object.

coffee cappuccino = new coffee("Cappuccino", 250.50);

System.out.println(getBrand());

System.out.println(cappuccino);

Getters [also known as object reference variables] are methods used to ‘get’ a value from the object [usually its instance variables]. This allows us to maintain the principle of encapsulation.

coffee cafe = new coffee("Cappuccino", 250.50);

System.out.println("Coffee name?");
String str = scanner.nextLine();

cafe.setBrand(str);

Method overloading

It is the process of defining multiple methods for different purposes. First, let’s try using our constructor method :

public class coffee
{
    private String brand;
    private double price;
    private double rating;

    public coffee(String brand, double price, double rating)
    {
        this.brand = brand;
        this.price = price;
        this.rating = rating;
    }
    public coffee(String brand, double price)
    {
        this(brand,price,0);
    }
}

Now let’s try using methods :

public class coffee
{
    //statements go here
    public double orderSum(double a, double b)
    {
        return (a+b);
    }
    public double orderSum(double a, double b, double c)
    {
        return (a+b+c);
    }
}

Objects as parameters

We can use objects as our parameters. Here’s how we do to compare two objects :

public boolean checkEqual(coffee compareOrder)
{
    if (this == compareOrder)
    {
            return true;
    }
        
    coffee order = (coffee) compareOrder;

    if (this.brand.equals(order.brand) && this.price.equals(order.price))
    {
        return true;
    }
    return false;
}

We can also return objects.

public class coffee
{
    //statements go here
    public void createOrder(String brand, double price)
    {
        return new coffee(brand, price);
    }
}

Access controls

These control the visibility of class members.

  • public : Accessible from anywhere
  • private : Accessible only within the class
  • protected : Accessible within the package and included sub-classes
  • (default) : Accessible within same package

A package is a folder inside which classes are stored. We have to include package folderName; at the top of our program in case it’s inside a folder.

final

This attribute prevents a variable’s value from being changed.

static

This makes a class member belong to a class rather than the instance of a class [which is an object].

Recursion

It is a process where a method calls itself until the base condition is reached.

Statements in Java

Control statements

If statement

if (str.equals(""))
{
    break;
}

If else statement

if (str.equals(""))
{
    break;
}
else
{
    continue;
}

If else-if ladder

if (str.equals(""))
{
    break;
}
else-if (str.equals("No"))
{
    System.out.println("Are you sure?");
    if (scanner.nextLine.equals("Yes"))
    {
        break;
    }
    else
    {
        continue;
    }
}
else
{
    continue;
}

Iterative statements

For loop

for (int i=0; i<=arr.length; i++)
{
    System.out.print(i);
}

While loop

int i=10
while (i>0)
{
    System.out.println("Real");
    i--;
}

Do-while loop

int i = 10;
do
{
    System.out.println("Real");
    i--;
}
while (i>0);

For-each loop

for (coffee i:list)
{
    System.out.println(i);
}

Type conversion

Type conversion refers to conversion of a variable’s data type to another data type.

Implicit conversion or widening

This is automatically done when converting from a smaller to a larger type.

int sum = 10;
double percentage = sum / 100;

Explicit conversion or narrowing

This is done manually when converting from a larger to a smaller type using a technique called casting

int sum = 10;
int n = 4;
double average = (double) sum / n;
int number = (int) average;

Arrays

Arrays are used to store multiple values of the same type in a single variable. They have a fixed size.

//single-dimensional
int[] list = new int[5];
list[0] = 1;

int[] listDeux = {1,2,3,4,5};

//multi-dimensional
int[][] multiList = new int [2][3];
multiList[0][1] = 100;
//printing array elements using a for-loop
int[] listDeux = {1,2,3,4,5};
for (int i=0; i<=list.length; i++)
{
    System.out.println(i);
}