0% found this document useful (0 votes)
5 views49 pages

Java UNIT - 1

This document provides an overview of Java programming, focusing on Object-Oriented Programming (OOP) concepts such as classes, objects, abstraction, inheritance, polymorphism, and encapsulation. It also covers the history of Java, its key features, the architecture of the Java Virtual Machine (JVM), and primitive data types. Additionally, it explains how Java enables code reusability and simplifies software development through its OOP principles.

Uploaded by

sham vasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

Java UNIT - 1

This document provides an overview of Java programming, focusing on Object-Oriented Programming (OOP) concepts such as classes, objects, abstraction, inheritance, polymorphism, and encapsulation. It also covers the history of Java, its key features, the architecture of the Java Virtual Machine (JVM), and primitive data types. Additionally, it explains how Java enables code reusability and simplifies software development through its OOP principles.

Uploaded by

sham vasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

Each student object has unique state and behavior,

• State (fields / properties) → name, age


• Behavior(methods) → study() (actions of each student)

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;

// below is the method which tells the behavior of students


void study() {
[Link]("Student is studying");
}
}

How to create objects of a class:


Syntax:

Class Classname = new Classname();

Actual creation of multiple objects of a student class:

Student student1 = new Student();


Student student2 = new Student();
Important to remember :
In the above example,

• Student → class name


• student1, student2 → object reference (variable name)
• new Student() → creates a new Student object in memory

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:

• abstract methods will have only method signature with no implementation


unlike normal / concreate methods (method which has complete body /
implementation )

Abstract method Syntax Concreate method Syntax


abstract void marks(); // no method void marks(){
body / implementation this is method body which has
implementation logic
….
…..
}

• In the below example of Student class,


• abstract class Student → The class is defined with abstract keyword, so that
we can have abstract method (marks) inside it.
• abstract void marks() → Declares action to perform, but hides the
implementation logic how it is done.
• class CollegeStudent extends Student → We create a separate child class
“CollegeStudent” which extends (extends is a keyword) the parent class
“CollegeStudent” will have the Implementation logic for the marks() method
on how the student performs actions.
• Student student = new CollegeStudent(); → Creates object of child class.
• [Link](); [Link](); → Calls methods without
seeing internal details.

abstract class Student {


abstract void marks(); // line 2, implementation hidden
}

class CollegeStudent extends Student {


void marks() {
[Link]("Studying from books"); // implementation logic
}
}

public class Main {


public static void main(String[] args) {
Student student = new CollegeStudent(); // abstraction in action
[Link]();
[Link]();
}
}

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.

Example of “is-a” relationship:


// Superclass (Parent Class)
class Animal {
String species = "Animal";
public void eat() {
[Link]("The animal eats food.");
}
}

// Subclass (Child Class)


class Dog extends Animal {
// Dog inherits the 'species' field and 'eat()' method from Animal
public void bark() {
[Link]("The dog barks.");
}
}

// Main class to demonstrate inheritance


public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();

// Accessing inherited field


[Link]("My dog is an " + [Link]); // Output: My dog is an
Animal

// Accessing inherited method


[Link](); // Output: The animal eats food.

// Accessing the subclass's own method


[Link](); // Output: The dog barks.
}
}

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.

In Java, we use method overloading and method overriding to achieve


polymorphism.

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. }

Compile and Run


Output:

An animal makes a sound


Animal sound: Generic
Dog barking is: Loud
Dog barking is: Soft

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.

A Java class is an example of encapsulation. A Java bean is a fully encapsulated class


because all the data members are private.

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:

Student Name: John

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.

On 2010, Oracle Corporation acquired JAVA from Sun Microsystems

Java versions starts from 1.0 till 25 currently

Commonly used long term support (LTS) versions are : Java 8, 11, 17, 21, 25

Java buzz words:


1. Simple : Java was designed to be easy for the professional programmer to learn and use
effectively. . Because Java inherits the C/C++ syntax and many of the object-oriented
features of C++, most programmers have little trouble learning Java.
2. Secure: The object model in Java is simple and easy to extend, while primitive types,
such as integers, are kept as high-performance nonobjects.
3. Portable
4. Object-oriented : Everything in Java revolves around objects and classes.

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.

Key Object-Oriented Programming (OOP) concepts include:

1. Object: An instance of a class.


