
History of Java
In 1990, Sun Microsystems launched a project called Green to develop software for consumer electronic products. Gosling began to write software in C ++ to embed elements such as toast, VCR, and personal digital assistants (PDA). The history of java started with Green Team. In this team, there were three members James Gosling, Mike Sheridan, and Patrick Naughton protecting the language started in June of 1991.
It was named “Greentalk” by James Gosling. The file extension was ".gt". Later it was called Oak. Oak is a national tree of many countries like the U.S.A, France, Germany, Romania, etc. In May 1995, Oak was renamed as “Java” given by James Gosling, by then it was already a trademark of the organization.
There were more choices of names before finalizing, but Java was so unique, so James and most of his team members preferred Java.
A more interesting fact is related to Java, Java is an island in Indonesia where the first coffee was produced and the name of the coffee was Java. Java is a name, not an acronym.Java coffee consumed in large quantities by the creator of the language. This indicates the story behind the logo of Java.
#History #Java #Programming #Language #JamesGosling #Inventor
Java Versions and How to Set Up Your Computer: A Simple Guide
Java is a flexible programming language with many versions designed for different uses. With so many options, it's important to pick the right version for your needs. We'll take a look at Java versions, especially the important Long-Term Support (LTS) ones.
Java 8 was the first LTS version. It's a bit old now, but still widely used, even though it's a little different from newer versions. If you write code in Java 8, you might find it doesn't work the same in later versions. So, the version you choose is very important for making sure your code will work and for making coding easier.
Fast forward to the present, Java 17 is the latest LTS version, known for its better features and reliability. Java 21 is coming soon, but Java 17 is currently the best choice for reliable and supported Java use. Now, let's talk about what you need to actually use Java. You'll want a good Integrated Development Environment (IDE), and IntelliJ IDEA is a great one that's easy to use for Java coding. It comes in both paid and free versions, and the free one is good enough for most people.
Downloading and installing IntelliJ IDEA is simple. Just click to download IntelliJ IDE, and you'll be set up in no time. It has a clear interface that makes starting a new project easy. For Java coding, you need the Java Development Kit (JDK), and IntelliJ IDEA makes it easy to manage this with a built-in feature. Just a few clicks and you'll have the newest JDK ready to go in your IDE, which means less trouble as you develop your programs.
With IntelliJ IDEA and the latest JDK, you're all set to start using Java.
#Java #Programming #IntelliJIDEA #JavaCoding #CodingGuide #LTSVersions #SetUpGuide
Guide to Importing Projects into IntelliJ IDEA
The ability to import projects quickly and accurately into their preferred Integrated Development Environment (IDE) is not just a convenience; it's a necessity that saves time and streamlines workflow. IntelliJ IDEA, a leading IDE for Java development, offers robust features for project import that cater to both novices and seasoned professionals. This guide will walk you through the essential steps and tips to ensure your project import into IntelliJ IDEA is as smooth as silk.
Core Steps for Importing Projects
Start IntelliJ IDEA
Launch IntelliJ IDEA. If you have a project open, close it by going to File > Close Project.
Import Project:
On the Welcome screen, click Import Project.
Navigate to your project directory and select the project you wish to import.
Select Import Project Type:
Choose the appropriate type of project to import based on your project's existing structure, such as Maven, Gradle, or a simple directory structure.
Configure Project Settings:
Follow these steps to configure the project settings. Set the JDK for the project and resolve any dependency issues.
Finish Import:
Review your settings and click Finish to complete the import process. The IDE will now open your project.
Alternative Method: Importing from Within the IDE
If you're already working within IntelliJ IDEA and need to import another project:
Access the Project Structure:
Go to File > Project Structure.
Add Module:
Click on the Modules section, then click the + button and select Import Module.
Select and Configure:
Choose the project you wish to import and configure it just like in the core steps outlined above.
Troubleshooting Common Issues
Missing JDK or OpenJDK Error:
Go to File > Project Structure > SDKs and add a JDK by providing the path to the JDK installation directory.
Ensure that the JDK version matches the one required for your project.
Dependency Resolution:
If the IDE cannot resolve dependencies, check your build configuration files (like pom.xml for Maven) for errors.
Use the Refresh option in the IDE's build tool window to synchronize the project.
By following the steps provided, you can seamlessly import your projects into IntelliJ IDEA.
#IntelliJIDEA #ProjectImport #CodingMadeEasy #TechTips #JavaDevelopment
Starting Your First Java Project with IntelliJ IDEA: A Beginner's Guide
If you're new to programming or looking to refresh your skills, starting with a simple project in IntelliJ IDEA is an excellent choice. Here we will guide you through setting up a basic "Hello World" application using IntelliJ IDEA, a popular integrated development environment (IDE) for Java developers.
Setting Up Your Environment
First things first, you'll need to set up your Java development environment. IntelliJ IDEA is a powerful Integrated Development Environment (IDE) that makes Java programming simpler and more efficient. Once you've launched IntelliJ IDEA, start by creating a new project.
For beginners, it's best to begin with an empty project to keep things uncomplicated.
Simply name your project "Hello World" to keep with tradition.
Choosing the Right Java Development Kit (JDK)
For your project, you will need a Java Development Kit. We'll use Microsoft Open JDK 17, just select the appropriate JDK from the list in IntelliJ IDEA. Don’t worry about using Maven for this project; we'll keep it straightforward by not using it.
Writing Your First Java Program
Once your project setup is complete, it's time to dive into coding. Add a simple "Hello World" program to your project. This classic first program is perfect as it's simple yet teaches the basic structure of Java code. If you’re using a sample code provided or writing your own, IntelliJ IDEA makes this process smooth with helpful tools and suggestions.
Building and Running Your Application
After writing your code, the next step is to see it in action! Run your application directly within IntelliJ IDEA to see the output. If everything is set up correctly, you’ll see "Hello World" or whatever output your code is designed to produce.
Handling Output and Artifacts
In development, outputs and artifacts are essential for understanding how your application is built and executed. Explore how IntelliJ IDEA handles these, and learn how to manage and utilize the .class files and the src folder where your Java files reside. These elements are crucial as they contain the bytecode and source code respectively.
Creating a JAR File
A crucial skill in Java development is learning how to package your application. In IntelliJ IDEA, navigate through the project structure to create a JAR file — a portable format for distributing your Java applications. Use the modules with dependencies to ensure your application runs smoothly on other systems.
Troubleshooting Common Issues
You might encounter issues like the "class not found" error when running your JAR file. This is often due to configuration problems which can be easily fixed by adjusting the settings in IntelliJ IDEA.
Make sure your project is correctly configured before exporting it to ensure smooth operation.
Keeping Your JDK Updated
Java is continuously evolving, and so are its development tools. The video tutorial was updated to reflect changes in OpenJDK and other versions, demonstrating the importance of keeping your development environment up to date. This ensures compatibility and enhances security.
Starting with a simple Java project in IntelliJ IDEA introduces you to the world of software development in an accessible and manageable way. Whether you're a student just beginning your coding journey or an IT professional polishing your skills, mastering these fundamentals is your first step towards more complex programming challenges.
Happy coding, and remember — the best way to learn is by doing!
Don't hesitate to experiment with your code and explore the extensive features available in IntelliJ IDEA.
#JavaBasics #Java #IntelliJIDEA #Programming #HelloWorld #EasyDeployment #CodingForBeginners
Creating a Simple Java Project in IntelliJ IDEA: A Step-by-Step Guide
In this tutorial, we'll walk through the steps to create your first project and even generate a JAR file, perfect for beginners, all with simplicity in mind.
Creating Your First Project
Getting Started: Launch IntelliJ IDEA and select "New Project" from the welcome screen.
Project Setup: Choose a new empty project, name it "Hello World," and select Java as the language.
Choosing JDK: If you have Java installed, pick the appropriate JDK.
Adding Sample Code: IntelliJ IDEA provides a basic structure for your project, including sample code to get you started.
Generating a JAR File
Want to take it a step further and create a JAR file? Fear not, it's simpler than you think!
Project Structure: Navigate to "File" > "Project Structure" to configure your project.
Creating JAR: Under "Artifacts," add a new JAR file and select "Build JAR from modules with dependencies."
Setting Main Class: Choose the class with the main method.
Build and Run: Apply the changes and click "OK" to generate the JAR file.
Running Your Application: Right-click on the generated JAR file and select "Run" to execute your program.
Tips and Tricks
Refreshing Project: If the output folder doesn't appear immediately, try refreshing or reloading the project.
Handling Configuration Issues: If you encounter a "class not found" exception, edit the configuration to ensure proper setup.
Staying Updated: Keep up with changes in JDK versions and IntelliJ IDEA UI to adapt to industry standards.
And there you have it! A basic Java project is up and running in no time. But remember, the tech world is ever-evolving. Stay curious, embrace change, and keep exploring. Until next time, happy coding!
#JavaProgramming #IntelliJIDEA #BeginnerFriendly #JDK17 #Maven
Keyword
This tutorial deals with the concept of keywords in Java. Keywords are special entities that are predefined in Java. These words cannot be used as identifiers. Out of the 50 keywords, 48 are currently in use (const and goto not in use).
A Java keyword is one of the 50 reserved keywords for a programming language. Each keyword has a specific meaning in the language. These keywords are already known by Java.
Rules to follow for keywords:
Keywords cannot be used as identifiers for class, subclass, variable, and methods.
Keywords are case-sensitive.
Here is a list of keywords in the Java programming language:
abstract
assert
boolean
break
byte
case
catch
char
class
const*
continue
default
do
double
else
enum
extends
final
finally
float
for
goto*
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
*****************************************************************
Some significant points about Java keywords:
true, false, and null might seem like keywords but aren't
All keywords are in lowercase.
More on this topic ahead of the tutorial.
#keywords #reserved words #case-sensitive #java #rules
Understanding Variables
The manipulation of two variables having the same datatype is shown. The variables can be modified with help of any constant or otherwise with the help of the same datatype. Issues such as case sensitivity and order of execution of statements are shown here.
The variable can be declared to store data in the program. There are few variations in how we can declare a variable in a programming language. The following program will demonstrate how we can declare and then initialize an int variable.
Multiple variable initializations within a statement
When it comes to multiple variable initializations, Java also supports multiple initializations within a single statement within the statement. We can also merge the declaration and initialization of multiple variables within a single. To initialize multiple variables, we need to use a comma-separated list.
Initialization of variable through arithmetic operation
After the arithmetic operation, the final result would be assigned to the variable. Assignment of the result is done using the assignment operator (=) and the assignment sequence is from right to left. If you make use of the bracket within the operation, operation inside the bracket would be performed first.
Assigning one primitive variable to another
We can also assign a value to a variable by using another variable. This is also called copying the value of one variable into another.
Demonstration
Assign any integer value to an int variable.
Assign the variable value to a variable.
Naming Convention
The names of variables are case sensitive “value” and “Value” both are different.
Space is not permitted in variable names
Primitive Data Types
This tutorial describes the integer datatype and the similar types of the datatype with a couple of differences. Various operations like the maximum and minimum are shown. The following primitive datatypes are discussed are as follows.
1.byte(memory->(1 byte,8 bit),range->(-128,127))
2.int (memory->(4 bytes,32 bits),range->(-2^31,2^31))
3.short(memory->(2 bytes,16 bits),range->(-2^15,2^15))
4.long(memory->(8 bytes,64 bits),range->(-2^63,2^63))
Java supports eight primitive data types. These are the basic and predefined datatype of programming language. The size of the primitive data type is fixed. Primitive data types are represented by reserved keywords.
The primitive data type is divided into following categorize
Integer data type.
Floating Point data type.
Boolean data type.
Char data type.
Integer data type
An integer data type is used to store integer numbers (numbers without a decimal point). The minimum and maximum value that a variable can store also depends on the data type.
The range of Integer data types
We have a list of integer datatype, As the memory allocation of these different flavors of integer datatype is different, the range of these data type also differs. Based on our requirement, we can choose any flavor of integer datatype, int datatype being the most popular and recommended, as int performs fastest among all the flavors.
byte
The size of the byte type is 8bit/1byte. The minimum value of the byte variable is -128 and the maximum being 127.
short
The short data type is an integer-compatible data type and used to contain an integer value. The size of the short type is 16bit/2byte.
int
The size of the int value is 32bit/4byte. The minimum value of int is -2,147,483,648 and the maximum range is 2,147,483,647.
long
The size of the long data type is 64bit/8byte. While declaring long data type we have to use the suffix “L” by default java considered it as an int. It is recommended that you use the uppercase letter “L” because these are case-sensitive.
Initialization of long variable:
long longMax = 9,223,372,036,854,775,807L;
long longMin = -9,223,372,036,854,775,808L;
[ L specifies that value is a long. ]
Floating Point data type
The tutorial describes the float and the double primitive datatypes. Mostly used while dealing with decimals. The float datatype occupies 4 bytes hence will have a range from -2^31 to 2^31. It has single-precision(7 decimals)hence it is not used for complex calculation. For that purpose, double is used. The double occupies 8 bytes and hence double precision(15 decimals). This also outlines the various techniques of implementing the above datatypes.
Floating-point variables are used to deal with the decimal value. There are two types of floating-point data types. float-point types with storage sizes and range with their precision.
In the program, whenever we want to store a floating-point value in a variable, we can use one of these data types accordingly.
Initialization of float variable:
float var = 9f;
[ f specifies that value is a float. ]
Precision in float (7 spaces)
*********************************
double: double is used to store value with precision up to 16 spaces, it occupies 64-bit memory
Initialization of double variable:
double var = 9d;
[ d specifies that value is double. ]
Precision in double data type is more than a float data type.
This deals with the boolean datatype. The boolean data type has only two possible values: true and false. This data type is used for simple flags that track true/false conditions. This data type represents one bit of information, but its memory constant isn't precisely defined. Char datatype is a 16-bit Unicode character. It has a lower limit of '\u0000' (0) and a highest value of '\uffff' (or 65,535) both inclusive.
Boolean
Boolean is a data type that represents one bit of information either true or false.
Char
A char data type is a single-length entity. This could be an alphabet, a digit, or a symbol. It is also used to hold the Unicode for symbols. Value for char should be with single quotes.
Note: We must only use the single quotes pointing to left
The length should be one.
Single quote point to the left should be used
Any character on the keyboard is allowed
Example: ‘A’,’*’,’1’
More details about these concepts can be understood in this lecture.
This session deals with the Strings. Strings represent character strings. The various rules associated with string are stated in addition to some operations. Also, an introduction to typecasting is given (which is a conversion between the datatypes).
String
A Sequence of characters inside double quotes is called String, for e.g., “Java” String is the sequence of 4 characters.
Initialization of String variable
In the below example, we will create a String. Here var is the reference of data “Hello World” of type String.
String var = "Hello World";
Unicode symbols can also be stored as String. Unicode is a universal international standard character encoding that represents most of the languages in the world.
String var1 = "\u00BB";
Discussions on the same are continued in upcoming lectures.
This lecture deals with typecasting from basics to advanced. The conversion from one datatype to another is described here. This tutorial covers both types of typecasting namely explicit and implicit typecasting. Implicit typecasting is automatically done by the compiler to convert datatypes with large memory space to short memory space. The other (Explicit typecasting)has to be manually declared. It covers all the rules for conversion for typecasting.
In Java, Type Casting is a process of converting a variable of one data type into another.
Typecasting is of two types:
Implicit typecasting.
Explicit typecasting.
Implicit typecasting
Implicit type casting is also known as Widening or Automatic typecasting. When a small range data type variable is converted into a large range data type, The process is called implicit typecasting.
Explicit typecasting
Explicit typecasting is also known as narrowing typecasting. When a large range data type is converted into small range data.
Do you know?
Data type should be compatible for conversion. A non-primitive data type cannot be converted into a primitive type.
The precision loss may happen in Explicit typecasting.
In this program, we will be performing a simple equation in which we will calculate the result.
So which datatype would be best suitable for an algebraic expression?
Let us see, in our program, we are making use of two different datatypes: int a and float b.
As per Java convention, it is said higher the order of a datatype, the highest preference is given to that datatype.
The value of the result is stored using double datatype. So by default, Java will assume the result to be calculated in double type.
But there is a twist in our program, as we have provided the value of b which is a float type, ending with literal 'f', now our program output will provide a precision equivalent to 7-decimal.
Another scenario where we want our result must be calculated in int type, so how we will do that?
We have to make use of the explicit typecast concept to fulfill our requirements.
In this video tutorial, the steps are mentioned and the instructor had given a complete explanation of how to do it.
Here's a full, detailed course description for the Java Naming Conventions topic:
Java Naming Conventions – Write Clean, Readable & Professional Code
Welcome to this essential section of the Full Stack Java Developer course by Chaand Shiekh. Before you write thousands of lines of code, you need to learn how to name things the right way. Naming conventions might seem like a small detail, but they are one of the biggest factors that separate beginner code from clean, professional, industry-standard code.
In this section, you'll master the official naming rules recommended by Oracle and followed by Java developers and top companies across the world.
What You'll Learn
1. Why Naming Conventions Matter Understand how consistent naming improves code readability, makes debugging easier, helps teams collaborate, and keeps large projects maintainable over time.
2. Class & Interface Naming Learn to use PascalCase (also called UpperCamelCase), where every word starts with a capital letter. Classes should be nouns, while interfaces are often nouns or adjectives.
Examples: Student, BankAccount, EmployeeManager, Runnable, Comparable
3. Method Naming Methods should use camelCase and typically begin with a verb, since they represent actions.
Examples: getName(), calculateSalary(), sendEmail(), isAvailable()
4. Variable Naming Variables also follow camelCase and should be short, meaningful, and descriptive. Avoid single letters (except in loops) and unclear abbreviations.
Examples: firstName, totalAmount, userAge, accountBalance
5. Constant Naming Constants (declared with static final) use UPPER_SNAKE_CASE, where all letters are capital and words are separated by underscores.
Examples: MAX_SIZE, PI, DEFAULT_TIMEOUT, MIN_AGE
6. Package Naming Packages are written in all lowercase using the reverse-domain-name pattern to keep them unique.
Examples: com.company.project, org.example.utils
7. Best Practices & Common Mistakes
Choose descriptive names over short, cryptic ones
Avoid using reserved keywords
Don't start names with numbers or special characters (except _ and $)
Be consistent throughout your entire project
Avoid Hungarian notation and unnecessary abbreviations
By the End of This Section, You Will Be Able To:
Apply correct naming conventions for classes, methods, variables, constants, and packages
Write clean, readable, and professional Java code
Follow industry standards used in real-world projects
Avoid common naming mistakes that confuse other developers
This lecture deals with basic operators in java as the addition, subtraction, multiplication, and division operators. (+,-,*,/). In addition to these Operators, it also contains information about the increment(++) operator which increases the value by 1 as contrast to the decrement operator(--) which does exactly the opposite. Modulo operator(%) gives the remainder of two numbers.
Java provides a rich set of operators to manipulate a variable. Operators are the symbols in Java that perform a specific operation on many operands and return the output. Before knowing the arithmetic operators, let us know the type of operator.
Java operators are divided into the following groups:
Arithmetic Operators
Assignment Operators
Bitwise Operators
Logical Operators
Relational Operators
Operators
Arithmetic operator
In this tutorial, we will discuss the arithmetic operator. Mathematical operations are done by using arithmetic operators. The following table displays all the arithmetic operators supported by java. Assume integer variable “A” holds value 5 and variable “B” holds value 10.
Addition Operator
Plus (+) operator is used for the addition of two numbers. In addition to adding two numbers, the addition operator is also used for string concatenation.
Subtraction operator
Minus (-) operator is used for subtracting the second operand from the first.
Multiplication Operator
Multiplication (*) operator used to multiply two numbers.
Division Operator
Division operator (/) used to divide numerator by de-numerator and it gives the quotient.
In the following illustration 12 divided by 2 and the result is 6.
Modulus operator
Modulus operator used to returns the remainder of one number divided by another.
Increment operator
Increment operator is a unary operator that increments its operand by one. This operator can be used for both postfix(x++) as well as a prefix (++x).
Postfix-In the postfix form, it evaluates the value of the operand before the increment operation.
Prefix-In the prefix form it evaluates the value of the operand after the increment operation.
So do you now understood the difference?
In prefix, the value of the variable will get incremented first and then the statement will get executed. Whereas in postfix, the statement will be executed with the current value of the variable and then the value gets incremented
Decrement operator:
Decrement operator is also a unary operator that decrements its operand by one. This operator can be used for both postfix(x--) as well as a prefix (--x).
Postfix-In the postfix form, it evaluates the value of the operand before the decrement operation.
After this tutorial, you will be able to use these operators efficiently in your program.
In this video tutorial, we will take one simple example to define operations using the decision-making concept. All the basic arithmetic operations programs will be provided with an explanation in each of the parts.
This tutorial deals with the 'if' condition. The if condition verifies the basic yes or no condition. If this given condition is satisfied the statements inside the if cases are executed. Or if false the 'else' case is executed(if written or defined). The scope of the if statement and the implementation of this will be discussed further.
In this video tutorial, we will take one simple example to define operations using the decision-making concept. All the basic arithmetic operations programs will be provided with an explanation in each of the parts.
This tutorial is the continuation of the lecture above. In the lecture the implementation of if condition is shown.
This lecture deals with more cases that could be used in if-else condition. The use of &&(and) operator and ||(or) operator for condition checking is used along with !(not) or negation operator. At the end of the lecture, we will be able to use these in our programs efficiently.
This tutorial deals with three operands we use the ternary operator. It can be used as a single-line substitution for the given if-else condition. We can also use it to replace the switch. The basic syntax of the ternary operator along with the rules is shown in the following. At the end of the lecture, we will be able to use these in our programs efficiently.
Ternary Operator In Java
The ternary operator works on three operands. It returns a value based on a condition that evaluates either true or false statements. True and false statements are also an expression that you want to evaluate. If the expression is true it evaluates the expression true otherwise it evaluates the expression false.
The ternary operator is also known as a conditional operator that evaluates a condition of if-then-else. In Java “If” statement is used to make a decision based on a condition that allows testing a condition if the condition is true, the code inside “if block” will be executed, and else statement will execute when a condition is false.
Ternary operator has three operands: Condition? Expression 1: Expression 2
The condition is evaluated.
If the condition is true then Expression1 is returned.
If the condition is false then Expression2 will be returned
The ternary operator allows you to evaluate a Boolean expression that evaluates the true or false expression. If the condition is true then it will evaluate expression true otherwise it evaluates the expression false.
The ternary operator allows to returning of an output based on the relational operator.
Note: If two primitive values are equal you must use the comparison operator “==” not “=”.
Assignment Operators
Assignment operators are a binary operator that is used to assign a value of an expression to a variable on the left-hand side of the operator, with the result of the value on the right-hand side of the equation.
In Java, the assignment operator are as follows: =,+=,-+,*=,/=,%=
The simplest assignment operator is “=” assignment (int x= 1 ;)
Compound assignment operator in java
Besides the simple assignment operator”=” there are also various compound assignment operator. For example, the following statement after the declaration of x is equivalent:
x += 5; // simple assignment operator
x = x+5; // compound assignment operator
x -= 5; // simple assignment operator
x = x-5; // compound assignment operator
x*= 5;// simple assignment operator
x = x*5; // compound assignment operator
x /= 5; // simple assignment operator
x / 5; // compound assignment operator
x %= 5; // simple assignment operator
x = x%5;// compound assignment operator
This tutorial deals with assignment operators in java which provides an easier syntax for assigning a result of arithmetic or bitwise operator. The basic syntax along with the use of 4 assignment operators which are ([+=, -=, *=, /=, %=]) is shown in the program.
Making a decision with IF-Else
In this tutorial, we deal with the advanced details of the if-else condition.
IF Statement
If statement is one of the control flow statement. In Java If statement is used make decision based on condition.
In If statement we test a condition, if the condition is true, the code inside “If block” will be executed and if the condition is false, the code inside if the condition is ignored. Braces “{ }” decides the scope of if statement.
IF-Else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
“If” block would be executed when the condition is true (if x is equal to 5), otherwise “else” block is executed when the condition is false (value of x is greater than 5. Which will execute the ‘else’ block).
The tutorial highlights the errors committed while using if condition also gives insight into the scope of the if, else, and if-else statements. The nested-if condition also described here with various cases and code blocks. At the end of the tutorial, we have a better understanding of if conditions.
These are all the source codes of the programs discussed so far in the section. At the end of each section, we have presented the same.
The switch case is a more advanced version of else and if-else conditions. The switch case is a multi-way branch statement. We can assign n number of conditions for n cases in short as a contrast to the else and if-else. It also doesn't require code blocks. There are various further uses and details which will be seen further.
Switch Case
Switch case statement in java is the conditional statement that executes one statement out of many statements when the condition is matched. Default statement is executed when none of the conditions is matched.
Switch case always works on condition, switch case is always used with a break statement.
Do you Know?
It is not necessary to write case statements in sequence.
Only int, char, String, and Enum are allowed as switch expression.
This tutorial contains more in-depth information about the switch. The switch condition can only make use of int, char, and enum datatype. (enum is to be seen further- It is a user-defined datatype). The switch conditions have a variety of features as such multiple conditions for the same output. The implementation of the char datatype in the switch case is also shown here.
String as an expression
A String can be used as an expression in a switch statement. This switch statement expression is compared with the expression of each case. This comparison is case sensitive, so we convert all expressions into lower cases.
The following program explanation is provided in the video tutorial.
In this topic, we will make use of string as an expression methodology and try to execute the program using the switch case approach.
This tutorial about the switch case contains information about implementing the switch with String datatype. Also working with functions with String to manipulate the outcome of the program and apply various conditions for the same output is shown.
Program explanation is provided in the tutorial.
This tutorial deals with the implementation of for loop. The for loop deals with executing the code continuously over a given range of values specified by the user.
In a programming language, a loop means repeating the execution to the instruction or instruction block with respect to the condition specified by the programmer.
Types of loops in Java
while loop
for loop
do-while loop
For loop
In Java for loop is used to iterate a part of the statement multiple times until a particular condition is satisfied.
Syntax
for(initialization; condition; increment/decrement)
In the basic structure of for loop, there exist three parts
Initialization of variable
Condition
Variable increment /decrement
Initialization of variable
It initializes the variable which starts the loop. It does not matter how many iterations are present. It executed only once at the beginning of the “for” loop.
Condition
It is used for testing the exit condition and returns the Boolean value true or false if the condition is true the body is executed else the loop terminates without executing the statement loop body.
The condition in the loop doesn’t have any restriction; we can use any condition and any number of comparisons.
Variable increment and decrement
The increase and decrease part of for loop is used for updating the variable for the next iteration.
Note: All of the above is an optional component for a loop.
The further detailed implementation is shown in the next lecture along with implementation for prime numbers.
This tutorial deals with the implementation of a while loop in java. The while loop in java is same as a for loop and used to execute a statement repeatedly until it satisfies the given Boolean condition. It also deals with the condition of an infinite loop which can arise in the while loop.
while loop
while loop in Java is a structure that executes a statement of code multiple times until the boolean expression is false.
In while loop, boolean expression is evaluated before the execution of code. If the boolean expression is evaluated as true, then only the execution of code starts, and if the expression is evaluated as false, the block of code inside while loop will not be executed.
Infinite loop
The boolean expression, that is evaluated before each loop iteration is never modified, so the expression (true) will always evaluate true. The result is, the loop will never end. It is known as an infinite loop.
Difference between for loop and while loop
For loop is used when we know the number of iterations. For example when we are sure that how many times we need to execute a loop.
While loop is used when we are unsure about the number of iteration and want to loop while some condition is true. It will loop that block until the condition is false.
This tutorial deals with the do-while condition in Java programming. In this tutorial, the basic difference in the do-while, while, and for the loop is shown. The do-while loop is a variant of while loop which will execute for at least one time even if the condition is false. Hence this program will explain the concepts of the do-while loop in java.
do...while loop
Java allows you to create a do-while loop, which likes almost similar to a while loop, which is a structure of the repetition control with a termination condition and statements, or block of statement.
Difference between while and do-while loop
In Java While loop, the expression is evaluated at the beginning of the loop and if the expression is evaluated as True then only statements inside the while loop will be executed. So, while loop executes the code block only when the expression is true.
In Java Do While loop, the expression is evaluated at the end of the loop so even if the expression returns false, statements inside the code block will be executed at least once. Observe the semi-colon at the end of while condition’s parenthesis
Note:
Use while loop when a loop might not be executed at all.
Use a do-while loop when the loop is executed at least once.
This tutorial deals with the multi-variable implementation of for loop and the while loop. The implementation of these loops regarding a single boolean condition was discussed earlier. After the completion of this section, users will get a complete reference about various types of loops and their variants along with their implementation.
Break and continue statement
In this tutorial, we will discuss the Break and Continue statement.
Break statement
Sometimes it is required to do terminate the loop, without verifying test expression. In such cases break statement can be used. The break statement normally used with the conditional switch statement and do, while, or for loop statement. The break statement transfers the flow of control out of the current scope.
Continue statements
Sometimes if the programmer wants to skip a few statements inside the loop. In such cases, continue statements are used. Generally, the continue statement ends the current iteration of the loop.
In this section, you'll learn what the for-each loop is, how it works internally, when to use it, and when not to use it.
What You'll Learn
1. What Is the for-each Loop? Introduced in Java 5, the for-each loop is designed specifically for iterating over arrays and collections without needing an index variable or manual condition checks. It reduces boilerplate code and makes your loops cleaner and easier to read.
2. Syntax of the for-each Loop Understand the simple structure of the enhanced for loop:
java
for (dataType element : arrayOrCollection) {
// use element
}
dataType – the type of each element
element – a variable that holds the current item in each iteration
arrayOrCollection – the array or collection you want to loop through
3. Using for-each with Arrays Learn how to iterate through arrays effortlessly:
java
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
4. Using for-each with Collections See how the for-each loop works beautifully with List, Set, and other collections:
java
List<String> names = new ArrayList<>();
names.add("Ravi");
names.add("Priya");
for (String name : names) {
System.out.println(name);
}
5. How It Works Internally Understand that the for-each loop uses an Iterator behind the scenes for collections, which is why it's clean and safe for reading elements.
6. Advantages of the for-each Loop
Cleaner and more readable code
No need to manage index variables
Reduces chances of ArrayIndexOutOfBoundsException
Less boilerplate compared to the traditional for loop
7. Limitations of the for-each Loop You'll also learn where the for-each loop falls short:
You cannot access the index of the current element
You cannot modify the array/collection structure (adding or removing elements) during iteration
It only moves forward — no reverse iteration
Not suitable when you need to replace elements by index
8. for-each vs Traditional for Loop A clear comparison to help you decide which loop to use:
Use for-each when you simply need to read each element
Use the traditional for loop when you need the index, want to modify elements, or need reverse/conditional iteration
By the End of This Section, You Will Be Able To:
Write clean, readable loops using the for-each syntax
Iterate through arrays and collections with confidence
Understand the internal working of the enhanced for loop
Know exactly when to use for-each and when to use a traditional loop
Who Is This For?
Beginners learning Java loops
Students preparing for coding interviews
Developers who want to write cleaner, simpler iteration code
The for-each loop is one of those small features that makes your everyday coding life much easier. Master it here, and you'll write neater Java code from day one!
This tutorial deals with an advanced variant of for loop. The use of nested loops arises when we need an iteration over repeated conditions. For example, any operation on a matrix such as a matrix multiplication would require the user to iterate through rows and columns separately. The tutorial also implements the program of pattern printing which is the basic question in competitive programming.
Nested Loop
A nested loop is a loop within a loop, an inner loop within the body of an outer one. In this tutorial, we will learn the syntax for nested loops and understand the examples.
Nesting of loop is used for maintaining a structure where more than one loop can be performed. But using this type of looping structure, sometimes it becomes complex to understand the logic. Everyone who has started learning Java must practice the Nesting of loops in general.
It clarifies the concept of Java and makes a clear understanding of the concept. The inner loop and outer loop concept distinguish the structure of the loop significantly.
Another bonus video lecture made to understand the program sum of digits using decision controls and looping concept.
In this tutorial, we will see a very important topic in Java called Methods. There are various types of methods that are differentiated by the parameters passed or return type etc. In this tutorial parameterized methods and non-parameterized methods, are explained. Parameterized methods are which take any arguments (variables of any data type). These can be passed by reference or value. This will be studied further in the course.
Method in Java
In Java, Method is a block of code, which performs a specific task. It is also known as a function procedure.
"Methods" are blocks of code that can be used repeatedly by the programmer to reduce the complexity (length) of the code. There are various types of methods that are differentiated by the parameters passed or return type etc.
Method declaration has six component:
Modifiers – There are two types of modifiers in java. Access and Non-Access Modifiers
Access Modifiers are which control the scope of the defined function.
Access Modifiers are default, public, private, and protected.
Non-Access Modifiers provide additional features.
There are final, static, transient, synchronized, volatile
The return Type – The return type for the method is always the returned data type and if the return type is void, then it returns nothing.
Method Name – It should be according to the naming convention decided by Java.
Parameters – parameters are for taking input from the user. You can provide a comma-delimited list of parameters, the parameter is optional, you can use empty parenthesis if there is no parameter.
Method body – It is always enclosed between braces “{ }” and contains the code for functionality.
Methods reduce the code size and increase the reusability of the code.
Parameterized Method
This is a way of passing value from the user. Parameterization is also used to define some variables inside the method block.
Using parameterization above example can be written as
The variable step is responsible for the initial value of the loop.
The variable ‘final_value’ is responsible for the final value up to which the loop will execute.
This tutorial deals with parameters and returns types of the methods. The parameters are the variables or arguments passed to the function to be used in our program. The return type is the data type of the variable that is returned to the main function (it is not mandatory since the function can also be invoked from an external function).
Method Parameters & Return Type
Here we will deal with the parameters and return type of the method. Return type parameter which could be a value, object, or any data structure is returned by the method after the completion of its execution. The “return” keyword is used to return a value from a method.
A method can return primitive or non-primitive type value.
A method can return only a single It may or may not contain multiple values.
The “return” keyword ideally is the last statement of the method but it could also feature anywhere in the given code depending upon the code. Once the return statement is executed, the program returns to the code from where the method is called. Code written after the return statement will not be executed, it will give you a compile-time error.
This tutorial deals with the concept of method overloading. Method overloading in simple words is a set of methods that have the same name but should have atleast one of the following parameters which are unique to the method. The parameters are return type, parameters passed, and the sequence of parameters. If methods have any one of the above features which is unique to them then multiple methods can share the same name.
Method Overloading
In Java, Method overloading allows having multiple methods with the same name, if they differ in the number of arguments.
Method overloading can be achieved in the following ways:
Differs in numbers of parameter
Differs in the data type of parameters
Differs in the order of parameters.
Note: Method overloading cannot be achieved by changing the return type.
The above-given properties are verified by certain examples by taking a different number of parameters and also different datatypes for the same method name.
In this tutorial, we will check Method Overloading with the help of simple examples. The following methods will be achieved in the following ways.
Method Overloading with different number of parameter
Method overloading with a different data type of parameter
Method overloading with the difference in order of parameters.
This programming exercise defines all of these methods with a clear explanation of the concept.
Code blocks have been discussed earlier. A code block is a piece of code that is surrounded by curly braces '{}' which mark the start and end of the piece of code.
Indentation is the proper arrangement of the code by tabs or spaces such that the code is readable. It could also be done automatically by the eclipse editor which is shown in the video.
In addition, some tips and tricks about the editor are discussed here.
Here's a full, detailed course description for the Java Literals topic:
Java Literals – Understanding Fixed Values in Your Code
Welcome to this fundamental section of the Full Stack Java Developer course by Chaand Shiekh. Every time you assign a value like 100, 3.14, 'A', or "Hello" in your program, you're using a literal. Literals are the actual fixed values that you write directly into your code — and understanding them properly is essential before working with variables and data types.
In this section, you'll learn what literals are, the different types Java supports, and the special ways Java lets you represent values.
What You'll Learn
1. What Are Literals? A literal is a constant value that is written directly into the source code. For example, in int age = 25;, the value 25 is an integer literal. Literals never change — they represent the data exactly as written.
2. Integer Literals Learn how to represent whole numbers in different number systems:
Decimal (base 10) – int a = 100;
Octal (base 8, prefixed with 0) – int b = 0144;
Hexadecimal (base 16, prefixed with 0x) – int c = 0x64;
Binary (base 2, prefixed with 0b) – int d = 0b1100100;
You'll also learn about the long literal suffix L (e.g., long big = 100000L;).
3. Floating-Point Literals Represent decimal and fractional numbers:
double pi = 3.14;
float price = 9.99f; (note the f suffix for float)
Scientific notation – double large = 1.5e3; (means 1500.0)
4. Character Literals A single character enclosed in single quotes:
char grade = 'A';
Unicode literals – char ch = '\u0041'; (represents 'A')
Escape sequences – '\n', '\t', '\\', '\''
5. String Literals A sequence of characters enclosed in double quotes:
String name = "Chaand";
Strings can include escape sequences – "Hello\nWorld"
6. Boolean Literals Only two possible values:
boolean isActive = true;
boolean isClosed = false;
7. The 'null' Literal A special literal that represents "no value" or "no object reference":
String text = null;
8. Underscores in Numeric Literals A handy Java feature to improve readability of large numbers:
int million = 1_000_000;
long card = 1234_5678_9012_3456L;
The underscores are ignored by the compiler and used purely for readability.
In simple words class is a user-defined blueprint that contains user-defined variables and methods which can be accessed by entities called objects of the class. The methods and variables in the class are collectively known as the members of the class. The class is an imaginary template for the object. The class is usually used for defining the exact form and nature. The object operated on the data. These are used for depicting real-life objects and scenarios.
Classes Overview
Classes and Objects are the basic building block of Object-Oriented Programming language. The class can be created by using “class” keyword followed by a reference name.
Classes are the blueprint of object creation. Classes are the user-defined implementation of real-life scenarios. A class defines the state and behaviour of an object.
State – It is the property or variables declared inside a class.
Behaviour – It is the functions or methods created inside a class.
Getters and Setters Overview
In Java, Getter and setter methods are used to retrieve and update the private variables. When you hide the implementation of the object of the class from the outer world, you declare them as private. As private members of the class are not accessible from outside the class, so we use the getter and setter method to retrieve and update the values of private members.
We can manually write the getter and setter method for a variable. The setter method is a parameterized method with the return type as void, which is used to update the value. The getter method has a return type that will be the same as the data type of private variable.
This tutorial deals with the getters and setters assigned to a variable. This can be used especially when the variables are private (scope) that is they cannot be accessed outside from the class in which they are defined.
1. What Are Instance Variables? Instance variables are variables declared inside a class but outside any method, constructor, or block. Each object of the class gets its own copy of these variables. They are also known as non-static fields.
java
class Student {
int age; // instance variable
String name; // instance variable
}
2. Why Default Values Exist Unlike local variables (which must be initialized before use), instance variables are automatically given a default value by the JVM when an object is created. This ensures that every field always has a valid starting value.
3. Default Values for Each Data Type Learn the exact default value Java assigns to every type:
Data TypeDefault Valuebyte0short0int0long0Lfloat0.0fdouble0.0dchar'\u0000' (null character)booleanfalseObject references (e.g., String, arrays)null
4. Demonstrating Default Values See how default values work in practice:
java
class Demo {
int number;
boolean flag;
String text;
void display() {
System.out.println(number); // 0
System.out.println(flag); // false
System.out.println(text); // null
}
}
5. Instance Variables vs Local Variables A key distinction every Java developer must know:
Instance variables → automatically get default values
Local variables → get no default value and must be initialized manually before use, otherwise you get a compile-time error
6. Why This Matters
Prevents unexpected behavior from uninitialized fields
Helps you avoid NullPointerException by being aware that object references default to null
Makes your code more predictable and reliable
In this tutorial, basic functions are implemented in a class. As discussed earlier the class implements a real-life scenario such as the example above which depicts certain conditions that apply to a Car which is further explained here.
Adding functions to a class
Likewise, the class has properties, it also has functions or methods.
Let us understand the concept practically using an example, we will create a function in the class.
In this code we are validating the car’s behavior on multiple conditions. “run” function will return the behavior according to the applied conditions. Properties of the car are set in a different class.
The tutorial deals with the concept of constructors. Constructors are chunks of code that are used to initialize the variables automatically in the class to any random default value.
A constructor initializes an object as soon as it is created. It is similar to a method. The constructor can be created automatically in Eclipse and more details are described in the tutorial.
Constructor Overview
In Java, Constructor is a special method, which is invoked when an object of the class is created. It is used to initializing the class variables.
There are some rules for construction creation:
A constructor always has the same name as the class name.
A constructor is a special method that does not has any return type
The constructor is of two types
Default constructor
Parameterized constructor
This tutorial deals with the concept of the default constructor. We have seen that the constructor is the first entity which is called when an object is created. Hence if the variables are assigned while they are created then it has the same working as the default constructor when we assign random values to the specific variables.
This works fine unless the user assigns a constructor after which the user has to assign values for each of the variables.
Default Constructor
If you do not have any constructor in your class, Java compiler adds a default constructor to the class during compilation.
We will see more about the constructor with the help of an example. In the following example, we did not use the object of the class to initialize the variable, rather all the variables have been initialized using a constructor.
In Java, when you do not have any constructor in the class, so during execution Java compiler adds one constructor in the class, it is called as default constructor.
The default constructor does not have any parameters. The default constructor is used to providing the default value to instance variables.
As soon as we create the object of a class using the new keyword, the default constructor of the class is invoked.
Default Constructor added by JVM
In the following tutorial we have taken an example, wherein the Smartphone class we do not write any constructor so JVM will add a default constructor in the class, and properties of the Smartphone class will be initialized using this default constructor.
Inheritance is one of the most important OOPS concepts. This concept is important because it deals with assigning the blocks of code which are repeatedly used to a class (base class), and then using the unique properties (methods or variables) which are only used in the respective classes (derived class).
The derived classes such as the Bike, Car, and Truck automatically inherit the variables such as the engine, wheels, seats, etc. from the base class when it inherits from the base class.
Understanding Inheritance
Inheritance is used to store information and manage the information in a hierarchical order. It is the process of defining a new class based on an existing class where a child class acquires the properties of the parent class. The subclass (Child/Derived class) inherits the properties of the parent class, and the class from which the properties are inherited is called a Super Class (Parent class or Base class).
Inheritance allows us to reuse code and improve the reusability in Java application so that a class has to write only the unique features and the rest of the common properties and functionality can be extended by the other class.
Terminology
Super Class- Superclass is a class whose properties and behaviour are used by the child class.
Sub Class- Subclass is a class that inherits the properties of another class.
Reusability- Inheritance allows the reuse of code. When we create a new class and there is already a class that includes some common properties or features that a class has to write. It can be driven to the new class from the existing class by reusing the field and method.
Note: The advantage of Inheritance is that the code that already exists code in a superclass can be reused in a sub/derived class.
This tutorial deals with using the toString method instead of printing each attribute by calling the respective getter. Hence this method is also set by setting to String method from the Source tab in the menu bar. Hence we can print all the attributes by calling the toString method.
Java toString() method
In Java toString() method is used to get a String representation of an object.
We can override the object’s toString() method during implementation. The toString() method of the Object class helps us to return values of the object, so we don't need to write much code.
Inheritance as we have seen models an IS-A relation. For example the Bike IS-A vehicle. The Car IS-A Vehicle.
The composition follows a HAS-A relation. For example, Laptop HAS-A Screen, Laptop HAS-A Ram. This concept will be seen further.
Composition
The composition is the core concept of object-oriented programming. The composition is the design technique to implement a has-a relationship between different types of object/classes. We can use Java inheritance or object composition in Java for code reuse.
Difference between inheritance and composition?
In Java, Inheritance is suitable only when classes are in a relationship. For example Car, Truck Bike are a vehicle and all these vehicles have common features of vehicle class (Superclass). But to represent the engine relationship, we have an alternative to inheritance known as composition.
In inheritance, we can derive some functionality to a subclass of the parent class, in the composition a class reuses the functionality by creating a reference to the object of the class.
For example, A laptop is a composite object containing other objects such as Screen, processor, Ram, Hard drive, Graphics card, Optical drive, and Keyboard. In other words, the laptop object shares a HAS-A relationship with other objects. The laptop is a composition that consists of multiple components and works together as a team to solve a problem. The following components can be simple as well as complex.
In the following list, Screen, RAM, Hard drive, optical drive Keyboard are simple composition.
Screen -> Full HD/HD
Ram-> DDR1/DDR2/DDR3/DDR4
Hard drive-> 500 GB/1 TB/ 2TB
Optical drive-> Single layer/multilayer
Keyboard-> backlit/standard
Processor and graphics card are complex components. There are multiple things involved.
Processor
Brand
Series
Generation
No of Cores
No of threads
Cache memory
Frequency
Graphics card
Brand
Series
Memory
Composition setting up
In inheritance, we deal with the attributes of other classes. Composition studies have a relationship in which we 'inherit' or use objects from other classes.
In the following example, Laptop HAS-A Processor may have many features. Therefore, we inherit the object and then access the attributes through these objects.
In this tutorial, we will study composition example. In Inheritance, we dealt with the attributes of other classes. Composition studies HAS-A relation in which we 'inherit' or use the objects of other classes. For example, Laptop HAS-A Processor may have many features. Hence we inherit the object and then access the attributes through these objects.
Working with composition
As we discussed, the classes inherit the objects of other classes.
This tutorial is a further continuation of the above composition topic. In this topic as discussed the classes inherit the objects of other classes. Hence to access the attributes we need to create the getters to return the object of the classes by the virtue of which we can access the required attribute.
Importance:
By using composition, we can control the visibility of another object for customer classes and reuse only what we need.
The composition allows the creation of backend classes when necessary.
This tutorial deals with the concept of encapsulation.
Encapsulation simply means restricting access to class variables or methods to outside classes or packages.
This is brought into action in order to impose some restrictions on the variables.
Encapsulation
In Java, Encapsulation is the process of binding the class members (variables and methods) into a single unit. It protects the data of the class to be accessed from outside the class.
In Encapsulation, we hide the implementation details from the outer class and provided them the controlled access to the class.
Encapsulation can be achieved by declaring the instance variables as private. However, we can access the private variable through the getter and setter method. setter method used to update ( void setAge() ) and getter method is used to read (int getAge() ) the value of private variable.
In the following example, we demonstrate how to implement encapsulation and the benefits of encapsulation.
Person class has some public properties and these properties can be accessed and modified from the outside classes.
This concept will be studied in detail in forthcoming videos.
This tutorial is in continuation of the previous lecture regarding the same topic. Encapsulation is the restriction implied on the class members so as to restrict their access to outer classes. Here such an example is provided where the outer class cannot initialize other classes with a non-parametrized constructor.
To implement the encapsulation concept, we need to convert the public properties into private, and to get the default value of these variables we need the getter method.
This tutorial deals with the concept of polymorphism. Polymorphism in simple words means to have multiple forms of a single entity.
In the above example when a note8 object call features methods by different scopes (class scope, one of Phone, and one of SamsungNote8) we obtain different outputs. This concept will be studied further.
This is a continuation of the above tutorial. In this tutorial, another such example of the same function depicting a different output when referenced by the object of the different class is shown.
Here the same example as above is taken in an altogether different function outside the main function which has a return type of Phone class.
These are all the source codes of the programs discussed so far in the section. At the end of each section, we have presented the same.
These are all the source codes of the programs discussed so far in the section. At the end of each section, we have presented the same.
This tutorial deals with interfaces. The interfaces are somewhat similar to a class but have very interesting properties. Interfaces serve as an outline of the class 'implementing it'(inherit). The members declared in it are public, static by default.
Hence we can have a constructor for an abstract class (which will be discussed further) but not for the interface as it contains static members.
If any method (abstract by default) is not declared in the class implementing it then the class has to declared as abstract.
A method which only declared and not defined is called an abstract method. A class can contain zero or more abstract methods. We cannot create an object of an abstract class.
Hence we have to use inheritance to define the method (abstract).
But the class that we created to extend the abstract should define all the abstract methods. The new class which extends the abstract class is called the Concrete Class.
If the Concrete class doesn’t define all the methods, then we have to define the class as abstract too.
Why should we use the abstract class.?
Consider a class Person. Consider two classes Students and Faculty which inherit from the Person class.
Hence we don’t want to create an object of class person but only Students and Faculty.
Here is the use of the abstract class.
Inner Classes
Here in Java Inner classes is the concept where we want to add more encapsulation to the given code. When we declare a class inside a class then the inside class can access all the private members in addition to the inner class can be hidden from the outside world.
Also, it is logical to group two classes that are related together. In this tutorial, we will discuss non-static inner classes.
Types of inner class in java.
Nested Inner class
Method Local Inner class
Anonymous Inner class
Static Inner class
The types of nested classes are categorized here. Category of the nested class, we have already seen in the inner class and further types will be seen in the forthcoming articles.
In Java, It is possible to specify, a class within another class, such classes are known as nested classes. They allow you to logically group classes that are only used in one place. Therefore, this increases the use of encapsulation and creates a more readable and maintainable code.
Nested classes are divided into two types:
Nested, non-static classes - Non-static classes are an inner class. We know that a class cannot be associated with the private access modifier, but if we have the class as a member of another class, then the inner class can be made private. And this is also used to access private members of a class.
Static nested classes −These are members of a class and declared static are called static nested classes. It can be accessed without creating an instance of the external class, using other static members. Like static members, a static nested class does not have access to the instance variables and methods of the external class.
The working of the local inner class which is defined or structured inside the outer class is shown here. Here the example of door and lock is shown as a real-life example.
The advantage of such case is the inner class is completely hidden from the outside world.
If the user enters the correct key and executes the following program, then the output would be false; otherwise, the user will get the output.
Anonymous Object
The anonymous object simply means creating a new Object without assigning it to a reference. Hence this could be used only once in the execution of a program as it is not referenced to any object.
It is useful for writing implementation classes for listener interfaces in graphical programming.
Let us take a simple program, to understand an anonymous object.
Here, an object for Door class is not created. We can create a new Object without assigning it to a reference.
Anonymous Inner Class
Java anonymous inner class can be created in two ways, it can be abstract or concrete.
The class that has no name and that is used to overwrite an interface or an abstract method is called an anonymous inner class.
It is an inner class with no name and for which a single object is created. An anonymous inner class can be useful when creating an instance of an object with certain "extras", such as the overload methods of a class or interface, without having to actually subclass a class.
It is useful for writing implementation classes for listener interfaces in graphics programming.
A class is created but its name is decided by the compiler which extends the lock class and provides the implementation of the isUnlocked method.
An anonymous class is created that is referred by lock variable of lock type. In order to get lock method, we are adding a getter method.
An advantage of Inner Class
This tutorial depicts the Advantage of Inner Class as we have discussed so far in this series of tutorials. Inner classes are the concept where we want to add more encapsulation to the given code. When we declare a class within a class, the inner class can access all the private members, in addition to the inner class, it can hide from the outside world.
An advantage of inner classes
In Java, there are three advantages of inner classes. They are as follows:
The inner class could be used only by the outer class. Inner classes represent a special type of relationship that allows access to all members (data members and methods) of the outer class, including the private class.
Inner classes are used to develop a more readable and maintainable code because they logically group classes and interfaces in one place.
Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to write. It can avoid having a separate class.
User Input
This tutorial tries to take information from the user using the Scanner class. There were several types of datatype as we have seen previously.
Sometimes, we can face a situation where we need to get information from the user at runtime. We use the "Scanner" class to accept user input to obtain user information. The Java Scanner class comes under java.util package. To use the Scanner class, we need to import the java.util package to our program.
The syntax for each of the data types is discussed here. Therefore, the user may receive input from the user.
One of the strengths of Java is the huge code libraries available to you. This is the code that has been written to do specific jobs. All you need to do is to reference the library you want to use and then put a method in action.
A really useful class that handles a user's input is called the Scanner class. The Scanner class is present in java.util package. To use the scanner class, you need to import this package into our program.
Static Elements
Java allows you to access static members, static members are class level and can be accessed directly without any instance. For example. The static keyword means that the variable or function is shared among all the instances of that class since it belongs to the type, not to the real objects themselves.
The implementation of a static variable is shown here. The basic concept of a static variable is that it has a single reference variable.
In this way, the utilization of such variables should be possible to keep up a basic count of created objects or objects that access a class.
Static Inner Class
We have seen the inner classes. The inner classes can access the outer variables. The static inner class can only access static members. Hence the non-static members when tried to access give an error.
A static class in Java, created within a class is called a static nested class. It is unable to access non-static data methods and members. It can be accessed by an outer class name. You can access the static data members of the outer class, including private ones.
The following example is demonstrating the static inner class would not compile because the static inner class tries to access the non-static member of the outer class that is not permitted.
This lecture is a continuation of the above lecture.
Here the properties of the inner static class are shown and also how they can access the outer class variables and methods is shown. After the lecture user will learn how we can use this type of class in our daily programs.
Final Keyword
Final keyword can be applied to variables, methods, classes, etc. It is used in various contexts to define an entity that can only be assigned once. Once a final variable has been assigned, the variable cannot be changed. Therefore, the user tries to change the value using the setter or the constructor, and then the errors are entered into the program.
In this tutorial, the use of the final keyword in a program is shown. When a final keyword is assigned to a variable then the variable cannot be changed. Hence we the user tries to change the value using setter or constructor then errors creep into the program.
More use of this word will be seen further.
Final variable
If you make a variable as final, you cannot change the value of the final variable. There is a final variable x, we are going to change the value of this variable, but it cannot be changed because we have defined the final variable in constructor B().
If you make a variable as final, you cannot change the value of the final variable. In the following program, there is a final variable x.
A variable that is not initialized at the time of declaration is known as a final blank variable. We must initialize the final variable in the constructor of the class, otherwise, it will throw a compilation error.
The final keyword is very useful for the following purposes. When we define a method as final then it cannot be modified by any other class overriding the same method.
If a class is defined as final then it cannot be used for inheritance and cannot override any method.
Packages
It is a way to group many classes belonging to a specific project. A package is like a folder of similar things such as music or a folder of movies.
The package adds a different level of inheritance, this level of inheritance is by default applied to all the members created in the method. Hence a package is a useful and efficient entity in java. The package also has a naming convention which we have studied earlier. We can also import the packages which will result in accessing all the classes and methods in it.
The company uses always reversed Internet domain names for its package names. For example, the company's Internet domain name is studyasy.org, and then all its package names start with org.studyeasy
Every component of the package name corresponds to a subdirectory.
In the following program, we have created two different packages. In both packages, we have created the same name classes. The import statement in Java allows you to refer to the classes that are declared in other packages that can be accessed without referring to the full name of the package.
This is a continuation of the above topic. The same example which addresses the topic is used. A package is imported and hence used in other classes. Also, various ways to import classes are shown here.
Scope in Java
The scope of the variable is defined by the passage of the variable in which it can be used and accessed. The scope is an important concept in the OOPS. We have learned that public, private, protected, and default which is the package. These are the scope operators which operate on a variable to decide their existence in various parts of the code.
The following code demonstrates the variables declared within a method have a method level scope and cannot be accessed outside the method.
The Scope of variables method has a variable defined with the name i. This variable (local variable) is defined within the main method, which is initialized in for loop.
A variable i is accessed within the method, it will check the declaration of the variable in the current scope (that is, between braces). How the statement is in its current scope. in the main method, the local variable i is accessed in its current scope. Then, this variable takes the value and the println() method will print the output.
Access modifier
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, and data member.
There are four types of access modifiers:
Private
Public
Protected
Default - No keyword is required
We will learn all these access modifiers with the help of a program in the following videos.
In this example, we will create two packages org.studyeasy.parent and org.studyeasy.child. Class A in org.studyeasy.parent is made public, to access it in org.studyeasy.child. The variable display in class A is private and class B is inherited from class A and this private variable is then accessed by creating an object of class A.
The public variable is visible everywhere in contrast to the private variable which is a local variable to a class and the protected variable which is also not visible in the different classes until It has the same package.
The public access modifier is specified by the keyword public. You can access classes, methods, or data members that are declared public from anywhere in the program. There are no restrictions on the scope of public data members.
The program specifies all the access modifiers mentioned in the access modifier table.
The above concept is explained with the help of a table that includes all levels of access. (in the class) which also includes packages, subclass, and non-subclass.
Exception handling
Exception Handling is done to avoid errors that occur during the runtime of the program. Hence in such cases, we take care of such exceptions to prevent the program from ending abruptly.
To avoid the crashing of the programs due to the occurrence of some exceptions such as divide by zero or file not found etc we use the concept of exception handling.
In this, we use a try block which has a mechanism to pass the exceptions that occurred in the block to the catch block where we can continue the further execution of the program by printing the exception in the try block.
This is a continuation of the above lecture as it shows multiple catch blocks for a single try block. It also shows the hierarchy of the exception classes. All the exceptions can be further classified into Throwable and Unchecked Exception which can be further classified into many more which will be seen forward.
This further explains the concept of a hierarchy of the exception classes. This hierarchy if not maintained can transform into the code being unreachable at some points. For example, if the Exception catch block appears before the Arithmetic Exception Block then the latter will become unreachable as the Exception will catch all the thrown exceptions.
Finally block
The finally block is the block that always gets executed no matter the program throws an exception or not. But we have to follow some basic conditions that the catch blocks always is after the throw block.
This could be used to execute an important segment of code we always want the compiler to execute no matter what is the state of the exception.
Throw and throws
Throws are used to suppress the error if the user doesn't want to specify the try and catch block. Note that this doesn’t handle the error only suppresses it. It should be used only when the developer is sure that the error doesn't occur.
The throw is used to forcefully throw an error where it is decided by the developer regarding certain conditions.
The keyword "throw" is used to throw an exception from any method or static block, while the keyword "throws", used in a method declaration, indicates what exception can be thrown with this method. They are not interchangeable.
In a program, if there is a possibility that an exception occurs, the compiler always warns us and we must handle that checked exception. Otherwise, we will get a compile-time error.
To avoid this compile-time error, we can handle the exception in two ways:
By using try-catch block
By using throws keyword
User-defined exception
A user-defined exception is manually defined by the users as suggested by the name. For example, while developing a simple HTML form we want to throw an exception when the password length is less than 8 than such exceptions are used.
In the following program, we have created a user-defined exception by extending the Exception class. We provide the exception information through try and catch block.
Through catch block, we provide the bracket e and hold the information that this is an exception of Exception, FileNotFoundException, UserDefinedException which is customized created.
Then keyword “throw” is used to create a new Exception (Exception, FileNotFoundException, UserDefinedException) and throw it to the catch block. “throw” keyword always written inside the method.
Always remember when you create your own exception keep the following point in your mind:
All exception should be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or declare rule, you must extend the Exception class.
Checked and unchecked exceptions
In Java, there are two types of exceptions:
Checked exceptions
Unchecked exceptions.
Java makes this division of exceptions depending on the level of importance of the exception. The checked exceptions are handled by the java compiler itself and the unchecked exception are handled by the user (not mandatory) in case of occurrence of such exceptions.
If any code within a method throws a checked exception, then the method must handle the exception or must specify the exception using the keyword throws.
For example, consider the following Java program we make use of the FileReader class object and initialize it. The program is not compiled, because the main function uses FileReader() and FileReader() throws a checked exception FileNotFoundException.
To fix the above program, we need to specify the list of exceptions using throws, or we need to use a try-catch block.
Unchecked exceptions are not checked at compile time. All exceptions are disabled, so the compiler does not force them to handle or specify the exception. This is handled by the user (not mandatory) in case of the occurrence of such exceptions.
Consider the following Java program. It compiles well but throws ArithmeticException when it runs. The compiler allows you to compile because ArithmeticException is an unchecked or runtime exception.
1. What Is a String? A String is a sequence of characters. In Java, String is not a primitive type — it's a class in the java.lang package. A String object holds text enclosed in double quotes.
java
String name = "Chaand";
2. Creating Strings Learn the two main ways to create Strings:
String literal – String s1 = "Hello";
Using the new keyword – String s2 = new String("Hello");
You'll understand the difference between these two approaches and when each is used.
3. The String Constant Pool Discover how Java optimizes memory by storing string literals in a special area called the String Constant Pool. Learn why two identical literals can point to the same object, while new String() always creates a separate object.
4. Strings Are Immutable One of the most important concepts: Strings in Java cannot be changed once created. Any operation that seems to modify a String actually creates a new String object. You'll learn why immutability is useful for security, caching, and thread safety.
5. Common String Methods Master the most-used methods of the String class:
length() – number of characters
charAt(index) – character at a position
toUpperCase() / toLowerCase() – change case
trim() – remove leading/trailing spaces
substring() – extract part of a string
indexOf() / lastIndexOf() – find character/substring positions
replace() – replace characters or text
contains() – check if text exists
split() – break a string into parts
concat() / + – join strings
6. Comparing Strings A critical topic every developer must understand:
== – compares references (memory locations)
.equals() – compares actual content
.equalsIgnoreCase() – compares content ignoring case
.compareTo() – compares strings lexicographically
You'll learn why using == to compare string content is a common bug.
7. String Concatenation Learn different ways to join strings and how concatenation works with other data types:
java
String msg = "Age: " + 25;
8. Escape Sequences in Strings Handle special characters inside strings:
\n (new line), \t (tab), \" (double quote), \\ (backslash)
9. Introduction to StringBuilder & StringBuffer Since Strings are immutable, learn why StringBuilder and StringBuffer are preferred when you need to modify text frequently — offering better performance for operations like appending in loops.
By the End of This Section, You Will Be Able To:
Create and manipulate Strings confidently
Understand immutability and the String Constant Pool
Use built-in String methods effectively
Compare strings the correct way using .equals() and .compareTo()
Know when to use StringBuilder/StringBuffer instead of String
In this section, you'll learn exactly how Java stores Strings in memory and why the way you create them matters.
What You'll Learn
1. Two Ways to Create a String Recap the two creation methods:
java
String s1 = "Hello"; // String literal
String s2 = new String("Hello"); // String object
2. What Is a String Literal? A String literal is text written directly in double quotes. When you create one, Java first checks the String Constant Pool to see if that exact value already exists.
If it exists → the variable points to the same existing object
If it doesn't → a new object is created in the pool
This reuse saves memory.
3. What Is a String Object (using new)? When you use new String("Hello"), Java always creates a brand-new object in the heap memory, even if the same value already exists in the String Constant Pool. This means no reuse happens.
4. The String Constant Pool Understand this special memory area inside the heap:
Stores string literals
Enables reuse of identical strings
Improves memory efficiency and performance
5. Memory Comparison – Literals vs Objects See how the two differ in memory:
java
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b); // true (same pool object)
System.out.println(a == c); // false (different object in heap)
System.out.println(a.equals(c)); // true (same content)
6. Why == Behaves Differently A crucial concept:
== compares references (memory addresses)
.equals() compares the actual content
This is why two literals return true with ==, but a literal and a new object return false.
7. The intern() Method Learn how to move a heap String into the String Constant Pool:
java
String c = new String("Java").intern();
System.out.println(a == c); // true
The intern() method returns the pooled version of the string.
8. Which One Should You Use? Best practice guidance:
Prefer string literals in almost all cases — they're memory-efficient and faster
Avoid new String() unless you have a specific reason to force a new object
By the End of This Section, You Will Be Able To:
Explain the difference between string literals and string objects
Understand how the String Constant Pool works
Predict the output when comparing strings with == and .equals()
Use the intern() method correctly
Choose the right way to create strings in real-world code
1. Why String Formatting Matters Plain printing often produces messy, uneven output. Formatting lets you align text, control decimal places, pad numbers, and create clean, professional-looking results — essential for reports, tables, and real-world applications.
2. Introduction to printf() Learn how System.out.printf() works. Unlike println(), it lets you embed format specifiers inside a string and supply values to fill them in.
java
System.out.printf("Name: %s, Age: %d%n", "Chaand", 25);
3. Understanding Format Specifiers Master the most commonly used specifiers:
%d – integer (whole numbers)
%f – floating-point (decimal numbers)
%s – string
%c – character
%b – boolean
%n – platform-independent new line
%% – prints a literal percent sign
4. Formatting Decimal Numbers Control how many decimal places appear — extremely useful for money and measurements:
java
System.out.printf("Price: %.2f%n", 99.5); // Price: 99.50
System.out.printf("Pi: %.3f%n", 3.14159); // Pi: 3.142
5. Width and Alignment Create neatly aligned columns by setting field width:
java
System.out.printf("%10s%n", "Java"); // right-aligned in 10 spaces
System.out.printf("%-10s|%n", "Java"); // left-aligned (- flag)
6. Padding Numbers with Zeros Add leading zeros for clean numeric display:
java
System.out.printf("%05d%n", 42); // 00042
7. Formatting with Commas (Grouping) Make large numbers readable:
java
System.out.printf("%,d%n", 1000000); // 1,000,000
8. The String.format() Method Learn how to build a formatted String instead of printing directly — useful when you want to store or reuse the result:
java
String result = String.format("Total: %.2f", 250.5);
System.out.println(result);
9. printf() vs println() vs String.format() Understand when to use each:
println() – simple, quick output
printf() – formatted output printed directly
String.format() – formatted output returned as a String
10. Common Mistakes to Avoid
Mismatching specifiers with argument types (e.g., using %d for a decimal)
Forgetting %n or \n for new lines
Wrong argument order
By the End of This Section, You Will Be Able To:
Use printf() to produce clean, formatted output
Apply format specifiers for numbers, strings, characters, and more
Control decimal places, width, alignment, and padding
Use String.format() to build formatted strings
Choose the right printing method for any situation
Enum in Java
Enum is used to define a set of constants in java. Not only constant by it could also call any method, constructor associated with it. Which will be seen further in the tutorial.
We should always use enum when a variable (especially a method parameter) can only take one from a small set of possible values.
Enum is default public static hence we can directly reference variable by Enum Name.
You can define an enum type either independently or as part of a class.
These are all the source codes of the programs discussed so far in the section. At the end of each section, we have presented the same.
Array overview
An array is basically a collection, an arrangement of similar datatypes entities. It is used to assign a common variable name for accessing a large number of entities of the same datatype by the difference of the index number. Data stored in an array has contiguous memory locations.
An array is a static data structure to store more than one value, it acts as a container that contains a collection of homogeneous elements. Thus, this tutorial deals with the initialization, working of an array, and various other datatypes. In arrays, all elements are stored under one single variable name. So, we have a reference variable that will be pointing to the array. Also, how to access the array and certain elements located at various indexes is shown here.
Note: In array, we can't store different types of data in the same array. So if we create an array for integers, the data must be in the form of integer type.
Types of Arrays
There are various different types in which we can represent data in an array. In Java, only two types of arrays are used:
Single Dimensional Array(1D array): It is a type of array where elements are stored in a continuous row. In a 1D array, the elements of the array are defined in a row and the values are stored in a linear order(one after another).
Multidimensional Array: It is a type of nested arrays, where a lot of data can be stored. Multidimensional arrays don't have limitations with respect to memory. Hence, an ideal choice to represent a large amount of data elements.
Note: In Java, we don't have an array of arrays known as two-dimensional arrays.
Arrays are further defined in two basic data types:
Numerical arrays: int, float, double.
Character arrays: These arrays are those which we declare with a char data type.
The array as seen above is a collection of entities that have similar data types, thus this tutorial deals with the initialization of an array. And various other datatypes. Also how to access the array and certain elements located at various indexes is shown here.
Declaration of an array in Java:
dataType[] arrayName;
Initialization of an array:
int[] intVariableArray = {1,2,3,4,5,6,7,8,9,10};
The length of the array is determined by the number of values provided that are separated by commas. In this example, the length of intVariableArray is 10.
You can easily access and alter the elements of an array by using its numeric index. The default initial value of the index of an element of an array is 0.
Foreach loop
Here we deal with the for and foreach loop which is the advanced version of for loop. The for loop can be used to iterate over the elements of the array. The foreach loop is a shorter version of the same.
This is the ordinary approach of the "for" loop. In the following example, you can see the use of index of the array as a counter.
For-Each Loop helps us to reduces the code significantly, and there is no use of the index or, rather the counter in the loop.
This tutorial deals with call by value and call by reference. While passing a value to function outside the main function, the value in the main function remains unchanged as there is no actual change in the value in the desired memory location. By while passing the value by reference, (such as we pass a pointer to the memory location in C) we can pan the array (which by default passes the address) so that the change can be seen in the variable.
Method Call by value and reference
Call by value means to call a method with a parameter as a value. Through this, the value of the argument is passed to the parameter.
Call by reference means call a method with a parameter as a reference. Through this, argument reference is used to pass the parameter.
In the following example, while passing a value to function outside the main function, the value in the main function remains unchanged as there is no actual change in the value in the desired memory location.
Method Arguments in Java – Call by Value vs Call by Reference
Welcome to this important and often-misunderstood section of the Full Stack Java Developer course by Chaand Shiekh. When you pass data into a method, how exactly does Java handle it? Does the method receive a copy of your value, or the original itself? This is one of the most confusing — and most frequently asked — topics in Java interviews. In this section, you'll finally get complete clarity.
What You'll Learn
1. How Java Passes Arguments First, the big truth that clears up most confusion: Java is always call by value. Java never passes the original variable itself — it always passes a copy. What that copy contains is what changes the behavior, depending on whether you're passing a primitive or an object reference.
2. Call by Value with Primitives When you pass a primitive such as an int, double, or char, a copy of the actual value is handed to the method. Any changes made inside the method affect only that copy, so the original variable outside the method stays exactly the same.
java
void change(int x) {
x = 100;
}
int a = 10;
change(a);
System.out.println(a); // still 10
3. Passing Object References When you pass an object, Java passes a copy of the reference (the memory address), not the object itself. Both the original variable and the copy point to the same object in memory. Because of this, changes made to the object's internal data inside the method are visible outside the method as well.
java
void update(Student s) {
s.name = "Updated"; // affects the original object
}
4. Why People Call This "Call by Reference" (and Why That's Misleading) Because object changes are visible outside the method, many beginners assume Java is call by reference. You'll learn the precise truth: Java passes the reference by value, which behaves like reference passing for object data — but is technically still call by value.
5. The Key Distinction – Modifying vs Reassigning This is the concept that makes everything click. If you use the reference to modify the object's fields, those changes are visible outside the method. But if you reassign the reference to a completely new object inside the method, the original reference outside remains untouched.
java
void reassign(Student s) {
s = new Student(); // original reference outside is unchanged
}
6. How Arrays Behave Since arrays are objects in Java, passing an array to a method passes a copy of its reference. This means changes made to the array's elements inside the method are reflected in the original array outside.
java
void modify(int[] arr) {
arr[0] = 99; // original array is affected
}
7. How Strings & Wrapper Classes Behave Strings and wrapper objects such as Integer appear to behave like primitives. You'll learn that this is because they are immutable — their values can't be changed once created — so a method can never alter the original object.
Issues with Array
There are many issues with the array, such as the memory factor, where the user once assigned any memory to the array cannot add or change the memory and append any other element to it.
There are significant weaknesses when working with arrays, these includes:
Fixed-size (We can create a structure with a fixed number of member variables, but we can't change that amount)
Expensive to move many of the entries in an array
All the entries of an array must be of the same type
You cannot traverse back to the original state and change the memory once the memory is allocated.
ArrayList
ArrayList in Java is used to store a collection of dynamic-sized elements. Unlike arrays that have a fixed size, an ArrayList automatically increases its size when new elements are added.
Here all the basic operations associated with the Arraylists are shown such as append the name to the ArrayList, remove by position, remove by the string (case sensitive) and also get the position of the element given.
The following example demonstrates:
Creation of an ArrayList
Addition of new elements to an ArrayList using the add() method
Consider the following amazing experiment which shows:
Removal of the element by position
Removal of the element by object name
This is a continuation of the above tutorial. In this tutorial, the further implementation of search by position using indexOf() function and also the modification entity with the help of function is shown here.
In the following program, we can search an element from the list, if the element is available in the list, it returns the index of that element else it returns -1.
Autoboxing and Unboxing
In this tutorial, we will learn about what is autoboxing and unboxing. The ArrayList is very efficient, as we have seen, but it includes some more interesting features that are seen in this tutorial.
ArrayList only accepts the elements that are an object for a class such as an Integer class or any class defined by the user, but not for any primitive data type. Therefore, if we define the class as an Integer and not as a class defined by the user, then java automatically simplifies the work to create necessary new objects and the same while getting the value through indexing which we have to manually define while using a user-created class both of which examples are shown.
In the following example, ArrayList accepts the elements which are an object to a class such as an Integer class but not for any primitive data type.
We define the class as an Integer and it is autoboxed through method invocation. This is known as Autoboxing because in the following code conversion is taking place automatically.
ArrayList
As we know the size of an array is fixed. So if we wish to have a variable-length data structure so that we can store the elements in an array dynamically we make use of ArrayList. In this tutorial, we will discuss ArrayList.
ArrayList is a part of the collection framework present in java.util package. In java, it provides dynamic arrays. An ArrayList is an object which can be a resizable array. It is an implementation of List interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size.
The ArrayList shown earlier has some disadvantages such as very slow deletion or addition.
ArrayList is a very important data structure useful in handling the dynamic behavior of elements. However, it can be slower than standard arrays, but it can be useful in programs where a lot of manipulation is needed.
Pros
Fast
Easy to access any element from any location
Cons
Operations are slow
Tends to use more memory while operating
Stack
We see the stack data structure here. The properties of a stack data structure are shown here and there some of the operations that include the search, insertion, deletion, and the front element in the stack are shown here.
Java Stack is a LIFO (Last in first out) object. Extends the Vector class but supports only five operations. The Java stack class only has one constructor that is empty or the default constructor. Then, when we create a Stack, initially it does not contain elements that mean that the Stack is empty.
Stack Methods
The useful stack methods that are a push(), pop(), and search() along with empty() methods are shown here. These methods are used to perform basic operations. In this tutorial, users will learn how to define a stack along with the use of all the above-stated methods.
The following program will demonstrate stack methods:
A stack of Integer type is created, the push method is used to push elements in the stack. A foreach loop is used to iterate through all the elements of the stack.
LinkedList
This is one of the most useful data structures and highly used in real-world scenarios because of its high-speed capacity and fast addition and deletion. This basic collection structure is the data in and the address which points to the next node functions as the guide of the respective node (That is the reason for it being called the Linked List). Several methods on this include the addition, deletion of a node anywhere in the list.
The following tutorial deals with the operations regarding the Linked Lists such as add, adding in the specific position, printing, and removing the elements from the specific position in the linked list.
add() method is used to add data in a newly created linked list. But if the linked list is already created then add() will add data at the end of the linked list.
LinkedList operations
In this tutorial, you will learn the basic operations used in LinkedList.
Performing Various Operations on LinkedList
The following tutorial deals with the operations regarding the Linked Lists such as add, adding in the specific position, printing, and removing the elements from the specific position in the linked list.
add() method is used to add data in a newly created linked list. But if the linked list is already created then add() will add data at the end of the linked list.
In the following example, using add(int index, Object item) method, data can be added at the specific position of the linked list. Eg. Canada is added at the second position in the countries list.
In the following example, linked data can be modified using set() method.
Eg. Data is modified at the 7th index position.
In the following example, remove() method is used to remove the data from the specified location.
Eg, remove(4) data will be removed from the 4th index position.
Practically learn all these operations in the following lecture in greater detail.
List interface in Java
The interface is an outline of the methods for a particular class to implement. Here the ArrayList, LinkedList implements the list interface, therefore, you can use the methods that are defined in the List interface as shown here.
In the following example, List <> interface is the input parameter of printList method, which will take input as a different type of lists like ArrayList and LinkedList.
In the following example, we can declare the List object by using List Interface and later initialize with their specific type.
List of countries is declared with List interface and later initialize with type ArrayList.
Sorting and reversal of elements
The sorting and reversal of elements from the Collections are shown in the article by the built-in functions in the collection frameworks.
The following example demonstrates the alphabetical sorting of the List of country names. sort() method will sort the elements (country names) of the LinkedList using natural ordering (alphabetically in ascending order).
Compare To method
This is a very useful method in Java. The compared methods are used to compare TWO OBJECTS and not two primitive datatypes. The output of the compared to the method is explained on the basis of some arguments. If we want to compare two primitive datatypes, we have to use Wrapper Class as studied earlier and convert it to objects.
In the following program compareTo() method compares two Integer objects. This method returns the value 0 if both Integer is equal else it only results in either negative or positive value.
Comparable Interface
The comparable class is shown here. The syntax of the comparable class is unique to the others which include objects and the class. This class can be used for various purposes as shown in the tutorial. The Comparable interface is found in java.lang package and it contains only one method named compareTo(Object).
A comparable Interface is used to sort the custom-type objects. By default, a class defined by the user is not comparable. Hence, their objects cannot be compared. To make an object comparable, the class must implement a comparable interface.
A comparable interface can be used to achieve a single way of sorting like ascending or descending sorting the numerical collection or alphabetical sorting for string object collection.
In the following program, class data implements a Comparable interface. Implement the unimplemented compareTo() method based on the length of the String variable. This method accepts an object of the same instance type and based on certain criteria defined, it returns a negative value if the current value is less than the value we are comparing with, respectively.
Are you ready to elevate your career in IT?
Dive into our Full Stack Java Development course designed for all skill levels. Whether you're a seasoned IT professional looking to expand your skillset or a newcomer eager to explore the world of web development, our comprehensive course is crafted to cater to all levels of expertise.
The course begins with a solid foundation in Java, ensuring a seamless transition for beginners and a perfect refresher for those with existing Java knowledge. Dive deep into Java fundamentals, exploring key concepts such as Lambdas Expression, Java Generics, Collections, Multithreading, and File handling. Our expertly designed curriculum doesn't just stop at the basics; we guide you through the details of debugging in IntelliJ IDEA, ensuring you develop the crucial skill of identifying and fixing errors efficiently.
As you progress, immerse yourself in the dynamic universe of web development with a focus on JSP and Servlets, essential components in building robust Java web applications. Harness the power of Hibernate and Spring framework, both built on the latest Java 17 LTS version, to master the art of seamless data persistence and efficient application development.
Our course places a special emphasis on mastering Spring Boot REST, a vital component in contemporary web development. Explore RESTful APIs and gain a profound understanding of JavaScript basics, which is essential for creating dynamic and interactive web pages. Dive into JSTL and Restful Micro-webservices concepts, covering the legacy part of the course built on Java 8, ensuring you are well-versed in both the latest advancements and established practices.
Take your skills to the next level with in-depth coverage of advanced topics such as HATEOS introduction, Junit, and testing methods, as well as Testing exceptions. Our commitment to providing a holistic learning experience means you'll not only grasp the theoretical aspects but also gain practical insights through real-world projects.
Join our course, and benefit from a curriculum that is carefully curated to align with the demands of the ever-evolving IT landscape. Whether you're aiming for a career transition or seeking to enhance your existing skills, our Full Stack Java Developer course is your gateway to success in the dynamic and high-demand field of web development.
Course Highlights
High-quality video content
Course materials (Project files and quizzes)
Get a FREE 6-month subscription for IntelliJ IDEA Ultimate or another JetBrains IDE of your choice
More than 650+ Lectures and 70+ hours of video content
Latest tools and software versions used
Course built on the latest JAVA 17 LTS version
Legacy concepts (Additional content on Java 8)
What Sets Us Apart?
Extensive Content: With over 650+ lectures and 70+ hours of high-quality video content, our course leaves no stone unturned in equipping you with the knowledge and skills needed to excel as a Full Stack Java Developer.
Latest Tools and Technologies: Stay ahead of the curve with our course built on the latest Java 17 LTS version, coupled with legacy concepts on Java 8. Experience hands-on learning with industry-standard tools like IntelliJ IDEA, Eclipse IDE, and VS Code IDE.
Focus on Modern Technologies: Immerse yourself in the world of modern web development with a special emphasis on React, Spring Boot, Restful Microservices, and JavaScript basics. From setting up React JS to implementing Swagger using React, our course covers it all.
Uncover the top skills taught in our course
Java Programming
Spring Framework
Back-End Development
Front-End Development
Server-Side Architecture
New Addition: Dive into the Exciting World of React
But that's not all!
In response to the growing demand for cutting-edge technologies, we've added a comprehensive section on React. Explore topics such as setting up React JS, user management, making HTTP GET calls, dynamic menus, and much more!
What you’ll learn
Enhance your foundational understanding of Java to seamlessly transition into advanced frameworks such as Spring, Java EE, and JavaScript.
Develop expertise in the latest Java version, Java 17, while also mastering earlier iterations including Java 8.
Elevate your programming skills with comprehensive Java fundamentals for a holistic grasp of key concepts essential for advanced development.
Build a fully functioning web application through a simplistic step from a professional trainer.
Java programming language
Learn Java server pages(JSP), Servlets, and JSTL from the basics to advance
Understand building web forms with JSP
Apply validations on the forms
Use the web template to make the web application incredible
Learn how to Handle Sessions in JSP
Develop Dynamic Web Applications
Learn MVC in JSP
Forms under JSP and Servlets
Learn the concept related to Generics
Add validations on form data
Adding records to the database
Updating record(s) into a database
Deleting record(s) into a database
Spring Framework
Web Services – RestFul API
Spring Boot
Spring Boot Restful API
JavaScript basics
Build frontend using REACT
JUnit
Course Curriculum Content
Build a Strong Foundation in Java
The course begins with a solid foundation in Core Java, ensuring a seamless transition for beginners and a perfect refresher for those with existing Java knowledge. Dive deep into Java fundamentals, exploring key concepts such as Lambdas Expression, Java Generics, Collections, Multithreading, and File handling. Our expertly designed curriculum doesn't just stop at the basics; we guide you through the details of debugging in IntelliJ IDEA, ensuring you develop the crucial skill of identifying and fixing errors efficiently.
Topics have been covered:
Decision-making under Java
Object-oriented programming concepts
Collections framework & debugging
Generics
Multi-threading
Lambdas
File Handling under Java
Explore the World of Web Development
Dive deep into the realm of web development with JSP and Servlets, mastering the art of building resilient Java web applications. Seamlessly integrate Hibernate and Spring frameworks, leveraging the power of Java 17 LTS to achieve unparalleled efficiency in data persistence and application development.
Topics in this section:
Apply validations on the forms
Create & Deploy Java Servlets
Learn how to Handle Sessions in JSP
Develop Dynamic Web Applications
Forms under JSP and Servlets
Adding records to the database
Updating record(s) into a database
Deleting record(s) into a database
Image/File upload
Hibernate for Database Operations
Establish a robust connection between Hibernate and databases.
Dive into Hibernate Query Language (HQL) basics.
Perform CRUD operations seamlessly with Hibernate.
Special Emphasis on Spring Boot REST
Make your applications come alive with Spring Boot, the shining light of modern Java development. Dive into the Spring ecosystem, covering IoC, Dependency Injection, Restful APIs, JWT token generation, and more, with a special focus on Spring Boot for rapid application development. Learn how to use Spring Boot effectively to create strong, flexible web applications that can handle challenges and grow over time.
Topics in this section:
Spring Framework
Inversion of control
Spring Beans
Resource-based URIs for CRUD methods
JSON response
HATEOAS - get links from resources
Idempotence of HTTP Methods
Method parameter and return type
Spring Boot REST API
Spring Boot JWT token generator
Integration of H2 database in Spring Boot
Web template Integration
Update Profile (Account) on the Spring Boot Blog
Adding Spring security into the application
Spring security login, adding rules and Bcrypt password
Web App with spring boot
Sending email for password reset
Email Service in Spring Boot
Docker and WSL on Windows
Spring Boot OAuth2 JWT token generator
Spring Boot OAuth2 JWT Adding Public-private KeyGenerator
Spring boot JWT JPA Auth Controller
Build Add Album API
Elevate Frontend Dynamics with React & JavaScript
But wait, there's more! The crown jewel of our curriculum lies in React
We've supercharged our curriculum with an exclusive focus on React, the powerhouse of frontend development. Elevate your skills with in-depth coverage of REACT, the cutting-edge JavaScript library for building user interfaces.
Begin your journey with JavaScript basics to setting up React JS and mastering Material UI, manage user interactions, make HTTP calls, and implement dynamic functionalities with ease, all within the sleek environment of VS Code IDE. From token handling to Swagger implementation, our REACT section is designed to empower you with the latest tools and techniques for crafting cutting-edge front-end experiences.
Topics in this section:
JavaScript basics
Keywords, datatypes in JavaScript
Normal functions and expression functions in JavaScript
Foreach methods
JavaScript - Dom Object
JavaScript - Callback functions
React
Setting up React JS
Material ui with React
User management with react
Making HTTP GET call with axios
Local server, CORS and Proxy in React
Login functionality
Albums use case in React
Token handling and local storage with react
Dynamic menus and updated registration page
Swagger implementation using React
Upload photos onto the Albums
Props, useEffect and Async
Albums Show page
Add, Edit, Delete functionality
Show Photos using Albums API
Bonus Modules:
Unlock the Secrets of Testing & Deployment
Every journey has its challenges, but with JUnit, your code will be strong enough to overcome any bugs.
Topics in this section:
Fundamentals of the JUnit testing framework
JUnit Testing
Gain proficiency in the JUnit testing framework and explore testing exceptions.
Structure and implementation of effective test methods
Techniques for testing exceptions
And many more!
Micro-Web Services and JSTL
Concluding the curriculum, Discover the legacy concepts of Spring Legacy, Restful Micro-Web Services, JSP & Servlets, and JavaServer Pages Standard Tag Library (JSTL) covering both basic and advanced concepts all developed on Java 8, ensuring you're well-versed in both cutting-edge technologies and established practices.
Key Learning Objectives
Java Fundamentals: Master core Java concepts, including multi-threading, Lambdas, Collections framework, and file handling.
Hibernate: Explore Hibernate, learn to build applications using JSP and Hibernate, and perform CRUD operations.
Spring Framework: Dive into the Spring framework, covering Inversion of Control, Dependency Injection, and more.
Spring Boot: Gain in-depth knowledge of Spring Boot, covering migrations, security integration, Thymeleaf tags, and Restful API implementation.
JavaScript Basics: Understand essential JavaScript concepts, including objects, loops, decision-making, array methods, and asynchronous JavaScript.
React: Setting up React JS, Material ui with React, User management with react, Making HTTP GET call with axios, Local server, CORS and Proxy in React, Login functionality, Albums use case in React, token handling and local storage with react, Dynamic menus and updated registration page, Swagger implementation using React, Upload photos onto the Albums, Props, useEffect and Async, Albums Show page, Add, Edit, Delete functionality, Show Photos using Albums API.
Course Features
Understand the end-to-end process of building web forms with JSP and Servlets.
Acquire a strong foundation in object-oriented programming, covering core concepts, method parameters, return types, arrays, collections, and debugging.
Implement sessions in JSP for efficient web application management.
Apply a wide range of concepts to projects, allowing you to practice and reinforce your new skills.
Why Choose This Course?
Comprehensive Content: Covering essential concepts, tools, functions, and topics required for Java Developers in the web application development process.
Unique Teaching Style: Experience a unique and easy-to-understand teaching approach that caters to various learning styles.
Comprehensive Learning: From theory to practice, from legacy to cutting-edge, our curriculum leaves no stone unturned, ensuring you emerge as a well-rounded, versatile developer.
Hands-On Approach: Learn by doing with a hands-on approach that lets you practice and reinforce your learning.
Career Booster: In today's competitive landscape, mastering Full Stack Java Development isn't just an advantage — it's a necessity. With our course, you'll unlock doors to exciting career opportunities and pave your path to success.
Why Learn Full Stack Java Development?
In today's digital era, where web applications drive businesses, full-stack Java Developers are in high demand. Mastering Full Stack Java Development empowers you to create dynamic and static web content, offering a skill set that is crucial in the ever-evolving IT landscape.
About the Instructor
Our experienced instructor, with over 8 years of teaching IT to 200,000+ students, is also a seasoned web application developer. His unique teaching style ensures that you not only grasp the concepts but also enjoy the learning process.
Enroll Risk-Free
Still hesitating? Rest easy with our No Question Asked - Money Back Guarantee!
If you're not satisfied within the first 30 days, we'll refund your investment — no strings attached. Your journey to mastery begins with a single step — Enroll Today, Transform Tomorrow.
With our easy-to-follow curriculum, you'll be amazed at how quickly you can master Java, Spring Boot REST, and JavaScript. Remember, practice makes perfect, and your efforts will shape your success.
Don't miss the opportunity to propel your career forward and unlock your full potential in the world of IT.
Enroll today and become the architect of tomorrow's web. Your destiny awaits — seize it now!
See you on the course!