Java UNIT - 1
Java UNIT - 1
Java Programming
Introduction:
Object Oriented Programming System (OOPS) :
Below are the OOPS concepts which simplifies software development,
• Class
• Object
• Abstraction
• Inheritance
• Polymorphism
• Encapsulation
1. Class:
A class is a design or blueprint from which objects are created.
Syntax :
Class Classname
{
…..
…..
}
Example :
Below is a student class that tells what details a student will have, this means every
student will have a unique name, age, etc.
class Student {
….
….
}
Important to remember :
While declaring a class,
• The class name (Student) should begin with the initial letter capitalized by
convention
• The class body is surrounded by braces { }
Object:
An object is the instance of class with state and behavior,
Example :
• Student is a class (blueprint)
• student1, student2 are objects
Syntax :
Class Classname
{
// below were properties which tells the state of students
….
….
// below is the method which tells the behavior of students
…..
……
}
Example :
Below is a student class that tells what details a student will have, this means every
student will have a unique name, age, behavior, etc.
Class Classname
{
// below were properties which tells the state of students
String studentName;
int age;
Abstraction:
Abstraction is a technique of hiding internal details and showing only the
functionalities to the user.
Consider a real world example of abstraction like it is a Student, the internal details
such as the marks calculation, attendance calculation, performance calculation, etc.
are hidden from the user, and only the features such as how much marks, total
present hours, performance percentage, etc were shown to the user rather than
knowing how it is being calculated.
Instructions to achieve abstraction:
• abstract is a keyword, which can be used with class and methods to achieve
abstraction
Implementation of abstraction:
Inheritance
Inheritance in Java is a mechanism where one class acquires the properties
and behaviors (fields and methods) of another class, promoting code
reusability and establishing an "is-a" relationship, “has-a” relationship. The extends
keyword is used to implement inheritance.
Polymorphism:
If one task is performed in different ways, it is known as polymorphism. For
example, to convince the customer differently, to draw something, for example, a
shape, a triangle, a rectangle, etc.
Another example can be to speak something; for example, a cat says meow, a dog
barks woof, etc.
Example:
1. class Animal {
2. // Method Overloading (compile-time polymorphism)
3. void sound() {
4. [Link]("An animal makes a sound");
5. }
6. void sound(String type) {
7. [Link]("Animal sound: " + type);
8. }
9. }
10. class Dog extends Animal {
11. // Method Overriding (runtime polymorphism)
12. @Override
13. void sound(String type) {
14. [Link]("Dog barking is: " + type);
15. }
16. }
17. public class Main {
18. public static void main(String[] args) {
19. Animal a = new Animal();
20. Dog d = new Dog();
21. Animal poly = new Dog();
22. // Method Overloading
23. [Link]();
24. [Link]("Generic");
25. // Method Overriding
26. [Link]("Loud");
27. // Performing the Polymorphism
28. [Link]("Soft");
29. }
30. }
Encapsulation:
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example, a capsule is wrapped with different medicines.
1. class Student {
2. // Private data members
3. private String name;
4. // Setter method
5. public void setName(String name) {
6. [Link] = name;
7. }
8. // Getter method
9. public String getName() {
10. return name;
11. }
12. }
13. public class Main {
14. public static void main(String[] args) {
15. Student s = new Student();
16. // Setting value using setter
17. [Link]("John");
18. // Getting value using getter
19. [Link]("Student Name: " + [Link]());
20. }
21. }
Compile and Run
Output:
History Of JAVA:
James Gosling initiated the Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called Oak after an oak tree that
stood outside Gosling's office, also went by the name Green and ended up later
being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA) This was achieved using the Java Virtual Machine
(JVM), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
Commonly used long term support (LTS) versions are : Java 8, 11, 17, 21, 25
Java allows you to model real-world entities (like a car or a bank account) as
objects in your program, making it easier to manage and build complex
applications.
5. Robust : Java provides many features that make programs execute reliably in a
variety of environments.
Java is a strictly typed language that checks code at compile time and runtime.
6. Multithreaded :
7. Architecture-neutral :
Java language and JVM help achieve the goal of “write once; run anywhere, any
time, forever.”
9. High performance
10. Distributed
Java applications can access remote objects on the Internet as easily as they can
do in the local system.
11. Dynamic
Java can link in new class libraries, methods, and objects dynamically.
JVM architecture
The Java Virtual Machine (JVM) is a core component of the Java Runtime
Environment (JRE) that allows Java programs to run on any platform
without modification. JVM acts as an interpreter between Java bytecode
and the underlying hardware, providing Java’s famous Write Once, Run
Anywhere (WORA) capability.
• Java source (.java) -> compiled by javac -> bytecode (.class)
• JVM loads the bytecode, verifies it, links it, and then executes it
• Execution may involve interpreting bytecode or using Just-In-Time
(JIT) compilation to convert “hot” code into native machine code for
performance
• Garbage collection runs in the background to reclaim memory from
unused objects
1. Class Loader Subsystem
The Class Loader is responsible for loading the .class files (which contain bytecode)
into the JVM memory during runtime. This process involves three steps:
• Loading: Finds and loads the binary data for a class from the file system or network,
and creates a Class object in the heap memory.
• Linking: Integrates the loaded class into the JVM's runtime state. This stage
includes:
o Verification: Ensures the bytecode is valid and adheres to the JVM's security rules.
o Preparation: Allocates memory for static variables and initializes them to default
values.
o Resolution: Replaces symbolic references in the class's constant pool with direct
references in memory.
• Initialization: Assigns the actual values defined in the code to all static variables and
executes static blocks.
• Bootstrap ClassLoader: Loads core Java API classes (e.g., from [Link] in older JDKs, or
similar core libraries in modern Java).
• Method Area: A single, shared area for all threads that stores class-level information
such as class name, parent class info, methods, variable data, and the runtime
constant pool. In Java 8 and later, this is called Metaspace.
• Heap Area: A shared memory area where all objects, instance variables, and arrays
are allocated and stored. This is the area managed by the Garbage Collector.
• Stack Area: Each thread has a private JVM stack, created when the thread is started.
It stores frames, which hold local variables, method calls, and partial results.
• PC (Program Counter) Registers: Each thread has its own PC register to hold the
memory address of the current instruction being executed.
• Native Method Stacks: Each thread has a separate stack to store information about
native methods (methods written in languages like C/C++) called via JNI.
3. Execution Engine
The execution engine is responsible for executing the bytecode read from the
runtime data areas.
• Interpreter: Reads and executes the bytecode instructions line by line. It is quick to
load the code but slower in execution due to repeated interpretation of the same
code.
• Just-In-Time (JIT) Compiler: To improve efficiency, the JIT compiler identifies "hot
spots" (frequently used code sections) and compiles their bytecode into highly
optimized, native machine code. This compiled native code is stored in the Code
Cache and reused for subsequent calls, significantly speeding up long-running
applications.
• Garbage Collector (GC): A daemon thread that automatically tracks and reclaims
memory from objects that are no longer referenced by the program, thereby
managing the heap memory and preventing memory leaks.
• Java Native Interface (JNI): A framework that acts as a bridge, allowing Java code to
interact with native applications and libraries written in other languages (like
C/C++).
• Native Method Libraries: The collection of C/C++ libraries required for the
execution of native methods.
Data types:
Primitive Data Types
boolean booleanVar;
Eg:
public class Geeks {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Is fish tasty? " + isFishTasty);
}
}
Output
Is Java fun? true
Is fish tasty? false
Output
Grade: A
Symbol: $
A 16-bit signed integer often used when memory is limited and values are
moderate in size.
Syntax:
short shortVar;
Output
Number of Students: 1000
Temperature: -200
A 32-bit signed integer and the most commonly used numeric data type.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
A 64-bit signed integer used when int is not sufficient for large values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
Output
World Population: 7800000000
Light Year Distance: 9460730472580800
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
1. String
Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder for heavy
string manipulation.
2. Class
class Car {
String model;
int year;
void display() {
[Link](model + " " + year);
}
}
Output
Toyota 2020
3. Object
class Car {
String model;
int year;
Output
Car Model: Honda
Car Year: 2021
4. Interface
interface Animal {
void sound();
}
Output
Woof
5. Array
Output
First number: 1
Second name: Geek2
Variables
Rules to Name Java Variables
• Start with a Letter, $, or _ – Variable names must begin with a letter (a–
z, A–Z), dollar sign $, or underscore _.
• No Keywords: Reserved Java keywords (e.g., int, class, if) cannot be
used as variable names.
• Case Sensitive: age and Age are treated as different variables.
• Use Letters, Digits, $, or _ : After the first character, you can use letters,
digits (0–9), $, or _.
• Meaningful Names: Choose descriptive names that reflect the purpose
of the variable (e.g., studentName instead of s).
• No Spaces: Variable names cannot contain spaces.
• Follow Naming Conventions: Typically, use camelCase for variable
names in Java (e.g., totalMarks).
class Geeks {
// Integer variable
// String variable
// Double variable
Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5
From the image, it can be easily perceived that while declaring a variable,
we need to take care of two things that are data type of the variable and
name.
class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables
Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
[Link] = instanceVar;
// Local Variable
int blockVar = 5;
// [Link](blockVar);
Output
Instance Variable: 50
Static Variable: 100
Method Parameter: 30
Local Variable: 20
Block Variable: 5
The scope of variables is the part of the program where the variable is
accessible. Like C/C++, in Java, all identifiers are lexically (or statically)
scoped, i.e., scope of a variable can be determined at compile time and
independent of the function call stack. In this article, we will learn
about Java Scope Variables.
Java Scope of Variables
Java Scope Rules can be covered under the following categories.
• Instance Variables
• Static Variables
• Local Variables
• Parameter Scope
• Block Scope
Now we will discuss all these Scopes and variables according to them.
Variables declared inside a method have method level scope and can't be
accessed outside the method.
Here's another example of method scope, except this time the variable got
passed in as a parameter to the method
Array:
// initializing array
int[] arr = {40, 55, 63, 17, 22};
// size of array
int n = [Link];
// traversing array
Output
40 55 63 17 22
• Store Primitives and Objects: Java arrays can hold both primitive types
(like int, char, boolean, etc.) and objects (like String, Integer, etc.)
• Contiguous Memory Allocation When we use arrays of primitive
types, the elements are stored in contiguous locations. For non primitive
types, references of items are stored at contiguous locations.
• Zero-based Indexing: The first element of the array is at index 0.
• Fixed Length: After creating an array, its size is fixed; we can not
change it.
Operators:
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on
primitive and non-primitive data types.
int a = 10, b = 3;
// Addition
int sum = a + b;
// Subtraction
int diff = a - b;
// Multiplication
int mul = a * b;
// Division
int div = a / b;
// Modulus
Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1
2. Unary Operators
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
import [Link].*;
// Driver Class
class Geeks{
// Integer declared
int a = 10;
int b = 10;
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
The assignment operator assigns a value from the right-hand side to a
variable on the left. Since it has right-to-left associativity, the right-hand
value must be declared or constant.
int n = 10;
// n = n + 5
n += 5;
n *= 2;
// n = n - 5
n -= 5;
// n = n / 2
n /= 2;
// n = n % 3
n %= 3;
Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0
Note: Use compound assignments (+=, -=) for cleaner code.
4. Relational Operators
Relational Operators are used to check for relations like equality, greater
than, and less than. They return boolean results after the comparison and
are extensively used in looping statements as well as conditional if-else
statements.
import [Link].*;
class Geeks{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR"
operations, similar to AND gate and OR gate in digital electronics. They
have a short-circuiting effect, meaning the second condition is not
evaluated if the first is false.
import [Link].*;
class Geeks {
// Main Function
// Logical operators
boolean x = true;
boolean y = false;
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has
three operands and hence the name Ternary. The general format is
// numbers
Output
Max of three numbers = 30
7. Bitwise Operators
These operators perform operations at the bit level.
• Bitwise Operators manipulate individual bits using AND, OR, XOR,
and NOT.
• Shift Operators move bits to the left or right, effectively multiplying or
dividing by powers of two.
import [Link].*;
class Geeks
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
Output
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
8. instanceof Operator
The instanceof 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. The general
format,
}
}
Output
true
true
false
control statements:
If statement:
class Geeks {
int i = 10;
if (i < 15) {
[Link]("Condition is True");
}
}
Output
Condition is True
class Geeks {
int i = 10;
if (i < 15)
else
}
Output
i is smaller than 15
int i = 10;
// Outer if statement
if (i < 15) {
if (i == 10) {
}
Output
i is smaller than 15
i is exactly 10
class Geeks {
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
Output
It is 20
Constructors:
A constructor in Java is a special member that is called when an object is created. It
initializes the new object’s state. It is used to set default or user-defined values for
the object's attributes
• A constructor has the same name as the class.
• It does not have a return type, not even void.
• It can accept parameters to initialize object properties.
Types of Constructors in Java
1. Default Constructor
class Geeks{
// Default Constructor
Geeks(){
[Link]("Default constructor");
}
Output
Default constructor
Note: It is not necessary to write a constructor for a class because the Java compiler
automatically creates a default constructor (a constructor with no arguments) if your class
doesn’t have any.
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we
want to initialize fields of the class with our own values, then use a parameterized
constructor.
class Geeks{
String name;
int id;
// Parameterized Constructor
[Link] = name;
[Link] = id;
void display(){
[Link]("GeekName: " + name
// universal compatibility
[Link]();
}
Output
GeekName: Sweta and GeekId: 68
Unlike other constructors copy constructor is passed with another object which
copies the data available from the passed object to the newly created object.
import [Link].*;
class Geeks{
String name;
int id;
// Parameterized Constructor
[Link] = name;
[Link] = id;
// Copy Constructor
Geeks(Geeks obj2)
[Link] = [Link];
[Link] = [Link];
class GFG {
[Link]("First Object");
[Link]();
[Link](
}
Output
First Object
GeekName: Sweta and GeekId: 68
4. Private Constructor
A private constructor cannot be accessed from outside the class. It is commonly used
in:
• Singleton Pattern: To ensure only one instance of a class is created.
• Utility/Helper Classes: To prevent instantiation of a class containing only static
methods.
class GFG {
// Private constructor
private GFG(){
// Static method
class Main{
[Link]();
}
Output
Hello from GFG class!
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.
• A method allows to write a piece of logic once and reuse it wherever needed in
the program.
• This helps keep your code clean, organized, easier to understand and manage.
Syntax of a Method
Example:
public class World
// An example method
[Link]("Hello, World!");
[Link]();
}
Output:
Hello, World
Explanation:
• Here, first we create a method which prints Hello, Geeks!
• printMessage() is a simple method that prints a message.
• It has no parameters and does not return anything.
Static block
Whenever we use a static keyword and associate it to a block, then that block is
referred to as a static block. Java supports static block (also called static clause) that
can be used for static initialization of a class. This code inside the static block is
executed only once: the first time the class is loaded into memory.
Example:
class Test {
// Class 2
class GFG {
Output:
Static Data:
The static keyword in Java is used for memory management and belongs to the class
rather than any specific instance. It allows members (variables, methods, blocks, and
nested classes) to be shared among all objects of a class.
• Memory is allocated only once when the class is loaded.
• No object creation is needed to access static members; use the class name directly.
• Static methods and variables can’t access non-static members directly.
• Static methods can’t be overridden because they belong to the class, not
instances.
Types of Static Members in Java
1. Static Variables
2. Static Blocks
A static block is executed only once when the class is first loaded into
memory. It is often used to initialize static variables or perform configuration
tasks before the main method executes.
3. Static Methods
A static method belongs to the class rather than to any object. It can be called
directly using the class name.
• Can access only static data directly.
• Cannot access instance variables or methods directly.
• Cannot use this or super keywords.
4. Static Nested Classes
A static nested class is a class declared as static inside another class. It can be
accessed without creating an object of the outer class.
Example:
class Geeks{
// static variable
static int a = m1();
// static block
static{
// static method
static int m1(){
[Link]("From m1");
return 20;
}
From m1
Inside static block
Value of a: 20
From main
The [Link] package contains two string classes: String and StringBuffer. You
use the String class when you are working with strings that cannot
change. StringBuffer, on the other hand, is used when you want to
manipulate the contents of the string on the fly.
The reverseIt method in the following code uses both
the String and StringBuffer classes to reverse the characters of a string. If you
have a list of words, you can use this method in conjunction with a sort
program to create a list of rhyming words (a list of words sorted by ending
syllables). Just reverse all the strings in the list, sort the list, and reverse the
strings again.
Example:
class ReverseString {
public static String reverseIt(String source) {
int i, len = [Link]();
StringBuffer dest = new StringBuffer(len);
Output
These are the same steps for creating an object of any type.