Oops 1
Oops 1
Application of java
→ Desktop Applications
→ Web Applications
→ Mobile
→ Enterprise Applications
→ Smart Card
→ Embedded System
→ Games
→ Robotics etc
Features of Java
1. Simple
→ Java is very easy to learn and its syntax is simple, clean and easy to understand.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
2. Object-oriented
→ Java is object-oriented programming language
3. Platform Independent
→ Java is platform independent because it is different from other languages like C, C++ etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language.
4. Secured
→ Java is best known for its security. With Java, we can develop virus-free systems.
5. Robust
→ Robust simply means strong.
6. Architecture-neutral
→ Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
7. Portable J
→ Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.
8. High-performance
→ Java is faster than other traditional interpreted programming languages because Java bytecode is
"close” to native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an
interpreted language that is why it is slower than compiled languages e.g. C, C++ etc.
Unit-1 Page 1
9. Distributed
→ Java is distributed because it facilitates users to create distributed applications in java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
10. Multi-threaded
→ A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-
media, Web applications etc.
11. Dynamic
→ Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages i.e. C and C++. Java supports dynamic
compilation and automatic memory management (garbage collection).
History of Java
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team at Sun Microsystem.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk™ by James Gosling, and the file extension was .gt. After that, it was
called Oak and was developed as a part of the Green project.
4) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
5) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
6) Java is an island in Indonesia where the first coffee was produced (called Java coffee). Java name
was chosen by James Gosling while having a cup of coffee nearby his office.
7) Initially developed by James Gosling at Microsystems Sun (which is now a subsidiary of Oracle
Corporation) and released in 1995.
8) JDK 1.0 was released on January 23, 1996.
After the first release of Java, there have been many additional features added to the language.
Now Java is being used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.
Platform independent - You write code once, and the VM runs it on different platforms like window, mac or
Linux.
Safety first - The JVM checks for error before running code, preventing crash. When_you run a Java
program, you are actually saying, hey, VM, work your magic.
# operations
Unit-1 Page 2
JRE(Java Runtime Environment)
→ JRE contain the JVM and set of libraries and some other files.
→ So its work like JVM
Memory Management - It handles memory, garbage collection, and keeps things neat.
Speedy Execution - The JRE improves code for well-organized execution.
Platform independent - You write code once, and the JVM runs it on different platforms like window, mac or
Linux.
Safety first - the JVM checks for error before running code, preventing crash.
Java environment
→ Java environment includes large number of development tools The development tools are part of the
system known as Java development kit ( JDK).
→ It is a software development environment which is used to develop and run Java programs.
→ It is a collection of tools.
→ That are used for developing.
→ It is physically exist.
→ And it contain JVM and JRE
JDK includes:-
→ It is used to describe that the Java scores code file Must follow a structure., Java program Contain
exactly one public class.
→ The name of public class and name of program must match
Unit-1 Page 3
Structure of Java Program
1. Package Statements:
→ Package statement is like an address on a letter. And it is the first line in the source file. It tells to Java
program that where to find the classes and interfaces that are used in the code
→ Example: package com.example.myapp;
2. Import Statements:
→ It is like a shortcut that allow you to use Classes and methods form other libraries without having to
write their full names every time.
→ It is used to import classes, interfaces, or packages from other sources and allows you to use their
functionality in your code.
→ Example: import java.util.ArrayList;
3. Class Definition:
A class is a blueprint for creating objects.
It Contains variables and functions.
When we write a class definition in java, we are creating a detailed plan for how objects Will look and
function.
Example: public class MyClass
// variables and functions go here
1. Install JDK - Before you run the java program you need to install JDK on your computer.
Unit-1 Page 4
A first Java Program
Public Keyword: It makes classes, attributes(variables), methods, available from anywhere in the program.
Static Keyword: It is a special tag that you can put on a variable and method to say "this belong to the class
itself, not to specific object."
Void: It is the return type of method. It means it does not return any value.
String[] args: It is used for command line argument. It contains the value provided by the user when running
the program.
Compilation
A program is written in JAVA, the javac compiles it. The result of the JAVA compiler is the .class file or the
bytecode and not the machine native code (unlike C compiler).
The bytecode generated is a non-executable code and needs an interpreter to execute on a machine. This
interpreter is the JVM and thus the Bytecode is executed by the JVM. And finally program runs to give the
desired output.
Fundamentals of Java
Data Types: Tells you what kind of stuff you can put in the boxes like numbers or letters.
Control Statements: Rules that tell the computer what to do next, like choosing which path to take.
Unit-1 Page 5
Methods: Sets of instructions that you can use over and over, like a recipe.
Classes: Blueprints for making objects that group data and methods together.
Objects: Things you create using classes that can do all sorts of tasks.
Types of Class
1. Predefined Classes: These are the classes that come with Java itself. They're part of Java’s libraries
and you can use them directly in your program. Examples include String, Math, and Array List.
2. User-Defined Classes: These are the classes user create by themselves. User write the code to define
what the class does and what kind of data it holds. Example: If you are making a game, you might
create a Player class with fields for the player's name, score and level.
Unit-1 Page 6
Constructors
In Java programming, a constructor is like a special method that helps create an object from a class. It's
called automatically when you use the new keyword to make a new object.
a) Initial Setup: It sets up the new object with initial values and states.
b) Automatic Call: It’s called automatically when you create an object.
c) No Return Type: It doesn’t return anything, not even void.
d) Same Name as Class: It has the same name as the class it’s in.
For example, if you have a class Bike, the constructor Bike() will set up a new bike object when you do
something like new Bike(). Here’s a simple code example:
class Bike {
int_speed;
// This is the constructor for the Bike class.
Bike() {
speed = 0;
// Setting the initial speed of the bike
}
}
public class TestBike {
public_static void main(String[] args) {
// Creating a new Bike object.
Bike myBike = new Bike();
System.out.println('Bike speed: " + myBike.speed);
}
}
In this code, Bike() is the constructor that sets the initial speed of the Bike object to 0. When we create a new
Bike with new Bike() the constructor is called, and the bike’s speed is set.
Types Of Constructor
1. Default Constructor: This is the constructor that doesn’t need any extra information. If you don’t write a
constructor for your class, Java automatically gives you this one. It's like getting a basic model of a car
with no extra options.
2. Parameterized Constructor: This constructor takes some information to work, like specific features you
want. It’s like ordering a car with your choice of color and engine type.
a) Same Name: The constructor's name must be exactly the same as the class name
b) No Return Type: Constructors don’t have a return type, not even void.
c) Access Levels: You can use access modifiers like public, private, etc., to _control who can use the
constructor.
d) No Static: Constructors can’t be static. They are part of the object, not the class itself.
e) Overloading Allowed: You can have more than one constructor in a class as long as each has a different
set of parameters (this is called overloading).
Method
→ In Java programming, a method is a block of code that performs a specific task. It’s like a mini-program
within a program that you can run over and over. To create a method, you follow these steps:
1. Name Your Method: Choose a name that describes what the method does
2. Write Parameters: Decide what information, if any, the method needs to do its job.
3. Specify a Return Type: Determine what type of result the method will give back after it runs.
4. Add a Method Body: Write the code that will run each time the method is called.
Unit-1 Page 7
Syntax: Example:
Access Modifier: This controls who can use the method. Common modifiers are public, private, or protected.
Return Type: This is the type of data the method will return. If it doesn’t return anything, use void
Method Name: This is the name you give your method.
Parameter Type: This is the type of data you're passing into the method.
Parameter Name: This is the name of the data you’re using inside the method. method body: This is where
you write the code that the method will execute.
Access Modifiers
Access modifiers in Java are like rules that tell who can use certain parts of your code. They're like the
privacy settings on your social media profile.
Unit-1 Page 8
Static Members and Final Members
In Java, static members are those which belongs to the class and you can access these members without
instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class.
It is used to restrict a user in Java.
The following are different contexts where the final is used:
1. Variable
2. Method
3. Class
Comments
→ The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
→ Comments are used to make the program more readable by adding the details of the code.
→ It makes easy to maintain the code and to find the errors easily.
→ The comments can be used to provide information or explanation about the variable, method, class, or
any statement.
→ It can also be used to prevent the execution of program code while testing the alternative code.
Unit-1 Page 9
Data Types
→ Data types specify the different sizes and values that can be stored in the variable.
→ There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Variables
In Java, Variables are the data containers that save the data values during Java m program execution. Every
Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable
is a memory location name for HRR Sy the data.
Java variable is a name given to a memory location. It is the basic unit of storage in a program.
Unit-1 Page 10
Operators
→ Operators in Java are the symbols used for performing specific operations in Java. Operators make
tasks like addition, multiplication, etc which look easy although the implementation of these tasks is
quite complex.
Types of Operators
1. Unary Operators: Unary operators need only one operand. They are used to increment, decrement, or
Logical not operator (!) negate a value.
○ Unary minus (-): It used to convert into a negative number
○ Unary plus (+): Tt used to convert into a positive number
○ Logical not operator (!)
○ Increment operator (++): It increments the value by 1.
○ Decrement operator (-): It decrements the value by 1.
2. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types.
Output:
Unit-1 Page 11
4. Relational Operators: For comparing two 5. Logical Operators: For Combining Conditions
values
9. Instance of Operator: The instance of the operator is used for type checking. It can be used to test if
an object is an instance of a class, a subclass, or an interface.
Control Flow
→ Control flow in Java refers to the order in which the statements instructions, or function calls of a
program are executed or evaluated.
→ In simple terms, it's like the path your code follows based on certain conditions or loops you have set up.
Java provides various control flow statements that allow you to dictate how your program should run
under different conditions.
Decision-Making Statements:
1) If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a Boolean
value, either true or false.
Unit-1 Page 12
1) Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax:
Output:
2) If-else Statement: The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
3) If-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements that create a decision
tree where the program may enter in the block of code where the condition is true. We can also define
an else statement at the end of the chain.
4) Nested if-statement: In nested if-statements, the if statement can contain a if or if-else statement
inside another if or else-if statement.
Unit-1 Page 13
Switch Statements
→ In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of
the program.
○ The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
○ Cases cannot be duplicate
○ Default statement is executed when any of the case doesn't match the value of expression. It is optional.
○ Break statement terminates the switch block when the condition is satisfied. It is optional, if not used,
next case is executed. o While using switch statements, we must notice that the case expression will be
of the same type as the variable. However, it will also be a constant value.
OUTPUT:- 2
Loop Statements
→ In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
→ In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
1. Java for loop : In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.
Unit-1 Page 14
2. While Loop: The while loop is also used to iterate over the number of
statements multiple times. However, if we don't know the number of
iterations in advance, it is recommended to use a while loop. Unlike
for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.
3. do-while loop: The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least once,
we can use do-while loop. It is also known as the exit-controlled loop since the condition is not
checked in advance.
Jump Statements
→ Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e, break and continue.
→ As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
→ However, it breaks only the inner loop in the case of the nested loop.
→ The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
→ Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately
Unit-1 Page 15
Array
Types of Array:-
}} for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Java String
→ In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
→ The java.lang.String class is used to create a string object.
→ For example:
→ Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Unit-1 Page 16
→ There are two ways to create String object:
1. By string literal
2. By new Keyword
String Operations
1. equals(): System.out.println(s1.equals(s2));//true
2. compare by ==:
System.out.println(s1==s2);//true
3. compareTo():
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
System.out.println(s1.compareTo(s2));//0
4. Concat:
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
5. Split():
String[] words=s1.split(“ ");//splits the string based on whitespace
6. Ends with():
System.out.println(s1.endsWith("t"));
7. Substring() method
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
8. Join()
String joinString1=String.join("-","welcome","to","javatpoint");
System.out.println(joinString1);
}}
welcome-to-javatpoint
Unit-1 Page 17
Object Oriented Programming
Class
Java Classes:
Object In Java
An entity that has state and behavior is known as an object e.qg., chair, bike, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is
the banking system
Object Definitions:
Inheritance
→ Java, Inheritance is an important pillar of OOP. It is the mechanism in Java by which one class is
allowed to inherit the features(fields and methods) of another class.
→ In Java, Inheritance means creating new classes based on existing ones.
→ A class that inherits from another class can reuse the methods and fields of that class.
→ In addition, you can add new fields and methods to your current class as well.
○ Code Reusability Super Class/Parent Class: The class whose features are
○ Method Overriding inherited is known as a superclass(or a base class or a parent
○ Abstraction class).
Sub Class/Child Class: The class that inherits the other class
is known as a subclass(or a derived class, extended class, or
child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
Unit-1 Page 18
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are derived
from an existing class. In other words, “extends” refers to increased functionality.
Syntax:
→ On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
→ In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
1. Single Inheritance
→ In single inheritance, subclasses inherit the features of
one superclass. In the image below, class A serves as a
base class for the derived class B.
2. Multilevel Inheritance
→ In Multilevel Inheritance, a derived class will be inheriting
a base class, and as well as the derived class also acts as
the base class for other classes.
3. Hierarchical Inheritance
→ In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one subclass. In the below image,
class A serves as a base class for the derived classes B, C,
and D.
5. Hybrid Inheritance
→ It is a mix of two or more of the above types of inheritance. Since
Java doesn’t support multiple inheritances with classes, hybrid
inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only
through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
Unit-1 Page 19
Overloading and Overriding
Overloading: Overloading occurs when two or more methods in the same class have the same
name but different parameters. Method overloading is also called compile-time polymorphism,
static polymorphism, or early binding. In Method overloading, the child argument takes
precedence over the parent argument.
Overriding: Method overriding Is the act of declaring a method In a subclass that Is already
present in a parent class.
When two or more methods in the same class have the same method name but different
parameters, this is called overloading. In contrast, overriding occurs when two methods have
the same name and parameters
Encapsulation in Java
→ Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
→ Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates.
→ Another way to think about encapsulation is, that it is a protective shield that prevents the data from
being accessed by the code outside this shield.
→ Encapsulation can be achieved by Declaring all the variables in the class as private and writing public
methods in the class to set and get the values of variables.
→ It is more defined with the setter and getter method.
Advantages Disadvantages
Polymorphism
→ The word polymorphism means having many forms. In simple words, we “can define Java
Polymorphism as the ability of a message to be displayed in more than one form.
Real-life Illustration of Polymorphism in Java: A person at the same time can have different characteristics.
Like a man at the same time is a father, a husband, and an employee. So the same person possesses
different behaviors in different situations. This is called polymorphism.
Unit-1 Page 20
What is Polymorphism in Java?
1. Increases code reusability by allowing objects of different classes to be treated as objects of a common
class.
2. Improves readability and maintainability of code by reducing the amount of code that needs to be written
and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class
of the object.
4. Enables objects to be treated as a single type, making it easier to write generic code that can handle
objects of different types.
Disadvantages
1. Can make it more difficult to understand the behavior of an object, especially if the code is complex.
2. This may lead to performance issues, as polymorphic behavior may require additional computations at
runtime.
Abstraction
→ Abstraction in Java is the process in which we only show essential details/functionality to the user. The
non-essential implementation details are not displayed to the user.
→ In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction
using interfaces.
→ Data Abstraction may also be defined as the process of identifying only the required characteristics of
an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from
other objects of similar type and also help in classifying/grouping the objects.
Interfaces Syntax:
Unit-1 Page 21
How to declare an Interface?
→ An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.
Abstract Class
→ Abstract classes are classes that contain one or more abstract methods(methods without body)
→ Abstract class is declared with abstract modifier.
→ Abstract class can contain concrete methods as well.
→ Concrete methods are complete methods with method heading and body.
Packages
→ Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
→ Packages are used for:
1. Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
2. Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
3. Providing controlled access: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member (without
any access specifier) is accessible by classes in the same package only.
4. Packages can be considered as data encapsulation (or data-hiding).
Classpath in Java
CLASSPATH describes the location where all the required files are available which are used in the application.
Java Compiler and JVM (Java Virtual Machine)_use CLASSPATH to locate the required files. If the CLASSPATH
is not set, Java Compiler will not be able to find the required files and hence will throw the following error.
Note:
The above error is resolved when CLASSPATH is set.
Semi-colon(;) is used as a seperator
Set the CLASSPATH in JAVA in Windows
dot(.) is the default value of classpath.
Unit-1 Page 22
Command Line: Find out where you have installed Java, basically, it's in /usr/lib/jvm path. Set the
CLASSPATH in /etc/environment using
→ A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and
associated metadata and resources (text, images, etc.) into one file to distribute application software or
libraries on the Java platform.
→ In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image
files, or directories.
→ We can imagine a .jar file as a zipped file(.zip) that is created by using WinZip software. Even, WinZip
software can be used to extract the contents of a .jar .
→ So you can use them for tasks such as lossless data compression, archiving, decompression, and
archive unpacking.
Syntax:
Here, cf represents to create the file. For example , assuming our package pack is available in C:\directory , to
convert it into a jar file into the pack.jar , we can give the command as:
→ In Java, package plays an important role in preventing naming conflicts, controlling access, and making
searching and usage of classes, enumeration, interfaces, and annotation easier.
Naming Conventions
→ For avoiding unwanted package names, we have some following naming conventions which we use in
creating a package.
○ The name should always be in the lower case.
○ They should be period-delimited.
○ The names should be based on the company or organization name
→ In order to define a package name based on an organization, we'll first reverse the company URL. After
that, we define it by the company and include division names and project names.
→ In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access
the static members of a class directly without class name or any object.
→ For Ex: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static
import we can access sqrt() method directly. According to SUN microSystem, it will improve the code
readability and enhance coding. But according to the programming experts, it will lead to confusion and
not good for programming. If there is no specific requirement then we should not go for static import.
Advantage: Disadvantage
If user wants to access any static member Static import makes the program
of class then less coding is required. unreadable and unmaintainable if you are
reusing this feature.
Unit-1 Page 23