Day 2 Programming (Architecture) (Basic-Syntax) (Arrays) (JAVA)
Before we begin with basic syntax here a few prerequisites that has helped me to wrap my head around java.
Java Architecture.
Computers understand only binary (0s and 1s). Java, being a high-level language, allows users to write human-readable applications and programs. However, this code must still be converted into machine-readable binary (0s and 1s) for the computer to execute. Here`s how it happens.
JDK (Java Development Kit): A software development kit used to write, compile, and run Java programs. It includes tools like the compiler (javac), debugger, and JRE. Developers need the JDK to create Java applications.
JRE (Java Runtime Environment): Provides the libraries, Java Virtual Machine (JVM), and other components required to run Java applications. It’s for users who only want to execute Java programs, not develop them.
JVM (Java Virtual Machine): A virtual machine that executes Java bytecode, making Java platform-independent. It interprets or compiles bytecode into machine code and ensures runtime environment consistency.
So in short. Once Java source code is compiled into bytecode, it is stored in
.class
files, which are platform-independent. These.class
files can run on any system (Linux, Mac, Windows) that has a Java Runtime Environment (JRE).The JRE includes the Java Virtual Machine (JVM), which interprets the bytecode and converts it into machine code specific to the system, allowing it to be executed.
write once, run anywhere (Java`s tag line )
Once we have JDK installed let`s understand two mandatory topics.
Java Packages.
Classes.
Java Class.
In Java, everything must be declared inside a class, including variables, methods, and logic like printing strings or performing calculations, as it is a class-based, object-oriented language.
A Java class is like a blueprint for making things. For example, think of a Car class as a recipe for creating cars. The class says what a car has (like color and speed) and what it can do (like drive or stop). You can use the blueprint to make as many cars (objects) as you want, each with its own color or speed.
Java Packages.
Packages in Java are essentially a combination of related classes (and sometimes interfaces) grouped together to:
Organizes Code:
Like folders in a file system, packages help in structuring large programs by grouping similar classes.
For example:com.project.users for user-related classes (e.g., User, UserService).
com.project.orders for order-related classes (e.g., Order, OrderService).
Defines a Hierarchy:
- Packages create a clear hierarchy, showing how different components relate to each other. This is especially useful in larger projects or libraries.
Avoids Class Name Conflicts:
Two classes with the same name can coexist in different packages.
For example:com.companyA.Employee
com.companyB.Employee
Improve Maintainability and Reusability:
- Grouping related classes makes it easier to find, modify, or reuse code.
In Short:
Packages = Related Classes + Hierarchy = Better Organization
Basic Syntax.
Now Remember the golden rule anything and everything in Java must be declared inside a class let`s take a look at how we declare certain types of variables and how we print them.
class Main {
public static void main(String[] args) {
// This where we define/write our code
System.out.println("I love being Stupid ");
}
}
In the above code, we have a main class that contains the public static void main(String[] args)
method. The class itself doesn't need to be named "main" — it can have any valid class name.
So, what is a method, you may ask? Drawing from my experience in Python, I like to compare methods in Java to functions in Python. A function is a block of reusable, predefined code that performs a specific action or set of actions.
However, in Java, when you define a function inside a class, it is called a method. Unlike Python, where functions can exist outside of classes, Java requires all functions to be part of a class — this is why they're referred to as methods.
This method acts as the starting point of the program and is essential for running stand-alone Java applications. You can think of public static void main(String[] args)
as the main door of a Java program, through which the program begins its execution.
Now let`s break it down further What does public mean ?
public
These are access modifiers These modifiers control the scope of class and methods.
Common modifiers:
public
: Accessible from anywhere.private
: Accessible only within the class.protected
: Accessible within the class, package, and subclasses.(Default/no modifier): Accessible within the same package.
Static
The static keyword means something belongs to the class, not an object. In public static void main(String[] args), it allows the main method to run without creating an object, making it accessible when the program starts.
void
Return Type:
Specifies the type of value the method will return (e.g.,
int
,void
,String
).Use
void
if the method doesn't return anything.
Next,
Method Name:
The name of the method. It should follow Java's naming conventions (camelCase).
Parameter List:
Specifies input parameters (if any) the method requires.
Enclosed in parentheses
()
and separated by commas if there are multiple parameters.Specify the type and name for each parameter.In this case
What is happening in the parameter?
Inside the parentheses of
main
, you are passing:String[]
: This represents an array of strings.
args
: This is the name of the array. It’s just a variable name, and you can call it anything (e.g., arguments
or input
)
The line System.out.println("I love being Stupid ");
in Java does the following:
System
: A built-in Java class for system-level functionality.out
: Refers to the standard output stream (usually the console).
println()
: A method that prints the text provided and moves to the next line.
When executed, it prints: I love being Stupid
Phew that was a lengthy explanation but it was all worth it.
In Java, it's mandatory to define the type of a variable when declaring it. Let's look at a few examples.
Integer declaration
class Main {
public static void main(String[] args) {
// This where we define/write our code
int number = 5;
System.out.println(number);
}
}
In the above example we declared a variable named number with a value of 5.
we can also change the value of the variable to a different if required.
class Main {
public static void main(String[] args) {
// This where we define/write our code
int number = 5;
number = 10;
System.out.println(number);
}
}
Decimal Declaration
class Main {
public static void main(String[] args) {
// This where we define/write our code
double number = 5.5;
number = 10.9;
System.out.println(number);
}
}
Character Declaration
class Main {
public static void main(String[] args) {
// This where we define/write our code
char singlecharacter = 'I';
System.out.println(singlecharacter);
}
}
Boolean Declaration
class Main {
public static void main(String[] args) {
// This where we define/write our code
boolean isjavafun = true;
System.out.println(isjavafun);
}
}
What is an Array ?
An array in Java is a container that stores multiple values of the same type in a single variable. It allows you to store more than one value, like a list, and access each value using an index (position number).
Key Points:
Fixed Size: Once an array is created, its size cannot be changed. You define the size when creating the array.
Same Data Type: All elements in an array must be of the same type (e.g., all integers, all strings, etc.).
Indexed: You access each element by its index, starting from 0 (the first element is at index 0, the second is at index 1, etc.).
Declaring: means you're telling Java that you're going to use an array and what kind of values it will store, but you haven’t created the actual array yet e.g int , float , char , string , object.
Initializing: means you're actually creating the array and specifying how many elements it should hold. This is where you actually allocate space in memory for the array and define its size.
Let’s take a look at an example
class Main {
public static void main(String[] args) {
// Declaring the array // Intializing the array
int [] numbers = new int [5];
numbers [0] = 5;
numbers [1] = 10;
numbers [2] = 15;
numbers [3] = 20;
numbers [4] = 25;
int value = numbers [0];
System.out.println(value);
}
}
In the above code we have declared the type of array we are going to have in this case it`s an integer array int [] numbers.
Then we have initialized the array and mentioned we will store 5 elements into it new int [5];
Next, we assign specific values to each of the 5 elements in the array, starting with numbers[0] = 5;
, and so on for the remaining indices.
Next, we declare a new variable and assign it the value from the first element of the array, then print the value of the variable
We can shorten the code by declaring and initializing the array in the same line.
class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // An array of number intialized and
System.out.println(numbers[0]); // Prints 10 (first element)
}
}
In this case, the initialization happens right where the array is declared, using the array initializer ({10, 20, 30, 40, 50}
). This means you don’t have to use new int[5]
to create the array manually.
Next we take a look at array type of string.
class Main {
public static void main(String[] args) {
String [] Fruits = {"Apple", "Banana", "Mango", "Kiwi" };
System.out.println(Fruits[3]);
}
}
In the above code we have named our array Fruits and assigned it various fruits name.
Mixed Arrays (of Different Types):
While you can store mixed types of objects in an array of Object
(since everything inherits from Object
), all elements within a single array must be of the same type when dealing with arrays of primitives or objects.
Here’s an example of how to store mixed types in an Object
array:
class Main {
public static void main(String[] args) {
// An array of mixed types (since they are all derived from Object)
Object[] mixedArray = {10, "Hello", 3.14, true};
// print thied element in the array
System.out.println(mixedArray[3]);
}
}
Important Note: While the Object[]
array can hold any type of object, you would need to cast the values back to their original types when you retrieve them (e.g., String
, Integer
), which is generally not recommended because it can lead to errors and confusion.
User Defined Class example
class Main {
public static void main(String[] args) {
System.out.println("My personal car stock");
Car.Cartype();
}
}
class Car {
public static void Cartype () {
String car_brand = "VW POLO";
int Car_speed = 250;
String Car_color = "Cherryred";
String Car_model = "GT SPORTS 2022";
System.out.println("My car brand is " + car_brand + " " +"It has a top speed of" + " " + Car_speed + "KM" + " " +"It has a nice " + Car_color + " "+ "color" + " " +"and comes in "+ " " + Car_model );
}
}
The Main class contains the main() method, which is the starting point of the program. It prints a message "My personal car stock" and calls the Cartype() method from the Car class.
The Car class contains a static method, Cartype(). This method has several local variables (car_brand, Car_speed, Car_color, Car_model) that describe a car's attributes, such as its brand, speed, color, and model. These attributes are not shared with the Main class but are used inside the Cartype() method to print a descriptive message about the car.
Before we proceed, it's essential to understand the concept of data types in Java. I intentionally included "type" at the end of certain terms because, without it, the meaning might not be immediately clear. It was only through my own trial and error that everything started to make sense. Below is a description that ties it all together.
Difference Between Primitive and Non-Primitive (Reference) Data Types in Java
In Java, primitive data types (like int, double, char, etc.) represent simple values and do not have methods directly associated with them. For example, you can't call a method on a primitive type like int using the . operator. Primitive types are the building blocks of data and are stored directly in memory.
On the other hand, non-primitive data types (like String, Array, or custom objects) are reference types that allow us to perform operations on the data using methods. For instance, you can use methods like .toUpperCase() or .substring() on a String object.
class Main {
public static void main(String[] args) {
int number = 10;
// You cannot do number.toString() directly because 'int' is a primitive type.
}
}
class Main {
public static void main(String[] args) {
String text = "hello";
// You can call methods on 'text' because String is a non-primitive type.
System.out.println(text.toUpperCase()); // Outputs: HELLO
}
}
Prints the output to uppercase.
class Main {
public static void main(String[] args) {
// An array of mixed types (since they are all derived from Object)
Object[] mixedArray = {10, "Hello", 3.14, true};
System.out.println(mixedArray.length);
}
}
Display the length of the array.
In short, primitive types are basic, simple data holders, whereas non-primitive types are more flexible and allow you to perform operations using methods.
Keep in mind that certain words in Java are reserved as keywords, so they cannot be used for naming variables, methods, or classes. You can refer to the following URL to get started with the complete list of Java keywords .
https://www.geeksforgeeks.org/java-keywords/?ref=lbp
stay tuned for more
Thank YOU :)