2. Class: A blueprint for creating objects.
3. Inheritance: Allows one class to inherit the properties of another.
4. Polymorphism: The ability of objects to take on multiple forms.
5. Abstraction: Hides the complex details and shows only the essentials.
6. Encapsulation: Keeps the data safe by restricting access to it.

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.

• Java handles memory management with garbage collection and captures


serious errors through exception handling.

6. Multithreaded :

Multithreaded programs handle multiple tasks simultaneously, which is helpful


in creating interactive, networked programs.

Java run-time system supports multiprocess synchronization for constructing


interactive systems.

7. Architecture-neutral :

Java language and JVM help achieve the goal of “write once; run anywhere, any
time, forever.”

Changes and upgrades in operating systems, processors, and system resources


do not force any changes in Java programs.

8. Compiled and Interpreted

Java combines both compiled and interpreted approaches, making it a two-stage


system.

Compiled: Java compiles programs into an intermediate representation called


Java Bytecode.
Interpreted: Bytecode is then interpreted, generating machine code that can be
directly executed by the machine that provides a JVM.

9. High performance

Java performance is high because of the use of bytecode.

The bytecode can be easily translated into native machine code.

10. Distributed

Java is designed to create distributed applications on networks.

Java applications can access remote objects on the Internet as easily as they can
do in the local system.

Java enables multiple programmers at multiple remote locations to collaborate


and work together on a single project.

11. Dynamic

Java can link in new class libraries, methods, and objects dynamically.

Java programs carry substantial amounts of run-time type information, enabling


dynamic linking in a safe and expedient manner.

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.

There are three built-in Class Loaders:

• Bootstrap ClassLoader: Loads core Java API classes (e.g., from [Link] in older JDKs, or
similar core libraries in modern Java).

• Extension ClassLoader: Loads classes from standard extension directories.

• System/Application ClassLoader: Loads application-specific class files from the


classpath defined by the user.

2. Runtime Data Areas (JVM Memory)


These are the memory areas where data is stored during program execution.

• 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

1. boolean Data Type

Represents one of two logical values: true or false. It is commonly used in


conditions and control statements.
Syntax:

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

2. Char data type:


char Data Type

A 16-bit Unicode character used to store single symbols or letters.


Syntax:
char charVar;

Size : 2 bytes (16 bits)


Example: This example, demonstrates how to use char data type to store
individual characters.

public class Geeks {


public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
[Link]("Grade: " + grade);
[Link]("Symbol: " + symbol);
}
}

Output
Grade: A
Symbol: $

3. byte Data Type

An 8-bit signed integer used to save memory in large numeric arrays.


Syntax:
byte byteVar;

public class Geeks {


public static void main(String[] args) {
byte age = 25;
byte temperature = -10;
[Link]("Age: " + age);
[Link]("Temperature: " + temperature);
}
}
Output
Age: 25
Temperature: -10

4. short Data Type

A 16-bit signed integer often used when memory is limited and values are
moderate in size.
Syntax:
short shortVar;

public class Geeks {


public static void main(String[] args) {
short students = 1000;
short temp = -200;
[Link]("Students: " + students);
[Link]("Temperature: " + temp);
}
}

Output
Number of Students: 1000
Temperature: -200

5. int Data Type

A 32-bit signed integer and the most commonly used numeric data type.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )

public class Geeks {


public static void main(String[] args) {
int population = 2000000;
int distance = 150000000;
[Link]("Population: " + population);
[Link]("Distance: " + distance);
}
}
Output
Population: 2000000
Distance: 150000000

6. long Data Type

A 64-bit signed integer used when int is not sufficient for large values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)

public class Geeks {


public static void main(String[] args) {
long worldPopulation = 7800000000L;
long lightYears = 9460730472580800L;
[Link]("World Population: " + worldPopulation);
[Link]("Light Years: " + lightYears);
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

6. float Data Type

A 32-bit single-precision floating-point type used for fractional values.


Syntax:
float floatVar;
Size : 4 bytes (32 bits)

public class Geeks {


public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
[Link]("Pi: " + pi);
[Link]("Gravity: " + gravity);
}
}
Output
Value of Pi: 3.14
Gravity: 9.81

7. double Data Type

A 64-bit double-precision floating-point type and the default for decimal


numbers.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits). It is recommended to go through rounding off errors
in java.

