Java is a high-level programming language known for its robustness, object-oriented nature, enhanced security, and easy-to-learn features, all of which are referred to as Java Buzzwords. Java is a platform as well as a programming language. James Gosling, the creator of Java, is known as the "Father of Java." Before Java, it was known as Oak. Because Oak was already a well-known company, James Gosling and his team renamed the programming language Java. Java makes it simple for programmers to write, compile, and debug code. It is commonly used in the creation of reusable code and modular programs.
Features of Java :
Java is an object-oriented programming language that emphasizes dependency reduction. A Java program can be created once and run anywhere (WORA). Java programs are first compiled into bytecode, which can then be run on any Java Virtual Machine. In terms of syntax, Java is similar to C/C++.
Let us quickly go through some of the most important terms used in the Java programming language.
JVM: The JVM stands for Java Virtual Machine. A program’s execution is divided into three stages. A Java program is written, compiled, and then run.
As shown in the above image, the JVM language classes are first processed by the class loader subsystem, which is in charge of loading, linking, and creating the java classes. The generated files are stored in the JVM Memory after being processed by the class loader, which consists of a method area, heap, JVM language stacks, PC registers, and native method stacks. The execution engine uses the Native Method Interface and Native Method Libraries to access files from JVM memory.
Bytecode: Bytecode is a type of intermediate code generated by the compiler after the source code has been compiled (JAVA Program). Java is a platform-independent language thanks to this intermediate code.
JRE: The Java Runtime Environment (JRE) is included with the JDK. The JRE installation on our computers allows us to run the Java program, but we cannot compile it. A browser, JVM, applet support, and plugins are all included in JRE. JRE is required for a computer to run a Java program.
In the above image, we can see that JVM together with the Java Class Libraries makes up the JRE.
Java Development Kit (JDK): When we learn about bytecode and JVM, we use the name JDK. As the name implies, it is a complete Java development kit that includes everything from the compiler to the Java Runtime Environment (JRE), debuggers, and documentation. In order to design, compile, and run the java application, we must first install JDK on our computer.
In the above image, we can clearly see that JVM and the Library classes together make up the JRE. JRE when combined with Development Tools makes up JDK.
Garbage Collection: Garbage collection is the method by which Java programmes automatically maintain their memory. Java programs are compiled into bytecode that a Java Virtual Machine, or JVM, can execute. Objects are created on the heap, which is a section of memory reserved for the Java application while it is running on the JVM. Some items will become obsolete with the passage of time. The garbage collector detects and deletes these useless objects to free up memory.
finalize method: It’s a method that the Garbage Collector calls shortly before deleting or destroying an object that’s suitable for Garbage Collection in order to do cleanup. Clean-up activity entails de-allocating or closing the resources associated with that object, such as Database Connections and Network Connections. It’s important to remember that it’s not a reserved keyword. Garbage Collector destroys the object as soon as the finalise method completes.
Let us look at some of the basic concepts frequently used in the Java programming language.
object - An object is an entity with a state and behavior, such as a chair, a bike, a marker, a pen, a table, a car, and so on. It could be either physical or logical (tangible or intangible). The financial system is an example of an intangible object.
There are three characteristics of an object:
class - A class is a collection of objects with similar attributes. It’s a blueprint or template from which objects are made. It’s a logical thing. It can’t be physical. In Java, a class definition can have the following elements:
Constructors: A constructor in Java is a block of code that is comparable to a method. When a new instance of the class is created, the constructor is invoked. It is only when the constructor is invoked that memory for the object is allocated.
There are two types of constructors in Java. They are as follows:-
Default Constructor - A default constructor is a constructor that has no parameters. If we don’t declare a constructor for a class, the compiler constructs a default constructor for the class with no arguments. The compiler does not produce a default constructor if we explicitly write a constructor.
Output :
Default Constructor called
0
In the above code, the class Test has a default constructor with no arguments. When an object of the class Test is created, the default constructor gets invoked and the statement “Default Constructor called” is printed.
Parameterised Constructor - The term parameterized constructor refers to a constructor that has parameters. If we wish to initialize our own values to the class’s fields, we should use a parameterized constructor.
Output -
10
In the above code, the class Test has a parameterized constructor with 1 argument. When an object of the class Test is created by providing 1 argument, the parameterized constructor gets invoked and the data member of the object gets initialized to 10.
In the above image, we can see that a class Person has been defined with the data members ‘unique_id’, ‘name’, ‘age’, ‘city’ and ‘gender’ and the methods ‘eat()’, ‘study()’, ‘sleep()’ and ‘play()’. Two objects of this class have been defined. The first object has ‘name’ as ‘Parsoon’, ‘age’ as ‘25’, ‘city’ as ‘Delhi’, and ‘gender’ as ‘male’. The second object of the ‘Person’ class has ‘name’ as ‘Purva’, ‘age’ as ‘28’, ‘city’ as ‘Goa’ and ‘gender’ as ‘female’.
In Java, the above example can be represented as follows:
In the above code, we have created a class ‘Person’ which has the data members ‘unique_id’, ‘name’, ‘age’, ‘city’, and ‘gender’. We have added a default constructor and a parameterized constructor in the ‘Person’ class definition as well. The default constructor initialized the data members to their default value and the parameterized constructor initializes the data members to the values provided as arguments. We create a ‘Test’ class to create 2 objects of the ‘Person’ class as demonstrated in the above example. We pass the values {1, ‘Parsoon’, 25, ‘Delhi’, ‘male’} for the first object and the values {2, ‘Purva’, 28, ‘Goa’, ‘female’} for the second object.
keyword - Reserved words are another name for Java keywords. Keywords are specific terms that have special meanings. Because these are Java’s predefined words, they can’t be used as variable, object, or class names.
3. Variables in Java
In Java, a variable is a data container that stores data values during the execution of a Java program. A data type is allocated to each variable, indicating the type and quantity of data it may store. It is a program’s fundamental storage unit. All variables in Java must be defined before they may be used.
Syntax of declaring a variable:-
datatype variable_name;
Here, datatype refers to the type of data that can be stored in the variable. variable_name refers to the name of the variable being declared.
In the above image, we can see that a variable named ‘age’ has been declared of type ‘int’ and has been initialised with the value ‘20’.
Types of variables:-
The different sizes and values that can be stored in the variable are defined by data types. In Java, there are two types of data types:
Primitive Data Types in Java:-
Primitive data types are the building blocks of data manipulation in the Java programming language. These are the most fundamental data types in the Java programming language. I.e int, float, char, boolean, etc
Non Primitive data types in Java:-
The non-primitive data types in Java include classes, interfaces, and arrays. We will discuss more on them in the upcoming topics.
5. Java Keywords
a) Understanding this keyword in Java:
This keyword in java can be used in multiple ways. The following are the use cases of this keyword:
this: to refer to the current instance variable of the class
This keyword can be used to refer to the current instance variable of a class. If there is any ambiguity between the instance variables and arguments, this keyword clears things out.
Example -
Output -
a = 10
Explanation:
In the above code, we can see that both the data member of the class Sample and the parameter of the constructor of the Sample class have the same name ‘a’. Here, we use this keyword to differentiate between the two.
this: to call the method of the current class
This keyword can be used to call a method in the current class. If you don't use this keyword, the compiler will add it for you when you call the method. Let's look at an example.
Output -
hello foo
hello there
Explanation -
In the above code, we have 2 methods defined in the Sample class fun and foo. We create an instance of the Sample class and call the method foo(). In the foo() method, we call the fun() method using this keyword.
this() is used to call the constructor of the current class
The current class constructor can be called using this() call. It allows for constructor chaining.
Example -
Explanation - In the above code, we have two constructors defined in the Sample class. We call the default constructor from the parameterized constructor using this() statement.
this: to use as a parameter in a method
The keyword this can also be used as an argument in a method. It is primarily used in event handling. Let's look at an example:
In the above code, two functions fun and foo have been defined in the Sample class. The function fun() accepts a parameter of the Sample object type. We call the function fun() from the function foo() and pass this as a reference to the current invoking object.
this keyword can be used to get the current instance of a class
This keyword can be returned as a statement from the method. In this situation, the method's return type must be the class type (non-primitive). Let's look at an example:
Output -
Inside foo function
In the above code, we have a function ‘getObject’ defined in the Sample class which returns a reference to the current invoking object. We use this reference returned to call the foo() method from the Test class.
b) final keyword in Java:
The final keyword is used in a variety of situations. To begin with, the final is a non-access modifier that only applies to variables, methods, and classes. The behavior of final in each scenario is listed below:
Final Variables:
When a variable is declared using the final keyword, the value of the variable cannot be changed, making it a constant. This also necessitates the creation of a final variable. If the final variable is a reference, it cannot be re-bound to reference another object, but the internal state of the object indicated by that reference variable can be altered, allowing you to add or delete elements from the final array or collection.
Example -
finalint temp = 10;
Final Classes:
A final class is one that has been declared with the final keyword. It is not possible to extend a final class. A final class can be used in two ways:
Example -
The above code gives a compile-time error. The reason is that the class Sample is declared as final and since the class Test is trying to extend the Sample class, it gives a compile-time error.
Final Methods:
A method is called a final method when it is declared with the final keyword. It is not possible to override a final method. In the Object class, many methods defined are declared final. This is done so that a user cannot modify the definition of those functions in their java classes. We must use the final keyword to declare methods for which we must use the same implementation throughout all derived classes.
Example -
The above code on execution gives a compile-time error. The reason is that the fun() function declared in the Sample class is a final method so we cannot override it in the inherited class. In the above code, the Test class tries to override the fun() function defined in the Sample class and this leads to a compilation error.
c) static keyword in Java:
In Java, the static keyword is mostly used to control memory. In Java, the static keyword is used to share a class's variable or method. Static keywords can be used with variables, methods, blocks, and nested classes. The static keyword refers to a class rather than a specific instance of that class.
The static keyword is used in the following ways:
Static Blocks:
You can declare a static block that gets executed exactly once when the class is first loaded if you need to do the computation to initialize your static variables.
Consider the Java program below, which demonstrates the use of static blocks.
Output -
Inside Static block.
Value of x: 25
Value of y: 100
Explanation - In the above code, there are 2 static variables x and y. X is initialized with 25. We can see that first of all, the static block is executed which prints the statement “Inside Static block.” and initializes y to x * 4 (i.e., 100).
Static Variables:
When a variable is marked as static, a single copy of the variable is made at the class level and shared among all objects. Static variables are effectively global variables. The static variable is shared by all instances of the class. In a program, static blocks and static variables are executed in the order in which they appear.
Example -
Output -
Inside fun function
Inside static block
Value of x: 10
Inside the main method
Explanation - In the above code, first of all, x gets initialized by calling the fun() function. Hence, the statement “Inside fun function” gets printed. Then, the static block gets executed since it is after the initialization of the x statement. At last, the statements inside the main method get printed.
Static Methods:
The static method is defined as a method that is declared using the static keyword. The main() method is the most common example of a static method. Any static member of a class can be accessed before any objects of that class are generated, and without requiring a reference to any object. Static methods are subject to the following constraints:
Example -
The above code results in a compilation error. There are 3 reasons for it.
Static Classes:
When a class is declared with the static keyword, it is said to be a static class. A class can be made static in Java if and only if it is nested inside another class. We can't use the static modifier on top-level classes, but we can use it on nested classes.
Example -
Output -
PepHub
Explanation - In the above code, we have a static nested class named ‘Sample’ inside the ‘Test’ class. We create an object of the Sample class and call the display function.
d) super keyword in Java:
In Java, the super keyword is a reference variable that refers to parent class instances. With the concept of Inheritance, the term "super" entered the picture. It's most commonly used in the following situations:
Using super with variables:
When a derived class and a base class have identical data members, there is uncertainty for the JVM as to which class’s data member is being referred to. In order to resolve this ambiguity, we use the super keyword with the data member’s name. This code snippet will help us comprehend it better:
Output -
The value of x is: 1
Explanation - In the above code both the classes, Sample1 and Sample2 have a data member named ‘x’. We use the super keyword inside the display function of the Sample2 class to access the data member x of the parent class Sample1.
Using super with methods:
To resolve ambiguity when a parent and child class have the same-named methods, we employ the super keyword. This code snippet demonstrates how to use the super keyword.
Output -
Inside Sample1's fun method
Explanation - In the above code, both the classes Sample1 and Sample2 have a method named fun. However, in the display method of the Sample2 class, the statement “Inside Sample1’s fun method” gets printed because of the super keyword.
Use of the super keyword with constructors:
The super keyword can also be used to access the constructor of the parent class. Another key point to note is that, depending on the situation, 'super' can refer to both parametric and non-parametric constructors. The following is a code snippet to demonstrate the concept:
Output -
Inside Sample1's default constructor.
Inside Sample2's default constructor.
Explanation - In the above code, the class Sample2 extends the class Sample1. We invoke the constructor of the Sample1 class in the constructor of the Sample2 class by using the super keyword. Hence, when we create an instance of the Sample2 class, both the statements get printed.
The statements in a program that are not executed by the compiler and interpreter are referred to as Java comments. Comments can be used to explain and improve the readability of Java code. Comments in a program help to make it more human-readable by putting the details of the code involved, and effective use of comments makes maintenance and bug discovery easier. The following are the different types of comments in Java:
Only one line of code is commented with a single-line comment. It is the most common and straightforward method of commenting on statements.
Syntax -
// This is a sample comment
Multiple lines of code can be commented with the multi-line comment. Because we must offer '//' at every line to describe a full method in a code or a complex snippet, single-line comments might be tedious to write. To get around this, you can utilize multi-line comments. Between /* and */ are multi-line comments. Java does not execute any text between /* and */.
/*
This is an
Example of multi-line comment
*/
This type of comment is commonly used while writing code for a project/software package because it aids in the generation of a documentation page for reference, which can be used to learn about the methods available, their parameters, and so on.
Syntax -
/** Comment starts
* This is a
* Sample comment
* comment ends*/
The accessibility or scope of a field, function, constructor, or class is defined by the access modifiers in Java. The access modifier can be used to adjust the access level of fields, constructors, methods, and classes.
Java access modifiers are divided into four categories as shown in the image below:
The following table depicts the level of accessibility that each access modifier allows in Java.
8. Operators in Java
The below image shows the different types of operators available in Java.
The following table describes each category of operators along with examples of each type.
Precedence and Associativity of operators in Java:- When dealing with hybrid equations involving more than one type of operator, precedence and associative principles are applied. Because there might be multiple valuations for the same equation, these criteria determine which component of the equation to analyse first. The precedence of operators is shown in the table below in decreasing order of magnitude, with the highest precedence at the top and the lowest precedence at the bottom.
9. Identifiers in Java
Identifiers are used to identify items in the Java programming language. A class name, method name, variable name, or label can all be used as identifiers in Java.
Rules for defining Java identifiers:-
Reserved words:- Some words are reserved in the Java programming language to indicate the language’s established features. These are known as reserved words. They can be divided into two categories: keywords(50) and literals (3). Functionalities are defined by keywords, and literals are defined by values. Symbol tables use identifiers in the various analyzing phases of a compiler architecture (such as lexical, syntactic, and semantic).
The Java compiler runs the code from beginning to end. The statements in the code are executed in the order that they occur in the code. Java, on the other hand, includes statements for controlling the flow of Java code. It is one of Java’s most important aspects, as it ensures a smooth program flow.
There are three different types of control flow statements in Java. They are as follows:
Decision-Making Statements:
As the name implies, decision-making assertions determine which and when to execute statements. Decision-making statements analyze the Boolean expression and control the program flow based on the condition’s result. In Java, there are two sorts of decision-making statements: If and switch statements.
If Statement: The “if” statement in Java is used to test a condition. Depending on the circumstances, the program’s control is diverted. The If statement’s condition returns a Boolean value, either true or false. There are four forms of if-statements in Java, as mentioned below.
Simple if: The most basic of all control flow statements in Java is simple if statements. It evaluates a Boolean statement and, if the expression is true, allows the program to begin a block of code.
Syntax -
if-else: The if-else statement is an expansion of the if-statement that employs the else block of code. If the if-condition block is evaluated as false, the else block is executed. Syntax -
if-else-if ladder: The if-else-if statement is made up of an if statement and several else-if statements. In other words, a decision tree is created by a sequence of if-else statements in which the computer can enter the block of code where the condition is true. At the end of the chain, we may also define an else statement.
Syntax -
Nested if-statement: The if statement can contain an if or if-else statement inside another if or else-if statement in nested if-statements.
Syntax -
Switch Statement: Switch statements in Java are similar to if-else statements. A single case is run based on the variable that is being switched in the switch statement, which comprises various blocks of code called cases. Instead of using if-else-if statements, you can use the switch statement. It also improves the program’s readability.
We must remember that the case expression will be of the same type as the variable when employing switch statements. It will, however, be a constant value. Syntax -
Loop Statements:
In programming, we may need to run a piece of code multiple times while a condition evaluates to true. Loop statements are used to repeat the set of instructions. The execution of the set of instructions is contingent on a certain circumstance.
In Java, there are three different forms of loops that all work in the same way. However, there are differences in their syntax and the time it takes to check for conditions.
For Loop: The for loop in Java is comparable to the for loop in C and C++. In a single line of code, we may initialise the loop variable, check the condition, and increment/decrement. We only use the for loop when we know exactly how many times we want to run a block of code.
Syntax -
While Loop: The while loop can also be used to repeatedly iterate over a set of statements. If we don’t know the number of iterations ahead of time, though, we should use a while loop. In contrast to the for loop, the initialization and increment/decrement do not happen inside the while loop statement.
Because the condition is tested at the start of the loop, it’s also known as the entry-controlled loop. The loop body will be executed if the condition is true; else, the statements after the loop will be executed.
The while loop’s syntax is seen below.
Do While Loop: After running the loop statements, the do-while loop verifies the condition at the end of the loop. We can use a do-while loop when the number of iterations is unknown and we need to run the loop at least once.
Because the condition is not tested in advance, it is also known as the exit-controlled loop.
The do-while loop’s syntax is seen below.
Jump Statements:
Jump statements are used to move the program’s control to certain statements. Jump statements, in other words, move the execution control to another area of the program. In Java, there are two types of jump statements: break and continue.
A method is a collection of statements or a series of statements organised together to conduct a specific task or action. It’s a technique for making code more reusable. We create a method once and then use it repeatedly. We don’t have to write code over and over again. It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.
Method Declaration:- Method properties such as visibility, return type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.
Method signature - A method signature is a statement that identifies a method. It’s included in the method declaration. It contains the method name as well as a list of parameters.
Access Specifier - The method’s access specifier, also known as a modifier, determines the method’s access type. It specifies the method’s visibility. There are four different types of access specifiers in Java:
Return Type - The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or a void, for example. The void keyword is used when a method does not return anything.
Method name - The name of a method is defined by its method name, which is a unique name. It must be appropriate for the method’s functionality. If we’re making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.
Parameter List - The parameter list is a collection of parameters separated by a comma and wrapped in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.
Method body - The method declaration includes a section called the method body. It contains all of the actions that must be completed. It is protected by a pair of curly braces.
WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......
Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......
Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...
SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...
A quick summary upto what we did this far from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...
Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...
Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...
Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...
Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...
Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...
Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...
ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...
What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...
C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...
C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...
C++ programming language has templates which basically allows functions and classes to work with gen...
C++ was conceived in the late 1970s to overcome the limitations of C. It is an extension of th...
Interview Questions are a great source to test your knowledge about any specific field. But remember...
The most popular high-level, multipurpose programming language right now is Python.Python supports p...
IntroductionPython is a high-level programming language with dynamic binding and high-level inherent...
Interview Questions are a great source to test your knowledge about any specific field. But remember...
Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has lev...