Page cover image

🍵Fundamental Java Concepts and Practices

Personalized Java learning notes encompass foundational concepts including types, loops, conditionals, input handling, arrays, strings, and essential operations

Java

  • Anatomy of JAVA:

    • Every code should have a function called main.

    • Function in a class is called METHODS.

    • Every code should have a class which is called Main.

    • fields are the variables in a class.

    • private, public, and final.

    • Access modifiers: means that a class or a function can use the class functions or their methods (Private & Public).

    • Naming Conventions:

      • PascalNamingConvention - Classes

      • camelNamingConvention - Methods

    • void means this function is not going to return a value.

    • PACKAGES > CLASSES > METHODS / FUNCTIONS.

    • After running the compiler, the compiler turns the main.java file to main.class file which is BYTE CODE. That bytecode can run on every operating system that has JRE (Java Runtime Environment).

    • JVM - Java Virtual Machine converts that ByteCode or the .class file into native operating system language, so that it can run that code.

    • javac - for compiling the .java file.

    • java - to run the file. Write like this: com.package.Mainclass.

    • sout

Java:

  1. Java was developed by James Gosling in 1995.

  2. The acquisition of Sun Microsystems by Oracle Corporation was completed on January 27, 2010.

    • JAVA EDITIONS:

      • Standard Edition (SE): This contains all libraries that a JAVA developer should know.

      • Enterprise Edition (EE): This is used to create industry-level applications. Also, it is based upon Standard Edition, but it contains more libraries that help to create high-level applications.

      • Micro Edition (ME): This is specifically designed for mobile devices and contains libraries that are necessary to build mobile devices.

      • Java Card (JC):

  • Types:

    • int is the type of the data, and age is called an Identifier (also called a Label) because that points to the data. = is the assignment operator.

int age = 30;

Two Types:

  1. Primitive Types: for storing simple values.

  2. Reference Types: for storing complex values.

Primitive Types:

Type
Bytes
Range

Byte

1

[-128, 127]

Short

2

[-32K, 32K]

Int

4

[-2.15B, 2.15B]

Long

8

[-9.22QT, 9.22QT]

Float

4

[-2.15B, 2.15B]

Double

8

[-9.22QT, 9.22QT]

Char

2

A, B, C, ...

Boolean

1

True, False

  • We can use _ to give space in numbers.

  • By default, JAVA sees every value as an integer. So, even if you give a long or double float, the Java compiler will think that this is an integer. Thus, you need to add a suffix, which goes like this: L for long.

  • Double takes 8 bytes and is too large. Prefer float for short values.

  • By default, a decimal number is taken as a double, so suffix it with F/f for float.

  • Default decimal values are also double, so add suffix F to represent float. This can be capital or small.

  • CHAR = 'A' & "Akash Kumar" ⇒ For single character, use single quotes; for words or big strings, use double quotes.

Reference Types:

  • In primitive Types, we store data like numbers, characters, and booleans. In Reference Type, we store complex data, like a mail message.

  • Declaring Reference Types is not like Primitive Types.

  • We have imported this Class, now we can use the members of this Object or Instance.

  • Now, Variable is an INSTANCE of Date Class.

  • They store the address of the date. That’s why it’s called Reference Types.

  • In primitive Types, if we do this, the value doesn’t change.

Date now = new Date();
  • They store the address of the date. That’s why it’s called Reference Types.

  • In primitive Types if we do this, the value doesn’t change.

byte x = 1;
byte y = x;
x = 2;
System.out.println(y);

////////////////////////////////////////

Point pointak = new Point(1,2);
Point pointka = pointak;
pointak.x = 2;
System.out.println(pointka.x);

// This 1 and 2 are arguments of the parameters x and y 
  • But in Reference Types, those x and y will point or address to the same address. That means if I change the values of one variable, the other will be changed and visible.

  • Because they are pointing to the same Address.

  • References Values are copied by their reference, the data and the changes are visible. In Primitive Types, the Values are independent.

Strings:

Even though we can declare the variable without the new operator thing, we can directly give out string like a primitive type, but at the end, this is a Reference Type.

We can use directly String message = "Hello world".