public class Geeks {


public static void main(String[] args) {
double pi = 3.141592653589793;
double avogadro = 6.02214076e23;
[Link]("Pi: " + pi);
[Link]("Avogadro's Number: " + avogadro);
}
}

Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23

Non-Primitive (Reference) Data Types


Non-primitive data types store references (memory addresses) rather than
actual values. They are created by users and include types like String,
Class, Object, Interface, and Array.

1. String

String represents a sequence of characters enclosed in double quotes.


Unlike C/C++, Java strings are objects and are immutable.
Syntax:
String str = "Hello";

public class Geeks {


public static void main(String[] args) {
String name = "Geek1";
String message = "Welcome to Java";
[Link]("Name: " + name);
[Link]("Message: " + message);
}
}

Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder for heavy
string manipulation.

2. Class

A class is a user-defined blueprint that defines variables and methods. It


represents a type of object and forms the foundation of Object-Oriented
Programming.

class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}

void display() {
[Link](model + " " + year);
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
[Link]();
}
}

Output
Toyota 2020
3. Object

An Object is an instance of a class representing real-world entities. It has


state (data), behavior (methods), and identity (unique reference).

class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Honda", 2021);
[Link]("Model: " + [Link]);
[Link]("Year: " + [Link]);
}
}

Output
Car Model: Honda
Car Year: 2021

4. Interface

An interface defines a contract of abstract methods that implementing


classes must define. It provides a way to achieve abstraction and multiple
inheritance in Java.

interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Woof");
}
}

public class Geeks {


public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
}
}

Output
Woof

5. Array

An array stores multiple elements of the same type in a single structure.


Java arrays are objects, dynamically allocated, and indexed from 0.

public class Geeks {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Geek1", "Geek2", "Geek3"};
[Link]("First number: " + numbers[0]);
[Link]("Second name: " + names[1]);
}
}

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).

In Java, variables are containers used to store data in memory. Variables


define how data is stored, accessed, and manipulated.
A variable in Java has three components,
• Data Type: Defines the kind of data stored (e.g., int, String, float).
• Variable Name: A unique identifier following Java naming rules.
• Value: The actual data assigned to the variable.

class Geeks {

public static void main(String[] args) {

// Declaring and initializing variables

// Integer variable

int age = 25;

// String variable

String name = "GeeksforGeeks";

// Double variable

double salary = 50000.50;

// Displaying the values of variables

[Link]("Age: " + age);


[Link]("Name: " + name);

[Link]("Salary: " + salary);


}

Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5

How to Declare Java Variables?


The image below demonstrates how we can declare a variable in Java:

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.

How to Initialize Java Variables?


It can be perceived with the help of 3 components explained above:
Example: Here, we are initializing variables of different types like float,
int and char.

class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables

// Initializing float variable


float si = 5.5f;

// Initializing integer variables


int t = 10;
int s = 20;

// Initializing character variable


char var = 'h';

// Displaying the values of the variables


[Link]("Simple Interest: " + si);
[Link]("Speed: " + s);
[Link]("Time: " + t);
[Link]("Character: " + var);
}
}

Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h

Scope and life time of variables:

Important Points about Variable Scope in Java

• In general, a set of curly brackets { } defines a scope.


• In Java we can usually access a variable as long as it was defined within
the same set of brackets as the code we are writing or within any curly
brackets inside of the curly brackets where the variable was defined.
• Any variable defined in a class outside of any method can be used by all
member methods.
• When a method has the same local variable as a member, "this" keyword
can be used to reference the current class variable.
• For a variable to be read after the termination of a loop, It must be
declared before the body of the loop.

Java Program Demonstrating All Variable Scopes

