JAVA Notes Unit 1 - Print
JAVA Notes Unit 1 - Print
Lecture Notes
OBJECT ORIENTED
Subject Name
PROGRAMMING THROUGH JAVA
The team initiated this project to develop a language for digital devices such as
set-top boxes, television, etc. Originally C++ was considered to be used in the project
but the idea was rejected for several reasons (For instance C++ required more
memory). Gosling endeavoured to alter and expand C++ . James Gosling and his team
called their project “Greentalk” and its file extension was .gt and later became to
known as “OAK”.
Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office.
Also, Oak is an image of solidarity and picked as a national tree of numerous nations
like the U.S.A., France, Germany, Romania, etc. But they had to later rename it as
“JAVA” as it was already a trademark by Oak Technologies.
The name Java originates from a sort of espresso bean. The team came up with this
name while having a coffee near their office. Java was created on the principles
like Robust, Portable, Platform Independent, High Performance, Multithread,
etc. and it is widely used in internet programming, mobile devices, games, e-
business solutions, etc.
2. Java Platform, Enterprise Edition (Java EE) –A platform for developing and
running web and enterprise applications.
3. Java Platform, Micro Edition (Java ME) –A flexible environment for applications
that run on mobile and embedded devices.
4. Java Card - It is the tiniest of Java platforms targeted for embedded devices like
SIM cards, Banking Cards, Identity Cards, Healthcare Cards, Passports and
Several IoT Products.
Java Buzzwords
The primary objective of Java programming language creation was to make it
simple, portable and secure programming language. Apart from this, there are some
excellent features which play an important role in the popularity of this language. The
features of Java are also known as Java Buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Interpreted
4. Platform Independent
5. Architectural Neutral
6. Portable
7. Secured
8. Robust
9. High Performance
10.Multithreaded
11.Dynamic
12.Distributed
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple programming
language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-Oriented
3. Interpreted
4. Platform Independent
The Java platform differs from most other platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
5. Architectural Neutral
6. Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform ie different operating systems and architectures. It doesn't require any
implementation.
Java code is compiled into bytecode that can run on any device with a Java
Virtual Machine (JVM).
The JVM is platform-dependent, meaning that a different JVM is designed for
each operating system.
The bytecode is platform-independent, meaning that it can run on different
operating systems.
This allows developers to write code once and run it on many different
devices.
7. Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No Explicit Pointer
Java Programs run inside a Virtual Machine Sandbox
8. Robust
The Java is robust language ie strong because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
9. High Performance
10.Multithreaded
11.Dynamic
12.Distributed
For executing any Java program, the following software or application must be properly
installed.
Install the JDK if we do not have installed it, download the JDK and install it.
https://www.oracle.com/in/java/technologies/downloads/
Set path of the jdk/bin directory
Create the Java program.
Compile and run the Java program.
Creating Hello World Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Test it Now
Output:
Hello Java
We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
JRE
JRE is an acronym for Java Runtime Environment. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.
JVM
JVMs are available for many hardware and software platforms. JVM, JRE, and
JDK are platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not
required to be set because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the
path of JDK.
1. Temporary
2. Permanent
To set the temporary path of JDK, you need to follow the following steps:
For Example:
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new
tab of user variable -> write path in variable name -> write path of bin folder in
variable value -> ok -> ok -> ok
For Example:
1) Go to MyComputer properties
8) Click on ok button
9) Click on ok button
Now your permanent path is set. You can now execute any program of java from any
drive.
Java Keywords
Java keywords are reserved words with predefined meanings in the Java
programming language. They are part of the syntax and cannot be used as identifiers,
such as variable names, class names, or method names.
List of Java Keywords
1. Arrays:
A collection of similar types of data. For example, int arr[] = new int[5];.
2. Classes:
User-defined data types. For example, String, ArrayList, etc.
3. Interfaces:
Like classes but only contain method signatures.
For example, Comparable, Serializable, etc.
4. String :
In Java, a string is a sequence of characters. It’s a data type used to represent text
rather than numeric data. Strings in Java are immutable, meaning once a string object is
created, its contents cannot be changed.
Example :
// Declare String without using new operator
String s = "Welcome to VJIT !";
// Declare String using new operator
String s1 = new String("Welcome to CSE-Data Science !");
5. Enum:
An enum is a special data type used to define a collection of constants. It allows you
to create a set of named constants that represent a finite set of possibilities, typically
related to some specific type or category. Enums are declared using the enum keyword.
Example :
B.Tech (CSE-DS)-II-II Sem Page 22
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I
enum Day
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
Variables
Types of Variables
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
Output:
Variable: 10
2. Instance Variables
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
import java.io.*;
public class InstanceVariableDemo
{
//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
this.name = "Deepak";
}
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
}
Output:
Student Name is: Deepak
Age: 19
3. Static Variables
A variable that is declared as static is called a static variable also known as class
variables. It cannot be local. You can create a single copy of the static variable and
share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
StaticVariableDemo.java
class Student
{
//static variable
static int age;
}
S1 age is: 23
S2 age is: 23
Operators in Java
Java operators are the symbols that are used to perform various operations on variables
and its values.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Bitwise Operators
7. Comparison Operators
8. Ternary Operator
Operators Operations
+ Addition
- Subtraction
x Multiplication
/ Division
% Modulus
Assignment Operators
Assignment Operators are mainly used to assign the values to the variable in the
program.
= X = Y; X = Y;
+= X += Y; X = X + Y;
-= X -= Y; X = X - Y;
*= X *= Y; X = X * Y;
/= X /= Y; X = X / Y;
%= X %= Y; X = X % Y;
Relational Operators
Relational operators are assigned to check the relationships between two particular
operators.
Unary Operators
Unary Operators in Java are used in only one operand.
Operators Description
+ Unary Plus
- Unary Minus
++ Increment operator
-- Decrement Operator
! Logical complement operator
Bitwise Operators
Bitwise Operators in Java are used to assist the performance of the operations on
individual bits.
Operators Descriptions
~ Bitwise Complement
<< Left shift
>> Right shift
>>> Unsigned Right shift
& Bitwise AND
^ Bitwise exclusive OR
Comparison Operators
To compare two values (or variables), comparison operators are used. A
comparison's return value is either true or false. These are referred to as "Boolean
values."
Operators Operations
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Ternary Operator
The only conditional operator that accepts three operands is the ternary operator in
Java. Java programmers frequently use it as a one-line alternative to the if-else
expression.
Expressions in Java
An expression in Java is a construct that evaluates to a single value. This value
can be a number, a string, an object, or any other data type depending on the components
of the expression. Expressions can include variables, literals, method calls, and
operators.
There are different types of control statements in Java for different conditions. We
can divide control statements in Java into three major types:
1. Conditional Statements
2. Looping Statements
3. Jumping Statements
Conditional Statements
Conditional statements in Java are similar to making a decision in real life, where
we have a situation and based on certain conditions we decide what to do next.
1. if Statement
These are the simplest and yet most widely used control statements in Java.
The if statement is used to decide whether a particular block of code will be executed or
not based on a certain condition.
In the above flow diagram, we can see that whenever the condition is true, we
execute the if block otherwise we skip it and continue the execution with the code
following the if block.
Syntax:
if(condition)
{
// block of code to be executed if the condition is true
}
For example:
Output
10 is less than 15
Outside if-block
2. if-else Statement
The if statement is used to execute a block of code based on a condition. But if the
condition is false and we want to do some other task when the condition is false, how
should we do it?
That's where else statement is used. In this, if the condition is true then the code inside
the if block is executed otherwise the else block is executed.
Let's see the execution flow of the if-else statement in a flow diagram:
The above flow diagram is similar to the if statement, with a difference that whenever
the condition is false, we execute the else block and then continue the normal flow of
execution.
Syntax:
if (condition)
{
// If block executed when the condition is true
}
else
{
// Else block executed when the condition is false
}
Now, if the condition is false, the else block is executed and the if block code is skipped.
This is one example of controlling the flow of a program through control statements in
java.
For example:
int n = 10;
if (n > 5)
{
System.out.println("The number is greater than 5.");
}
else
{
System.out.println("The number is 5 or less.");
}
}
}
Output
The number is greater than 5.
Nested control statements mean an if-else statement inside other if or else blocks. It is
similar to an if-else statement but they are defined inside another if-else statement.
Let us see the syntax of a specific type of nested control statements where an if-
else statement is nested inside another if block.
Syntax:
if (condition)
{
// If block code to be executed if condition is true
if (nested condition)
{
// If block code to be executed if nested condition is true
}
else
{
// Else block code to be executed if nested condition is false
}
}
else
{
// Else block code to be executed if condition is false
}
Explanation:
Here, we have specified another if-else block inside the first if block. In the syntax, you
can see the series of the blocks executed according to the evaluation
of condition and nested condition.
Using this, we can nest the control flow statements in Java to evaluate multiple related
conditions.
Let's see the execution flow of the above-mentioned nested-if-else statement in a flow
diagram:
Example:
Let’s say that we want to know which floor of the mall a person needs to go to do
shopping based on the age and gender of the person. Let’s see the implementation of this
example through nested-if:
Output:
4. if-else-if Ladder
In this, the if statement is followed by multiple else-if blocks. We can create a decision
tree by using these control statements in Java in which the block where the condition is
true is executed and the rest of the ladder is ignored and not executed.
If none of the conditions is true, the last else block is executed, if present.
Let's see the execution flow of the if-else ladder in a flow diagram:
As you can see in the above flow diagram of the if-else ladder, we execute the if block if
the condition is true, otherwise if the condition is false, instead of executing the else
block, we check other multiple conditions to determine which block of code to execute.
If none of the conditions are true, the last else block, if present, is executed.
The syntax and execution flow of the if-else-if ladder statement is as follows:
Syntax:
if(condition1)
{
// Executed only when the condition1 is true
}
else if(condition2)
{
// Executed only when the condition2 is true
}
.
.
else
{
// Executed when all the conditions mentioned above are true
}
Example:
Let’s say that we have a browser-specific code, where we want to execute a code
depending upon the browser the user is using. Let’s try to implement this in the code:
Output:
Explanation:
As you can see, the first two conditions are not true. Hence, the first two blocks are not
executed. The third condition is true and hence the third block of code is executed giving
the output: The browser is chrome. Following this block, all other blocks (the
last else block) are ignored.
Here we can write the browser-specific implementation in the equivalent block, and if
none of the supported browsers are encountered then we can also give an error in the
last else block.
5. switch Statement
Switch statements are almost similar to the if-else-if ladder control statements in Java. It
is a multi-branch statement. It is a bit easier than the if-else-if ladder and also more user-
friendly and readable.
The switch statements have an expression and based on the output of the expression, one
or more blocks of codes are executed.
These blocks are called cases. We may also provide a default block of code that can be
executed when none of the cases are matched similar to the else block.
Syntax:
switch (expression)
{
case value1:
//code block of case with value1
break;
case value2:
//code block of case with value2
break;
.
.
case valueN:
//code block of case with valueN
break;
default:
//code block of default value
}
There are certain points that one needs to be remembered while using switch statements:
The expression can be of type String, short, byte, int, char, or an enumeration.
We cannot have any duplicate case values.
The default statement is optional.
Usually, the break statement is used inside the switch to terminate a statement
sequence.
The break statement is optional. If we do not provide a break statement, the
following blocks will be executed irrespective of the case value. This is known as
the trailing case.
Let's see the execution flow of the switch statement in a flow diagram:
In the above flow diagram, we have a switch expression and we match the output of the
expression through a series of case blocks.
Whichever case matches the output, its block is executed and execution skips to the end
of the switch; otherwise, if none of the cases matches, the default block is executed.
B.Tech (CSE-DS)-II-II Sem Page 40
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I
Here, we have multiple case statements and each case code block is followed by a break
statement to stop the execution to that case only.
Example:
If we take the previous example, we can easily implement that using switch statements:
Output:
In this example, the case with the value “chrome” is matched and hence its block is
executed. If we do not give a break statement in this block, the trailing blocks(default
block in this example) will also be executed.
Also, it's worthwhile to notice that the switch statement made the code more readable
and cleaner.
Code:
Output:
We can see that the default block is also executed. It is due to the following reason:
Once a case value is matched, all the following blocks of code are executed until
a break statement or the end of the switch statement is encountered.
This is not the expected behavior and hence we should use the break statement. We’ll
learn more about the break statement in the next sections.
Looping Statements
Java provides a set of looping statements that executes a block of code
repeatedly while some condition evaluates to true. Looping control statements in Java
are used to traverse a collection of elements, like arrays.
1. while Loop
The while loop statement is the simplest kind of loop statement. It is used to iterate over
a single statement or a block of statements until the specified boolean condition is false.
The while loop statement is also called the entry-control looping statement because the
condition is checked prior to the execution of the statement and as soon as the boolean
condition becomes false, the loop automatically stops.
You can use a while loop statement if the number of iterations is not fixed.
Normally the while loop statement contains an update section where the variables, which
are involved in while loop condition, are updated.
Let's see the execution flow of the while loop statement in a flow diagram:
We initialize a loop counter variable. After that, we check the loop condition and
if it's true, then the body of the loop is executed followed by the update of the
counter variable.
The control then again switches back to the loop condition and the cycle continues
till the condition is false and we execute the statements outside the loop body.
The syntax and execution flow of the while loop statement is as follows:
Syntax:
while (condition)
{
// code block to be executed
}
Example:
Let's say we want to print the numbers from 10 to 1 in decreasing order. Let's implement
this through a while loop.
// Update Section
num--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
1
Here, we have used the loop condition as num > 0 and then at each iteration of the loop,
we have decreased the value of the num variable by 1.
So the loop runs till the value of num becomes 1 from 10, and we get the desired output.
2. do-while Loop
The Java do-while loop statement works the same as the while loop statement with the
only difference being that its boolean condition is evaluated post first execution of the
body of the loop. Thus it is also called exit controlled looping statement.
You can use a do-while loop if the number of iterations is not fixed and the body of the
loop has to be executed at least once.
Let's see the execution flow of the do-while loop statement in a flow diagram:
We also initialize a counter variable, but instead of checking the loop condition at
the start, the body of the loop is executed.
After the completion of the loop body, we check the loop condition and continue
to execute the loop body till the condition is false when we come out of the loop
and execute the rest of the code.
The syntax and execution flow of the do-while loop statement is as follows:
Syntax:
do
{
// code block to be executed
} while (condition);
Example:
Let's try to use the same example of printing the number in decreasing order through a
do-while loop:
10
9
8
7
6
5
4
3
2
1
The implementation and output are almost similar, with the change that, even if the
value of the num initially is less than 1. We'll get at least one print statement with the
value of the num as the output.
3. for Loop
Unlike the while loop control statements in Java, a for loop statement consists of
the initialization of a variable, a condition, and an increment/decrement value, all in one
line. It executes the body of the loop until the condition is false.
The for loop statement is shorter and provides an easy way to debug structure in
Java. You can use the for loop statement if the number of iterations is known.
In a for loop statement, execution begins with the initialization of the looping
variable, then it executes the condition, and then it increments or decrements the looping
variable.
If the condition results in true then the loop body is executed otherwise the for
loop statement is terminated.
Let's see the execution flow of the for loop statement in a flow diagram:
As you can see in the above flow diagram, we have a for loop statement. In this
statement, the loop condition is checked, and if the condition is true, the for loop body is
executed until the condition is false and we continue with the normal flow of execution.
Syntax:
Example:
Output:
4. for-each Loop
general-purpose loop that we can use for any use case, the for-each loop can only be
used with collections or arrays.
In for-each loop statement, you cannot skip any element of the given array or collection.
Also, you cannot traverse the elements in reverse order using the for-each loop control
statement in Java.
Let's see the execution flow of the for-each loop statement in a flow diagram:
We check if the collection has any elements or not. If it has the elements, then the
first element is assigned to the local variable mentioned in the for each expression,
and the for each loop body is executed.
After this, we again check if the collection has any remaining elements and this
cycle continues till we have traversed all the elements.
The syntax and execution flow of for each loop statement is as follows:
Syntax:
Example:
Output:
Jump/Branching Statements
Jump/Branching control statements in Java transfer the control of the program to other
blocks or parts of the program and hence are known as the branch or jump statements.
1. Break Statement
The break statement as we can deduce from the name is used to break the current flow of
the program. The break statement is commonly used in the following three situations:
The break statement cannot be used as a standalone statement in Java. It must be either
inside a switch or a loop. If we try to use it outside a loop or a switch, JVM will give an
error.
Let's see the execution flow of the break statement in a flow diagram:
In the above flow diagram of a break statement, whenever the loop body encounters a
break statement, it stops the current flow of execution and jumps to the first statement
out of the loop body.
Syntax:
We have already seen how we use the break inside a switch. Let’s see the syntax in the
case of a loop:
for(condition)
{
// body of the loop
break;
}
while(condition)
{
// body of the loop
break;
}
Example 1:
Output:
As we can see the loop was terminated even when the condition of the loop was still
true. This is how we can use the break statement in a loop.
Example 2:
In case, we have nested loops, the break statement will only break the execution of the
loop its part of. For example:
if (inner_index == 3)
{
break;
}
}
Output:
2. Continue Statement
Sometimes there are situations where we just want to ignore the rest of the code in the
loop body and continue from the next iteration. The continue statement in Java allows us
to do just that. This is similar to the break statement in the sense that it bypasses every
line in the loop body after itself, but instead of exiting the loop, it goes to the next
iteration.
Let's see the execution flow of the continue statement in a flow diagram:
In the above flow diagram of a continue statement, whenever the continue statement has
encountered the rest of the loop body is skipped and the next iteration is executed if the
loop condition is true.
Syntax:
for(condition)
{
// body of the loop
continue;
//the statements after this won't be executed
}
while(condition)
{
// body of the loop
continue;
// the statements after this won't be executed
}
Example:
Let’s try to print the odd number between 1 to 10 as we did in the example of the for
loop, but this time we’ll use the continue statement:
System.out.println("The odd numbers between 1 to 10 are: ");
for (int number = 1; number <= 10; number++)
{
if (number % 2 == 0) continue;
System.out.println(number);
}
Output:
The odd numbers between 1 to 10 are:
1
3
5
7
9
3. Return Statement
The return statements are used when we need to return from a method explicitly. The
return statement transfers the control back to the caller method of the current method. In
the case of the main method, the execution is completed and the program is terminated.
Return statements are often used for conditional termination of a method or to return
something from the method to the caller method.
Let's see the execution flow of the return statement in a flow diagram:
As you can see in the above flow diagram, whenever a return statement is encountered
anywhere in a method, the execution of the current method is stopped and the flow of
the program returns to the caller method of the current method.
The syntax and execution flow of the return statement is as follows:
Syntax:
void method()
{
// body of the method
return;
}
Example:
Let’s say we are searching an element in a list, and as soon as we find it, our work is
done and we should exit the function. Let’s see the implementation of this problem:
public class ReturnStatementDemo
{
public static String search(int key)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int element : numbers)
{
if (element == key)
{
return "Success";
// Putting statements post this return statement
// Will throw compile-time error
}
}
return "Failure";
}
public static void main(String[] args)
{
System.out.println(search(3));
System.out.println(search(10));
}
}
Output:
Success
Failure
As we can search that the value 3 was in the array and we get the output as “Success”,
but since value 10 does not exist in the array, we get the “Failure” as the output.
Rules of Typecasting
Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down. It is done automatically. It is safe
because there is no chance to lose data. It takes place when:
WideningExample.java
Converting a higher data type into a lower one is called narrowing type casting. It
is also known as explicit conversion or casting up. It is done manually by the
programmer. If we do not perform casting, then the compiler reports a compile-time
error.
double -> float -> long -> int -> char -> short -> byte
NarrowingExample.java
Arrays in Java
An array is a collection of similar types of data.
1. Array Declaration
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
2. Create an Array
To create an array, you need to allocate memory for it using the new keyword:
We can access array elements using their index, which starts from 0:
The first line sets the value of the first element to 10. The second line retrieves the value
of the first element.
arrayRefVar=new datatype[size];
2. Two-Dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-
upper corner to 1,4 in the right lower corner.
Output:
268
486
469
This line uses the keyword class to declare that a new class is being defined.
class HelloWorld
{
//
//Statements
}
2. HelloWorld
It is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace ” { ” and the
closing curly brace ” } “.
3. main Method
In the Java programming language, every application must contain a main
method. The main function(method) is the entry point of your Java application, and it’s
mandatory in a Java program. whose signature in Java is:
public static void main(String[] args)
Explanation of the above syntax
public : So that JVM can execute the method from anywhere.
static : The main method is to be called without an object. The modifiers are public
and static can be written in either order.
void : The main method doesn’t return anything.
main() : Name configured in the JVM. The main method must be inside the class
definition. The compiler executes the codes starting always from the main method.
String[] : The main method accepts a single argument, i.e., an array of elements of
type String.
Like in C/C++, the main method is the entry point for your application and will
subsequently invoke all the other methods required by your program.
The next line of code is shown here. Notice that it occurs inside the main() method.
System.out.println("Hello, World");
This line outputs the string “Hello, World” followed by a new line on the screen.
Output is accomplished by the built-in println( ) method. The System is a predefined
class that provides access to the system and out is the variable of type output stream
connected to the console.
Comments
They can either be multiline or single-line comments.
// This is a simple Java program.
// Call this file "HelloWorld.java".
This is a single-line comment. This type of comment must begin with // as in
C/C++. For multiline comments, they must begin from /* and end with */.
Important Points
The name of the class defined by the program is HelloWorld, which is the same as
the name of the file(HelloWorld.java). This is not a coincidence. In Java, all codes
must reside inside a class, and there is at most one public class which contains the
main() method.
By convention, the name of the main class(a class that contains the main method)
should match the name of the file that holds the program.
Every Java program must have a class definition that matches the filename (class
name and file name should be same).
Compiling the Program
After successfully setting up the environment, we can open a terminal in Windows
and go to the directory where the file – HelloWorld.java is present.
Now, to compile the HelloWorld program, execute the compiler – javac, to specify
the name of the source file on the command line, as shown:
javac HelloWorld.java
The compiler creates a HelloWorld.class (in the current working directory) that
contains the bytecode version of the program.
Execute the Program
Now, to execute our program, JVM (Java Virtual Machine) needs to be called using
Java tool, specifying the name of the class file on the command line, as shown:
java HelloWorld
This will print “Hello World” to the terminal screen.
Object-Oriented Paradigm
The object-oriented paradigm in Java is a programming model that uses objects
to represent and manipulate data. It's a widely used approach in software development.
Object
Class
Encapsulation
Abstraction
Inheritance
Polymorphism
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}
}
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.println("Student Details: ");
System.out.println(this.name+ ", " + this.rollNo + ", " + section);
}
}
}
Abstraction: Showing the Essential Features and hiding their implementation details
The real-world example of an abstraction is a Car, the internal details such as the
engine, process of starting a car, process of shifting gears, etc. are hidden from the
user, and features such as the start button, gears, display, break, etc are given to the
user. When we perform any action on these features, the internal process works.
Subclass: The class that inherits the other class is known as subclass (also known
as derived or extended or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
Polymorphism
1. Method Overloading
2. Method Overriding
// Child Class
class Child extends Parent
{
// Method Overriding
public void m1(int a)
{
System.out.println("Child Method m1 with parameter: " + a);
}
}
// Main Method
class Poly
{
public static void main(String args[])
{
Parent p = new Parent();
p.m1();
p.m1(5);
Child c = new Child();
c.m1(4);
}
}
Applications of OOPs
Java is one of the most prominent programming languages that fully embrace the
OOP paradigm. The application of OOP in Java is extensive, spanning various types of
software, including desktop applications, web applications, enterprise software, mobile
apps, and games. Java's rich set of libraries, frameworks, and tools are built on OOP
principles, making it an ideal choice for developing scalable and maintainable
applications.
Java Constructors
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is syntactically
similar to a method. However, constructors have no explicit return type.
All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member variables to
zero. However, once you define your constructor, the default constructor is no longer
used.
Rules for Creating Java Constructors
You must follow the below-given rules while creating Java constructors:
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void as a return
type.
There can be multiple constructors in the same class, this concept is known as
constructor overloading.
The access modifiers can be used with the constructors, use if you want to
change the visibility/accessibility of constructors.
Java provides a default constructor that is invoked during the time of object
creation. If you create any type of constructor, the default constructor (provided
by Java) is not invoked.
Creating a Java Constructor
To create a constructor in Java, simply write the constructor's name (that is the
same as the class name) followed by the brackets and then write the constructor's body
inside the curly braces ({}).
Syntax
class ClassName
{
ClassName()
{
Statements;
}
}
There are three different types of constructors in Java, we have listed them as follows:
1. Default Constructor
2. No-Args Constructor
3. Parameterized Constructor
1. Default Constructor
If you do not create any constructor in the class, Java provides a default
constructor that initializes the object.
As the name specifies, the No-argument constructor does not accept any
arguments. By using the No-Args constructor you can initialize the class data members
and perform various activities that you want on object creation.
3. Parameterized Constructor
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a method,
just declare them inside the parentheses after the constructor's name.
Constructor overloading means multiple constructors are defined with the same
signature with different parameter list in a class. When you have multiple constructors
with different parameters listed, then it will be known as constructor overloading.
// Printing details
System.out.println("------------");
System.out.println("std1 Details");
st1.printDetails();
System.out.println("------------");
System.out.println("std2 Details");
st2.printDetails();
System.out.println("------------");
System.out.println("std3 Details");
st3.printDetails();
}
}
Java Methods
Java Methods are blocks of code that perform a specific task. A method
allows us to reuse code, improving both efficiency and organization. All methods in
Java must belong to a class. Methods are similar to functions and expose the
behavior of objects.
Syntax
AccessModifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
For using a method, it should be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
Output
class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj.a, obj.b);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}
Although values of x and y are interchanged, those changes are not reflected
on a and b. Memory representation of variables is shown in below figure:
class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}
The changes performed inside the method swap are reflected on a and b as we
have passed the reference obj into ref which also points to the same memory locations
as obj. Memory representation of variables is shown in below figure:
Note: In Java, parameters of primitive types are passed by value which is same as pass-
by-value and parameters of reference types are also passed by value (the reference is
copied) which is same as pass-by-reference. So, in Java all parameters are passed by
value only.
Access Control in Java refers to the mechanism used to restrict or allow access
to certain parts of a Java program, such as classes, methods, and variables. Java’s
access control mechanism promotes code encapsulation, and information hiding, and
reduces the likelihood of errors and security vulnerabilities in the program. It is
implemented by using access control modifiers, which are keywords placed before the
declaration of the class member.
1. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
2. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
outside
Access within outside
within class package by
Modifier package package
subclass only
Public Y Y Y Y
Private Y N N N
Protected Y Y Y N
Default Y Y N N
this Keyword
In Java, ‘this’ is a reference variable that refers to the current class object. It can
be used to call current class methods and fields, to pass an instance of the current class
as a parameter, and to differentiate between the local and instance variables. Using
“this” reference can improve code readability and reduce naming conflicts.
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + obj.a+ " b = " + obj.b);
}
static Keyword
The static keyword in Java is used for memory management. The static
keyword belongs to the class rather than an instance of the class.
1. Belongs to the class: When a member is declared as static, it is associated with the
class rather than with instances of the class.
2. Accessed without creating an instance: Since static members are associated with the
class itself, they can be accessed using the class name, without needing to create an
instance of the class. For example, ClassName.staticMethod().
3. Shared among all instances: Since there is only one copy of a static member per
class, it is shared among all instances of the class. This can be useful for maintaining
common data or behavior across all instances.
4. Can access other static members directly: static members can directly access
other static members of the same class, but they cannot directly access non-static
(instance) members. This is because static members exist independently of any
particular instance.
5. Initialization: static variables are initialized only once, at the start of the execution,
before the initialization of any instance variables. They are initialized in the order
they are declared.
6. Used for utility methods and constants: static methods are commonly used for
utility methods that perform a task related to the class, but do not require any
instance-specific data. static variables are often used for constants that are shared
among all instances of the class.
Static variables
When a variable is declared as static, then a single copy of the variable is created
and shared among all objects at the class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables:
We can create static variables at the class level only.
static block and static variables are executed in the order they are present in a
program.
Static methods
When a method is declared with the static keyword, it is known as the static
method. The most common example of a static method is the main( ) method. As
discussed above, any static member can be accessed before any objects of its class are
created, and without reference to any object. Methods declared as static have several
restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Static blocks
If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
public class StaticEx
{
public static int count = 0;
public int id;
// static block
static
{
System.out.println("Inside static block");
}
public StaticEx()
{
count++;
id = count;
}
Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-
level class with a static modifier but can declare nested classes as static. Such types of
classes are called Nested static classes. Nested static class doesn’t need a reference of
Outer class. In this case, a static class cannot access non-static members of the Outer
class.
// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the
class in which it is nested. But the enclosing class does not have access to the
member of the nested class.
1. static nested class: Nested classes that are declared static are called static
nested classes.
Syntax:
class OuterClass
...
class NestedClass
...
// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Syntax:
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
System.out.println("outer_private = "+ outer_private);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. A
method that calls itself is called a recursive method. A few Java recursion examples
are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.
The garbage collector automatically finds and removes objects that are no
longer needed, freeing up memory in the heap. It runs in the background as a daemon
thread, helping to manage memory efficiently without requiring the programmer’s
constant attention.
Strings
A String in Java is a sequence of characters that can be used to store and
manipulate text data and it is basically an array of characters that are stored in a
sequence of memory locations.
All the strings in Java are immutable in nature, i.e. once the string is created we
can’t change it.
1. String s="VJIT";
2. char[] ch={'H','y','d','e','r','a','b','a','d'};
String s=new String(ch);
1. By String literal
2. By new keyword
1) String Literal
String s="welcome";
2) By new keyword
class Strings
{
public static void main(String[] args)
{
// create a string
String s = "Hello! World";
System.out.println("String: " + s);
//substring
String st = "Hello, World!";
System.out.println(st.substring(7, 12));
// create 3 strings
String s1 = "java programming";
String s2 = "java programming";
String s3 = "python programming";
//Replace
String st1 = "Hello";
System.out.println(st1.replace('l', 'p'));
String txt = "Hello World";
//trim
String str = " Java World! ";
System.out.println(str);
System.out.println(str.trim());
}
}
Object class
Object class is the base class for all classes in Java. The Object class resides
within the java.lang package. It serves as a foundation for all classes, directly or
indirectly. If a class doesn't extend any other class, it's a direct child of Object; if it
extends another class, it's indirectly derived. Consequently, all Java classes inherit the
methods of the Object class.
import java.util.*;
ObjEx(int stno)
{
this.stno=stno;
}