String message = new String("Hello world"); // or we can use directly String message = "Hello world"
System.out.println(message);

////////////////////////////////////////////////////////////

message.replace("!", "*");
message.length(); // for getting the length of the string
message.indexOf("a"); // as from its name, it gives the index of the arguments
message.toLowerCase(); 
message.trim(); // remove the extra whitespaces from the beginning and at the ends

To Escape the Double Quotes we need to add \ as shown below:

String message = "Hello \"World\"";
System.out.println(message);
String message = "Hello \\window\\";
String message = "Hello \nwindow\\"; // for new line
String message = "Hello \twindow\\"; // for a tab

For specifying the Backslash, we need to escape the same backslash with another .

  • IN Java, the strings are immutables, which means we can’t change them.

  • Any method that changes the values of the strings, gives us a new string or we can say a copy of that string.

Arrays:

  • Arrays are also Reference Types.

  • When we print the arrayVariableName, it prints a string that is calculated based on the address of the object in memory.

  • If we create another object or array and then print their value, we will get another value because they both are at different addresses in memory.

  • But if we want an output like in Python [1, 2, 3, 4],

    • We need to import java.util.Arrays and then use a method called Arrays.toString() and pass the array name.

    • This method gets the arguments from almost all primitive types and then prints the value like [1, 2, 3, 4].

  • If we have initialized the value of the array, we will see that; if not, we will see 0 zeros in an integer array, empty strings "" in strings array, and false in a boolean array.

  • We can assign the array with values at the time we are declaring that array, just like this, but only if we know the values:

    • int[] arr = {1, 2, 3, 4, 5, 5}

  • Arrays are of fixed length size; after initializing, we cannot change.

  • While Printing the Value of Multi-Dimensional arrays, use Arrays.deepToString() then the name of the array.

  • Use final for constants, and for all constant variables, use uppercase naming convention. So instead of naming a variable pi, we will name the variable PI.

int[] arrayVariableName = new int[passTheSizeOfTheArray];
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; 
 // Declaring array literal
.sort();
// When we do this
Arrays.sort(intArray);
// The intArray is changed and sorted.

Dimensional Array


int[][] twoDArray = {
    {1, 2, 3},
    {4, 555, 6},
    {7, 8, 9}
};

// Printing elements of the array
System.out.println("Elements of the 2D array:");
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        // Accessing and printing elements using row and column indices
        System.out.print(twoDArray[i][j] + " ");
    }
    System.out.println(); // Move to the next line after printing each row
} // Ends the For LOOP
System.out.println(twoDArray[1][1] + "This is the First Row and the First Column");

Example For TwoD Arrayss.


import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Creating a 2D array of integers with 11 rows and 11 columns
        int[][] twoDimensionalArray = new int[11][11];

        for (int  i=1; i < twoDimensionalArray.length; i++){
            for (int j=1; j < twoDimensionalArray.length; j++){
                twoDimensionalArray[i][j] = i * j;
            } // Ends j loop
        } // Ends i Loop

        // Now Let's Print this Crazy Things
        for (int i = 1; i < twoDimensionalArray.length; i++){
            for (int j = 1; j < twoDimensionalArray.length; j++){
                System.out.printf("%4d",  twoDimensionalArray[i][j]);
            }
            System.out.println();
        }
    }
}

Arithmetic Operations:

  • The incrementor can be postfix {x++} and prefix {++x}.

  • This means if we do an assignment to a variable, like y, and then use postfix, the value of y will be the value of x without being incremented, because the value that will be copied is not incremented. After the assignment, the value of x will be incremented.

  • Now, as it defines prefix, it will first increment the value of x and then assign it to y.

  • We can use augmented operators like in Python in Java.

int x = 1;
int y = x++;

// x = 2 & y = 1

int x = 1;
int y = ++x;

// x = 2 & y = 2

x = x + 2;
x += 2;

// It's the same