public class Geeks {

// Instance Variable (belongs to each object)

private int instanceVar = 10;

// Static Variable (shared among all instances)

static int staticVar = 100;

// Constructor demonstrating parameter scope

public Geeks(int instanceVar) {


// Parameter Scope

// using 'this' to refer to instance variable

[Link] = instanceVar;

// Method to demonstrate local, parameter, and block scope

public void showScopes(int paramVar) {

// Local Variable

// only accessible in this method

int localVar = 20;

[Link]("Instance Variable: " + instanceVar);

[Link]("Static Variable: " + staticVar);

[Link]("Method Parameter: " + paramVar);

[Link]("Local Variable: " + localVar);

// Block Scope (variable only accessible inside this block)

if (localVar > 10) {

int blockVar = 5;

[Link]("Block Variable: " + blockVar);

// Uncommenting below line would cause an error: blockVar out of scope

// [Link](blockVar);

public static void main(String[] args) {

Geeks obj = new Geeks(50);


[Link](30);

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.

1. Instance Variables - Class Level Scope


These variables must be declared inside a class (outside any function).
They can be directly accessed anywhere in class.

2. Static Variables - Class Level Scope

Static Variable is a type of class variable shared across instances. Static


Variables are the variables which once declared can be used anywhere
even outside the class without initializing the class. Unlike Local variables
it scope is not limited to the class or the block.
3. Method Level Scope - Local Variable

Variables declared inside a method have method level scope and can't be
accessed outside the method.

4. Parameter Scope - Local Variable

Here's another example of method scope, except this time the variable got
passed in as a parameter to the method

5. Block Level Scope


A variable declared inside pair of brackets "{" and "}" in a method has scope
within the brackets only.

Array:

In Java, an array is an important linear data structure that allows us to store


multiple values of the same type.
• Arrays in Java are objects, like all other objects in Java, arrays implicitly
inherit from the [Link] class. This allows you to invoke
methods defined in Object (such as toString(), equals() and hashCode()).
• Arrays have a built-in length property, which provides the number of
elements in the array

public class Geeks {

public static void main(String[] args)

// initializing array
int[] arr = {40, 55, 63, 17, 22};

// size of array
int n = [Link];

// traversing array

for (int i = 0; i < n; i++)

[Link](arr[i] + " ");

Output
40 55 63 17 22

Key features of Arrays

• 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.

public class GFG{

public static void main(String[] args) {

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

int mod = a % b; // Modulus

[Link]("Sum: " + sum);

[Link]("Difference: " + diff);

[Link]("Multiplication: " + mul);

[Link]("Division: " + div);

[Link]("Modulus: " + mod);

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{

public static void main(String[] args){

// Integer declared
int a = 10;

int b = 10;

// Using unary operators

[Link]("Postincrement : " + (a++));

[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));

[Link]("Predecrement : " + (--b));

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.

public class GFG{

public static void main(String[] args){

int n = 10;

// n = n + 5

n += 5;

[Link]("After += : " + n);


// n = n * 2

n *= 2;

[Link]("After *= : " + n);

// n = n - 5

n -= 5;

[Link]("After -= : " + n);

// n = n / 2

n /= 2;

[Link]("After /= : " + n);

// n = n % 3

n %= 3;

[Link]("After %= : " + n);

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{

public static void main(String[] args){

// Comparison operators

int a = 10;

int b = 3;

int c = 5;

[Link]("a > b: " + (a > b));

[Link]("a < b: " + (a < b));

[Link]("a >= b: " + (a >= b));

[Link]("a <= b: " + (a <= b));

[Link]("a == c: " + (a == c));

[Link]("a != c: " + (a != c));

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

public static void main (String[] args) {

// Logical operators

boolean x = true;

boolean y = false;

[Link]("x && y: " + (x && y));

[Link]("x || y: " + (x || y));

[Link]("!x: " + (!x));

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

public class Geeks{

public static void main(String[] args){


int a = 20, b = 10, c = 30, result;

// result holds max of three

// numbers

result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);

[Link]("Max of three numbers = "+ result);

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

public static void main(String[] args)

// Bitwise operators

int d = 0b1010;

int e = 0b1100;

[Link]("d & e : " + (d & e));

[Link]("d | e : " + (d | e));

[Link]("d ^ e : " + (d ^ e));


[Link]("~d : " + (~d));

[Link]("d << 2 : " + (d << 2));

[Link]("e >> 1 : " + (e >> 1));

[Link]("e >>> 1 : " + (e >>> 1));

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,

public class GFG{

public static void main(String[] args){

String str = "Hello";

[Link](str instanceof String);

Object obj = new Integer(10);

[Link](obj instanceof Integer);

[Link](obj instanceof String);

}
}

Output
true
true
false

control statements:

If statement:
class Geeks {

public static void main(String args[])

int i = 10;

if (i < 15) {

[Link]("Condition is True");

}
}
Output
Condition is True

Java if-else Statement


The if-else statement allows you to execute one block if the condition is true and
another block if it is false.
import [Link].*;

class Geeks {

public static void main(String args[])

int i = 10;

if (i < 15)

[Link]("i is smaller than 15");

else

[Link]("i is greater than 15");

}
Output
i is smaller than 15

Java nested-if Statement


A nested-if is an if statement inside another if statement. It is useful when a second
condition depends on the first.
class Geeks {

public static void main(String args[])

int i = 10;

// Outer if statement

if (i < 15) {

[Link]("i is smaller than 15");


// Nested if statement

if (i == 10) {

[Link]("i is exactly 10");

}
Output
i is smaller than 15
i is exactly 10

Java Switch Case

The switch statement is a multiway branch statement. It provides an easy way to


dispatch execution to different parts of code based on the value of the expression.
import [Link].*;

class Geeks {

public static void main(String[] args)

int num = 20;

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

A default constructor has no parameters. It’s used to assign default values to an


object. If no constructor is explicitly defined, Java provides a default constructor.
import [Link].*;

class Geeks{

// Default Constructor

Geeks(){
[Link]("Default constructor");

public static void main(String[] args){

Geeks hello = new Geeks();

}
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{

// data members of the class

String name;

int id;

// Parameterized Constructor

Geeks(String name, int id)

[Link] = name;

[Link] = id;

// Method to display object data

void display(){
[Link]("GeekName: " + name

+ " and GeekId: " + id);

// main() method — placed inside the same class for

// universal compatibility

public static void main(String[] args){

// This will invoke the parameterized constructor

Geeks geek1 = new Geeks("Sweta", 68);

[Link]();

}
Output
GeekName: Sweta and GeekId: 68

3. Copy Constructor in Java

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{

// data members of the class

String name;

int id;

// Parameterized Constructor

Geeks(String name, int id)


{

[Link] = name;
[Link] = id;

// Copy Constructor

Geeks(Geeks obj2)

[Link] = [Link];

[Link] = [Link];

class GFG {

public static void main(String[] args)

// This would invoke the parameterized constructor

[Link]("First Object");

Geeks geek1 = new Geeks("Sweta", 68);

[Link]("GeekName: " + [Link]

+ " and GeekId: " + [Link]);

[Link]();

// This would invoke the copy constructor

Geeks geek2 = new Geeks(geek1);

[Link](

"Copy Constructor used Second Object");

[Link]("GeekName: " + [Link]

+ " and GeekId: " + [Link]);

}
Output
First Object
GeekName: Sweta and GeekId: 68

Copy Constructor used Second 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(){

[Link]("Private constructor called");

// Static method

public static void displayMessage(){

[Link]("Hello from GFG class!");

class Main{

public static void main(String[] args){

// GFG u = new GFG(); // Error: constructor is


// private

[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

public void printMessage() {

[Link]("Hello, World!");

public static void main(String[] args) {


// Create an instance of the class

// containing the method

World obj = new World();

// Calling the method

[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 {

// Case 1: Static variable


static int i;
// Case 2: non-static variables
int j;

// Case 3: Static block


static
{
i = 10;
[Link]("static block called ");
}
// End of static block
}

// Class 2
class GFG {

// Main driver method


public static void main(String args[])
{
[Link](Test.i);
}
}

Output:

static block called


10

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

A static variable is also known as a class variable. It is shared among all


instances of the class and is used to store data that should be common for all objects.

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{

[Link]("Inside static block");


}

// static method
static int m1(){

[Link]("From m1");
return 20;
}

public static void main(String[] args){

[Link]("Value of a: " + a);


[Link]("From main");
}
}
OUTPUT:

From m1
Inside static block
Value of a: 20
From main

The String and StringBuffer Classes

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);

for (i = (len - 1); i >= 0; i--) {


[Link]([Link](i));
}
return [Link]();
}
}

Output

Original String: HELLO


Reversed String: OLLEH

Why Two String Classes?


The Java development environment provides two classes that store and manipulate
character data: String, for constant strings, and StringBuffer, for strings that can
change.
Creating Strings and StringBuffers
The following statement taken from the reverseIt method creates a
new StringBuffer in three steps: declaration, instantiation, and initialization.
Syntax:

StringBuffer dest = new StringBuffer(len);

These are the same steps for creating an object of any type.

You might also like