Casting:

  • Casting, Widening Casting, or Implicit Casting means casting a variable that is of lower values to higher variables' values so that we don't get any errors.

  • For example, if I have a short variable, which means that I've allocated 2 bytes for that variable, then I try to assign the value of an int to it, which is a 4-byte memory, Java will see that the lower value variable can be added to the larger one.

  • So, it will create an anonymous variable with the same value of that short number and then add it to the int.

  • byte > short > int > long > float > double

  • We can convert strings into other primitive types using the wrapper classes like Integer.parseInt, Short.parseShort.

  • When we pass the strings as arguments, it will give the value.

short x = 2;
int y = x + 1;

// We'll not get any error.
// It happens only if the conversion is from low to high, means that short (2 bytes) from int (4 bytes).
// The integer is less precise than a decimal, so the casting happens and the int is converted to a float or double for the work we want.

double x = 3.3;
double y = x + 2;
// 2 will be casted and becomes 2.0
double x = 3.3;
int y = (int) x + 2;
// Now, we have casted this double to an int, then it will cast to int

Math Class:

  • .floor

  • .ceil

  • .round

  • .abs

  • .min and .max

  • It's straightforward, but we need to pay attention to casting.

  • Some methods are overloaded, meaning take care of the casting.

Math.random:

  • Store it to a double because it gives double values.

  • It simply creates values from 0 to 1 in decimals.

  • If we want a number bigger than that, just multiply that with that number.

  • Sometimes, the casting will not work directly, but we know that. We will just cast them because the Math.random returns double, and we can't store it into int according to the compiler or IDE.

  • But we will just cast that into int.

double random = Math.random() * 100;
// Gives us the random values till 100.
// But those values are with decimals; we can round them, and after rounding, they will have a .0 fraction because it's a double. So just cast it to int.

int number = (int) (Math.round(Math.random() * 99) + 1);
// It contains numbers from 1 to 100 (inclusive), so use the above line

NumberFormat

  • We cannot create a new instance of NumberFormat because it’s an abstract class (just so you know).

  • For now, we will use the methods of NumberFormat to create an instance like this:

  • NumberFormat.getCurrencyInstance(); will return a NumberFormat object, that's why the left side is NumberFormat.

  • In the below code, we have used currency many times, but we don't exactly need that.

  • We can use method chaining, so we will directly use the method like below:

NumberFormat currency = NumberFormat.getCurrencyInstance();
String money = currency.format(9934792.342342);
System.out.println(money);

Input Scanner

  • The .next will store only the first.

  • For a whole string, use .nextLine.

  • When we get a string from a value like .next(), if we want to lowercase it, we can do that by using stringVariable = scanner.next().toLowerCase().

Operators:

  • Comparison Operator:

    • ==

    • !=

    • <

    • >

  • Logical Operators:

    • && (AND)

    • || (OR)

boolean isWarm = temperature < 20 && temperature > 30;
// We can combine the boolean expressions like below

boolean hasCriminal = false;
boolean isEligible = (goodCredit || goodIncome) && !hasCriminal; // is not true

// When both ends are true then this will be true.
int income = 120_000;
if (income > 100) {
    // Some code here
}
  • We can remove unnecessary curly braces when we have only one line command. We must use curly braces when we have a code block. Also, we can’t declare variables without them.

Simplifying If Statements:

// This looks like a mess and a professional programmer will not do this.
int income = 120_000;
boolean highIncome = false;
if (income > 100_000)
    highIncome = true;
else
    highIncome = false;

// The most simple and elegant way is this:
boolean highIncome = income > 100_000;
// We can also add brackets if you want
// Must give the initial values

Ternary Operator:

// The old way to do this
String className;
if (income > 100_000)
    className = "First";
else 
    className = "Economy;"

// But we will use Ternary Operator like in Python

String className = condition & expression ? {This will be added if the condition is true} : {This will be added if the condition is false};
String className = income > 100_000 ? "yeah baby" : "NO, yeah baby";

Switch Cases:

String role = "admin";
if (role == "admin")
    System.out.println("You're an Admin");
else if (role == "moderator")
    System.out.println("You're a Moderator");
else
    System.out.println("You're a Guest");

// Use Switch Cases in this Case

switch (theNameOfTheVariable) {
    case "theValueOfTheVariableOnWhichMakesDecision":
    case "admin":
        System.out.println("You're an Admin");
        break;
    default:
        // The default code to be executed if none of the conditions matched
}

FizzBuzz:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int numberEnteredByUser;
        String fizzBuzz;
        Scanner scanner = new Scanner(System.in);

        for (int i = 0; i < 11; i++) {
            System.out.print("FizzBuzz => ");
            numberEnteredByUser = scanner.nextInt();
            fizzBuzz = (numberEnteredByUser % 3 == 0 && numberEnteredByUser % 5 == 0) ? "FizzBuzz":
                    (numberEnteredByUser % 3 == 0) ? "Buzz" : (numberEnteredByUser % 5 == 0) ? "Fizz": Integer.toString(numberEnteredByUser);
            System.out.println(fizzBuzz);
        }
    }
}

While Loops

We cannot use comparison operators with reference types because these operators will compare the addresses of the left-hand side variables. Instead, we should use .equals("quit") or !anyStringVariable.equals("quit") for comparison.

We can use break to exit a loop and continue to skip the current iteration and move to the next one.

String check = "quit";
Scanner input = new Scanner(System.in);
String iinp = "";

while (!iinp.equals("quit")) {
    System.out.print("$: ");
    iinp = input.next();
    System.out.println(iinp);
}

Using .equals() in the condition

while (iinp.equals("quit")) {
    System.out.print("$: ");
    iinp = input.next().toLowerCase();
    if (!iinp.equals("quit"))
        System.out.println(iinp);
}

Using 'break'


while (iinp.equals("quit")) {
    System.out.print("$: ");
    iinp = input.next().toLowerCase();
    if (!iinp.equals("quit"))
        break;
    System.out.println(iinp);
}

Simplifying the loop using 'while(true)' and 'break'


Scanner input = new Scanner(System.in);
String iinp = "";

while (true) {
    System.out.print("$: ");
    iinp = input.next().toLowerCase();
    if (iinp.equals("quit"))
        break;
    System.out.println(iinp);
}

Example of 'break' and 'continue'


for (int i = 1; i < 11; i++) {
    System.out.print(i + " => ");
    digit = input.nextInt();
    if (digit == 69)
        continue;
    System.out.println(i + " => " + digit);
    // 'continue' will skip the iteration if 'digit' is 69
}

For Each Loop

One limitation of the for-each loop is that it does not support reversing the iteration.

String[] fruits = {"kosta", "gjore", "ramonu"};

for (String gajvi : fruits)
    System.out.println(gajvi);

The Main Things I've Waited For:

Use the following to verify or filter the input:

When a variable is declared in a code block, its scope is only within that block.


while (true) {
    System.out.println("Enter Your Age!");
    age = input.nextInt();
    if (age < 30)
        continue;
    System.out.println(age);
    break;
}

// Although it works, this approach is not recommended

```java

while (true) {
    System.out.println("Enter Your Age!");
    age = input.nextInt();
    if (age > 30) {
        System.out.println("Yeah baby, you are right. Your age is " + age);
        break;
    } else {
        System.out.println("You entered a number less than or equal to 30. Please enter a larger number.");
    }
}
System.out.println(age);

Unfinished Work:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        float x1 = 2;
        float y1 = 3;
        float x2 = 5;
        float y2 = 7;

        float result = (float) Math.sqrt(calculateDistance(x1, y1, x2, y2));
        System.out.println(result);
}

    public static  float calculateDistance(float x1, float y1, float x2, float y2){
        float distance;
        distance = ((x2 - x1) * (x2 - x1)) +
                ((y2 - y1) * (y2 - y1));
        return distance;

    }

    public static void getCoordinates(String prompt, float xAxis, float yAxis){
        Scanner scanner = new Scanner(System.in);
        System.out.println(prompt);
        System.out.print("X => ");
        while (true){
            xAxis = scanner.nextFloat();
            if (xAxis >= 0 && xAxis <= 100)
                break;
            System.out.println("Coordinates Needs To Be Between 0 & 100");
        }
        System.out.print("Y => ");
        while (true){
            yAxis = scanner.nextFloat();
            if (yAxis >= 0 && yAxis <= 100)
                break;
            System.out.println("Coordinates Needs To Be Between 0 & 100");
        }

    }
}

Last updated

Was this helpful?