0% found this document useful (1 vote)
1K views62 pages

Unit 1 Java by Multiatoms

The document provides an overview of various operators in Java, including arithmetic, assignment, comparison, logical, bitwise, and control flow statements. It details object-oriented programming concepts such as classes, methods, inheritance, encapsulation, polymorphism, and abstraction, along with practical examples. Additionally, it covers Java packages, CLASSPATH, JAR files, and naming conventions, emphasizing Java's features like platform independence and security.

Uploaded by

Satyam Raj Singh
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 (1 vote)
1K views62 pages

Unit 1 Java by Multiatoms

The document provides an overview of various operators in Java, including arithmetic, assignment, comparison, logical, bitwise, and control flow statements. It details object-oriented programming concepts such as classes, methods, inheritance, encapsulation, polymorphism, and abstraction, along with practical examples. Additionally, it covers Java packages, CLASSPATH, JAR files, and naming conventions, emphasizing Java's features like platform independence and security.

Uploaded by

Satyam Raj Singh
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
You are on page 1/ 62

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.


Assignment Operators
Assignment operators are used to assign values to variables.
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important
in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either true or false.
Logical Operators
You can also test for true or false values with logical operators.
Logical Operators
You can also test for true or false values with logical operators.
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.).
Control Flow in Java
● Java compiler executes the code from top to bottom.
● Java provides statements that can be used to control the flow of Java code.
Such statements are called control flow statements.
● It is one of the fundamental features of Java, which provides a smooth flow of
program.

Java provides three types of control flow statements.


1. Decision Making Statements -> if statements and switch statement
2. Loops Statements -> for, while, do while, for each loop
3. Jump Statements -> Break and Continue Statement
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. In Java, there are four types of if-statements given
below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

LETS CODE….
SWITCH:
In Java, a switch statement is a control flow statement that allows you to execute
different blocks of code based on the value of a variable or expression.
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.

1. for loop
2. while loop
3. do-while loop
4. for-each loop

Lets Code…
while loop flowchart do-while loop flowchart
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements.

Java break statement


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.

continue 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.
Arrays in Java
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.
Advantages:
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime.
String in Java
In Java, string is basically an object that represents sequence of char values. An
array of characters works same as Java string.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:

● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
Class
A class is a basic building block. It can be defined as template that describes the data
and behaviour associated with the class instantiation. Instantiating is a class is to create
an object (variable) of that class that can be used to access the member variables and
methods of the class.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
Syntax:
<access specifier> class class_name
{
}
What is a method in Java?
A method is a reusable block of code designed to perform specific tasks. By calling
or invoking it, we execute its functionality without needing to rewrite the code.
This promotes code reusability, easy modification, and enhances code readability.
Access Specifier:
Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:

● Public: The method is accessible by all classes when we use public specifier in our
application.
● Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
● Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
● Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package
only.
Static Members:
● Static members belong to the class rather than to any specific instance of the class.
● They are shared among all instances of the class.
● Static members can be accessed directly using the class name without needing to
instantiate an object.

Final Members:
● Final members are constants that cannot be changed once initialized.
● For variables, once a final variable is assigned a value, it cannot be reassigned.
● For methods, a final method cannot be overridden by subclasses.
● For classes, a final class cannot be subclassed.
● Final members are often used to define constants or to prevent further
modification of certain elements in a program.
Constructors in Java
A constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.

It is a special type of method which is used to initialize the object.

Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types: Default and Parameterised


Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes.

Why use inheritance in java

● For Method Overriding (so runtime polymorphism can be achieved).


● For Code Reusability.
Terms used in Inheritance
● Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
● Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a
new class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
Method Overloading
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

There are two ways to overload the method in java:

● By changing number of arguments


● By changing the data type
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

Rules for Java Method Overriding:

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an inheritance.
Encapsulation
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.

We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.


Polymorphism
Polymorphism in Java is a fundamental concept in object-oriented programming
(OOP) that allows objects of different classes to be treated as objects of a common
superclass. This allows for flexibility and extensibility in your code.

(Think of it this way: you have a group of superheroes with different abilities, but they
can all be referred to as "superheroes".)

There are two main types of polymorphism in Java:

1. Compile-time Polymorphism: This is achieved through method overloading.


2. Runtime Polymorphism: This is achieved through method overriding.
Abstraction
Abstraction in Java is another core concept of object-oriented programming (OOP),
alongside encapsulation, inheritance, and polymorphism. It involves hiding the
complex implementation details of a system and showing only the essential features
of the object.
Abstraction can be achieved in Java using two main mechanisms:
1. Abstract Classes
2. Interfaces

Abstraction allows you to focus on what an object does rather than how it does it,
promoting code reusability, maintainability, and flexibility in large software systems.
Abstract Classes
An abstract class is a class that cannot be instantiated on its own and may contain
abstract methods (methods without a body) as well as concrete methods (methods
with a body). Abstract methods serve as placeholders for methods that must be
implemented by subclasses. Abstract classes can have constructors and instance
variables just like any other class.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}}
In this example, Shape is an abstract class with an abstract method draw(). Subclasse
Circle extend the Shape class and provide concrete implementations of the draw()
method.
Interfaces
An interface in Java is a blueprint of a class that defines a set of abstract methods.
Unlike abstract classes, interfaces cannot have instance variables or constructors.
Classes can implement multiple interfaces, allowing them to inherit behavior from
multiple sources.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}}
In this example, the Animal interface declares an abstract method sound().The
Dog class implement the Animal interface and provide their own implementation
of the sound() method.
Package in JAVA
In Java, a package is a mechanism for organizing classes, interfaces, and
Sub-Packages, which helps in avoiding name conflicts and controlling access.
Packages are also used to group related classes and interfaces together, making
the code more modular and easier to manage.
Package in java can be categorized in two form, built-in package and
user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
Example of java package
The package keyword is used to create a package in java.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
CLASSPATH in Java
The CLASSPATH is an environment variable used by the Java compiler
(javac) and the Java runtime (java) to locate classes that are referenced in your
program. Setting the CLASSPATH correctly is crucial for compiling and
running Java programs that are organized into packages.
You can set the CLASSPATH in various ways:
a. Setting CLASSPATH Temporarily
b. Setting CLASSPATH Permanently
a. Setting CLASSPATH Temporarily
On Windows:

set PATH=.;C:\Program Files\Java\JDK1.6.20\bin


On Unix/Linux/Mac:

sudo <editor name> /etc/environment


JAVA_HOME = "/usr/lib/jvm/<java folder (eg. java-1.8.0-openjdk-amd64>)/bin"
export JAVA_HOME
CLASSPATH=".:/usr/lib/jvm/<java folder>/lib:/home/name/Desktop"
export CLASSPATH
b. Setting CLASSPATH Permanently
On Windows:

1. Right-click on This PC or My Computer and select Properties.


2. Click on Advanced system settings.
3. Click on the Environment Variables button.
4. In the System variables section, click New or select the existing CLASSPATH
variable and click Edit.
5. Add your paths to the CLASSPATH variable.
JAR files in Java
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.
Create a JAR file
Syntax:

jar cf jarfilename inputfiles


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:

C:\> jar cf pack.jar pack


Naming Conventions for Java Packages:

For avoiding unwanted package names, we have some following naming


conventions which we use in creating a package.
1. Use Lowercase Letters:

E.g: package com.example.myapp;

2. Period-Delimited Structure:

E.g: package com.example.myapp.controllers;

3. Base Names on Company or Organization:

E.g: package com.example.myapp.services;


import and static import statement
Java 5.0 introduced static import, also known as the tiger version, as a new language
feature. Static variables and static members can now be accessed directly without
having to use class names.

We had normal import statements for every java class before static import was
introduced; we used class names to call methods and classes. Below is an example of a
normal import for the List class.

import java.util.List;
import static java.lang.Math.*;
UNIT-1 is Completed
Thank You
Subscribe For More Amazing Explanations
Checkout Desc. For Notes and More Subjects Playlist
Unit-1 OOPS WITH JAVA

1.3 Feature of JAVA.?


Platform Independence: "Write once, run
1. Introduction anywhere" capability due to the Java Virtual
1.1 why JAVA? Machine (JVM).
Java is a popular and versatile programming Object-Oriented: Encourages modular and
language that has been around for more than reusable code through classes and objects.
two decades. Simple: Easy to learn with a clean syntax
1. Platform Independence: Runs on any device similar to C++ but with fewer complexities.
with Java Virtual Machine (JVM). Secure: Built-in security features like
2. Object-Oriented: Encourages modular, bytecode verification and secure class

s
reusable code. loading.

lu
3. Robust and Secure: Strong memory Robust: Strong memory management,
management and security features. exception handling, and automatic garbage
4. Rich API and Libraries: Extensive standard collection.
library and third-party support. Multithreaded: Supports concurrent

sP
5. Community Support: Large, active execution of multiple threads for better
community with ample resources. performance.
6. Performance: Balanced performance with High Performance: Just-In-Time (JIT)
Just-In-Time (JIT) compilation. compiler enhances runtime performance.
om
7. Enterprise Adoption: Widely used in Distributed: Designed for building
enterprise applications and web services. applications that can be distributed across
8. Job Market: High demand for Java networks.
developers. Dynamic: Can adapt to evolving
1.2 History of Java environments with its dynamic linking and
loading capabilities.
At

Early 1990s: Developed by James Gosling at Rich Standard Library: Provides a vast set of
Sun Microsystems; originally named "Oak" APIs for various tasks like I/O, networking,
for interactive TV. and GUI development.
1995: Renamed to "Java" and released
1.4 JVM Vs JVM Vs JRE
publicly, emphasizing platform
ti

independence with the JVM.


Late 1990s: Gained popularity for web
ul

development with applets.


2004: Java 5.0 introduced major features
like generics and annotations.
2006: Became open-source under the GNU
M

General Public License.


2009: Oracle acquired Sun Microsystems.
JDK (Java Development Kit):
2011: Java 7 added features like the try-with-
resources statement. 1. Purpose: Provides tools to develop Java
2014: Java 8 introduced lambda expressions applications.
and the Stream API. 2. Components: Includes the JRE, compilers,
2017: Oracle announced a six-month release debuggers, and development tools.
cycle for new features. 3. Usage: Needed for writing, compiling, and
2018-Present: Continued regular releases debugging Java programs.
with incremental improvements. 4. JDK = JRE + development tools.

Notes by MULTI ATOMS PLUS Youtube Channel


JVM (Java Virtual Machine): Heap: Stores objects and arrays.
1. Purpose: Executes Java bytecode on any Java Stack: Stores frames containing local
device or operating system. variables, operand stack, and frame data for
2. Components: Consists of a class loader, a method calls.
bytecode verifier, and an execution engine. PC Register: Holds the address of the
3. Usage: Runs Java applications and ensures currently executing JVM instruction.
platform independence. Native Method Stack: Manages native
4. JVM = Engine to run Java bytecode. method calls used by Java programs.
3. Execution Engine:
JRE (Java Runtime Environment):
Interpreter: Executes bytecode instructions
1. Purpose: Provides the libraries and JVM one at a time.
necessary to run Java applications. Just-In-Time (JIT) Compiler: Compiles
2. Components: Includes the JVM and a set of bytecode Into native machine code for

s
core libraries but no development tools. improved performance.
3. Usage: Needed for running Java applications Garbage Collector: Manages memory by

lu
without compiling them. reclaiming memory used by objects that are
4. JRE = JVM + libraries to run Java applications no longer reachable.

sP
JVM Architecture 4. Native Method Interface (JNI):
Purpose: Enables Java code to interact with
native applications and libraries written in
other languages like C or C++.
om
5. Native Method Libraries:
Purpose: Provides libraries required for the
native methods that interact with the
underlying hardware and operating system.
At

1.5 Java Source File Stucture


The Java Virtual Machine (JVM) architecture is
designed to execute Java programs and A Java source file structure follows specific
provides platform independence. conventions and typically includes the following
ti

components:
1. Class Loader Subsystem:
1. Package Declaration (optional):
ul

Purpose: Loads class files into memory and Specifies the package name.
performs memory management. Must be the first statement in the file (if
Components: Includes three main parts: present).
M

1. Bootstrap Class Loader: Loads core Java package com.example.myapp;


classes.
2. Extension Class Loader: Loads classes from 2. Import Statements (optional):
the Java Extensions Directory. Import other Java classes or packages.
3. Application Class Loader: Loads classes Must follow the package declaration (if
from the classpath. present) and precede the class definition

2. Runtime Data Areas: import java.util.List;


import java.util.ArrayList;
Method Area: Stores class structures like
metadata, constant pool, method data, and
field data.

Notes by MULTI ATOMS PLUS Youtube Channel


3. Class/Interface Declaration: 4. Operators: Symbols and keywords that
perform operations on variables and values,
The main content of the source file, usually
including arithmetic, relational, logical,
one public class/interface per file.
assignment, and increment/decrement
The class name must match the filename.
operators.
public class MyClass {
// Class content 5. Control Structures: Statements and
} constructs that dictate the flow of program
execution, such as conditional statements (if,
1.6 Compilation Process in Java else, switch) and loops (for, while, do-while).
The compilation process in Java involves
converting human-readable Java source code 6. Methods: Functions that encapsulate
reusable code and perform specific tasks.
into bytecode that the Java Virtual Machine
Methods are defined with a return type, name,

s
(JVM) can execute.
parameters, and a body that contains
executable statements.

lu
7. Classes and Objects: Classes serve as
blueprints or templates for creating objects,

sP
which are instances of classes. Classes
encapsulate data (fields) and behavior
(methods) related to a concept or entity.

8. Inheritance: The mechanism by which one


om
1.7 Java Fundamentals class (subclass or derived class) inherits
"fundamentals" refer to the essential concepts properties and behaviors from another class
and building blocks that form the core of the (superclass or base class). Inheritance promotes
language. code reuse and supports the "is-a" relationship.
1. Basic Syntax and Structure:
At

Keywords: Reserved words in Java that have 9. Polymorphism: The ability of objects to take
a specific meaning in the language syntax on multiple forms. In Java, polymorphism is
(e.g., class, public, void). achieved through method overriding (runtime
polymorphism) and method overloading
Identifiers: Names used for classes,
(compile-time polymorphism).
methods, variables, etc. Must begin with a
ti

letter, a dollar sign $, or an underscore _,


10. Abstraction: The concept of hiding complex
followed by any combination of characters.
ul

implementation details and showing only the


Comments: Used to explain code, ignored by
essential features of an object. Abstraction in
the compiler:
Java can be achieved through abstract classes
1. Single-line: // This is a comment
and interfaces.
M

2. Multi-line: /* This is a multi-line comment */


2. Data Types: The various types of data that can
be used in Java, such as primitive types (int,
double, boolean, etc.) and reference types
(objects and arrays).

3. Variables and Constants: Declarations,


initialization, and usage of variables to store
data temporarily during program execution.
Constants, declared with the final keyword, hold
values that do not change.

Notes by MULTI ATOMS PLUS Youtube Channel


2. Programming Structures in Java
2.3 Methods in Java
2.1 Defining Classes in Java
It is a reusable block of code designed to
Class: A blueprint or template that defines the perform specific tasks. By calling or invoking it,
properties (fields) and behaviors (methods) we execute its functionality without needing to
common to all objects of that type. rewrite the code. This promotes code
public class MyClass { reusability, easy modification, and enhances
// Fields code readability.
// Constructor Method Components
// Methods Access Modifier: Defines the visibility of the
} method (public, private, protected).
Return Type: The type of data the method
2.2 Constructors returns (e.g., int, String, void).
A constructor is a special block of code that runs Method Name: The name used to call the

s
when an object is created. It initializes the method.

lu
object's state. Parameters: Variables passed into the
Rules for creating Java constructor method.
Constructor name must be the same as its Method Body: The code to be executed when
the method is called.

sP
class name
A Constructor must have no explicit return public class MyClass {
type // Method with no return value
public void displayMessage() {
A Java constructor cannot be abstract,
System.out.println("Hello, World!");
static, final, and synchronized
om
}
Types: Default and Parameterised

1. Default Constructors: // Method with a return value


Automatically provided by Java if no public int addNumbers(int a, int b) {
constructors are defined explicitly. return a + b;
}
At

public class MyClass {


public MyClass() { }
// Initialization code
} 2.4 Access Specifier:
} Access specifier or modifier is the access type of
ti

the method. It specifies the visibility of the


2. Parameterized Constructor:: method. Java provides four types of access
Accepts parameters to initialize object fields specifier:
ul

with specific values. Public: The method is accessible by all


public class Car { classes when we use public specifier in our
private String model; application.
M

private int year; Private: When we use a private access


// Parameterized constructor specifier, the method is accessible only in
public Car(String model, int year) { the classes in which it is defined.
this.model = model; Protected: When we use protected access
this.year = year; specifier, the method is accessible within the
}} same package or subclasses in a different
package.
Constructors are fundamental in Java
Default: When we do not use any access
programming for creating and initializing
specifier in the method declaration, Java
objects, ensuring they are ready for use with the
uses default access specifier by default. It is
appropriate state.
visible only from the same package only.

Notes by MULTI ATOMS PLUS Youtube Channel


2.5 Static Members:
Static members belong to the class rather 1. Primitive data types: The primitive data
than to any specific instance of the class. types include boolean, char, byte, short, int,
They are shared among all instances of the long, float and double.
class. 2. Non-primitive data types: The non-primitive
Static members can be accessed directly data types include Classes, Interfaces, and
using the class name without needing to Arrays.
instantiate an object. For More: Click Here
public class MyClass { 2.8 Variables in Java:
public static int staticVar; It is the name of a reserved area allocated in
} memory. In other words, it is a name of the
public class MyClass { memory location. It is a combination of "vary +
public static void staticMethod() { able" which means its value can be changed.

s
System.out.println("This is a static For More: Click Here

lu
method."); int data=50;//Here data is variable
}
} 2.9 Operators:
Arithmetic Operators: +, -, *, /, %

sP
2.6 Final Members: Relational Operators: ==, !=, <, >, <=, >=
Final members are constants that cannot be Logical Operators: &&, ||, !
changed once initialized. Assignment Operators: =, +=, -=, *=, /=
For variables, once a final variable is Increment/Decrement Operators: ++, --
assigned a value, it cannot be reassigned. For More: Click Here
om
For methods, a final method cannot be
overridden by subclasses. 2.10 Control Flow:
For classes, a final class cannot be Java compiler executes the code from top to
subclassed. bottom.
Final members are often used to define Java provides statements that can be used
constants or to prevent further modification
At

to control the flow of Java code. Such


of certain elements in a program. statements are called control flow
public class MyClass { statements.
public final int MY_CONSTANT = 100; It is one of the fundamental features of Java,
} which provides a smooth flow of program.
ti

public class MyClass { Java provides three types of control flow


public final void display() { statements:
ul

System.out.println("This is a final
1. Decision Making Statements -> if statements
method.");
and switch statement
}
2. Loops Statements -> for, while, do while, for
M

}
each loop
public final class FinalClass { 3. Jump Statements -> Break and Continue
// Class implementation Statement
} if statement: Executes a block of code if a
specified condition is true.
2.7 Data Types in Java: int x = 10;
Data types specify the different sizes and values if (x > 0) {
that can be stored in the variable. There are two System.out.println("x is positive");
types of data types in Java: }

Notes by MULTI ATOMS PLUS Youtube Channel


if-else statement: Executes one block of do-while loop: Similar to a while loop, but
code if a condition is true, and another block the block of code is executed at least once.
if it is false. int i = 0;
int x = -10; do {
if (x > 0) { System.out.println("i = " + i);
System.out.println("x is positive"); i++;
} else { } while (i < 5);
System.out.println("x is not positive"); break statement: Exits the nearest enclosing
} loop or switch statement.
else-if ladder: Checks multiple conditions in for (int i = 0; i < 10; i++) {
sequence. if (i == 5) {
int x = 0; break; // Exit the loop when i is 5
if (x > 0) { }

s
System.out.println("x is positive"); System.out.println("i = " + i);
} else if (x < 0) { }

lu
System.out.println("x is negative");
} else { continue statement: Skips the current
System.out.println("x is zero"); iteration of the nearest enclosing loop and

sP
} proceeds with the next iteration.
for (int i = 0; i < 10; i++) {
switch statement: Selects one of many code if (i % 2 == 0) {
blocks to execute based on the value of an continue; // Skip the even numbers
expression. }
om
int day = 3; System.out.println("i = " + i);
switch (day) { }
case 1:
System.out.println("Monday"); 2.11 Arrays in Java::
break; Arrays in Java are used to store multiple values
of the same type in a single variable, rather than
At

case 2:
System.out.println("Tuesday"); declaring separate variables for each value.
break; Arrays are a fundamental part of Java
// Other cases programming and provide a way to organize data
default: efficiently.
ti

System.out.println("Invalid day");
int[] myArray;
break;
myArray = new int[5]; // Array of 5 integers
}
ul

myArray[0] = 1; // Assign values


for loop: Repeats a block of code a specific individually
number of times.
2.12 Strings in Java::
M

for (int i = 0; i < 5; i++) { Strings in Java are objects that represent
System.out.println("i = " + i); sequences of characters. The String class is part
} of the java.lang package, and it provides various
while loop: Repeats a block of code while a methods to manipulate and process strings.
condition is true. String str1 = "Hello, World!";
int i = 0;
String str2 = new String("Hello, World!");
while (i < 5) {
System.out.println("i = " + i); int length = str1.length();
i++; char ch = str1.charAt(0); // 'H'
} int index = str1.indexOf("World"); // 7

Notes by MULTI ATOMS PLUS Youtube Channel


if-else statement: Executes one block of do-while loop: Similar to a while loop, but
code if a condition is true, and another block the block of code is executed at least once.
if it is false. int i = 0;
int x = -10; do {
if (x > 0) { System.out.println("i = " + i);
System.out.println("x is positive"); i++;
} else { } while (i < 5);
System.out.println("x is not positive"); break statement: Exits the nearest enclosing
} loop or switch statement.
else-if ladder: Checks multiple conditions in for (int i = 0; i < 10; i++) {
sequence. if (i == 5) {
int x = 0; break; // Exit the loop when i is 5
if (x > 0) { }

s
System.out.println("x is positive"); System.out.println("i = " + i);
} else if (x < 0) { }

lu
System.out.println("x is negative");
} else { continue statement: Skips the current
System.out.println("x is zero"); iteration of the nearest enclosing loop and

sP
} proceeds with the next iteration.
for (int i = 0; i < 10; i++) {
switch statement: Selects one of many code if (i % 2 == 0) {
blocks to execute based on the value of an continue; // Skip the even numbers
expression. }
om
int day = 3; System.out.println("i = " + i);
switch (day) { }
case 1:
System.out.println("Monday"); 2.11 Arrays in Java::
break; Arrays in Java are used to store multiple values
of the same type in a single variable, rather than
At

case 2:
System.out.println("Tuesday"); declaring separate variables for each value.
break; Arrays are a fundamental part of Java
// Other cases programming and provide a way to organize data
default: efficiently.
ti

System.out.println("Invalid day");
int[] myArray;
break;
myArray = new int[5]; // Array of 5 integers
}
ul

myArray[0] = 1; // Assign values


for loop: Repeats a block of code a specific individually
number of times.
2.12 Strings in Java::
M

for (int i = 0; i < 5; i++) { Strings in Java are objects that represent
System.out.println("i = " + i); sequences of characters. The String class is part
} of the java.lang package, and it provides various
while loop: Repeats a block of code while a methods to manipulate and process strings.
condition is true. String str1 = "Hello, World!";
int i = 0;
String str2 = new String("Hello, World!");
while (i < 5) {
System.out.println("i = " + i); int length = str1.length();
i++; char ch = str1.charAt(0); // 'H'
} int index = str1.indexOf("World"); // 7

Notes by MULTI ATOMS PLUS Youtube Channel


3. Object Oriented Programming:
Object means a real-world entity such as a pen, 3.3 Method Overloading
chair, table, computer, watch, etc. Object-Oriented If a class has multiple methods having same name
Programming is a methodology or paradigm to but different in parameters, it is known as Method
design a program using classes and objects. It Overloading.
simplifies software development and maintenance There are two ways to overload the method in
by providing some concepts: java:
Object By changing number of arguments
Class By changing the data type
Inheritance Code Link: Click Here
Polymorphism 3.4 Method Overriding
Abstraction
If subclass (child class) has the same method as
Encapsulation
declared in the parent class, it is known as method

s
3.1 Class and Object: overriding in Java.
Rules for Java Method Overriding:

lu
Class: A blueprint for creating objects. It defines
a datatype by bundling data and methods that The method must have the same name as in
work on the data. the parent class
public class Car { The method must have the same parameter as

sP
String color; in the parent class.
String model; There must be an inheritance.
int year; Code Link: Click Here
void displayInfo() { 3.5 Encapsulation
om
System.out.println("Model: " + model ); 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
public class Main {
medicines.
public static void main(String[] args) {
We can create a fully encapsulated class in Java
Car myCar = new Car();
by making all the data members of the class
At

myCar.color = "Red"; }}
private. Now we can use setter and getter
methods to set and get the data in it.
3.2 Inheritance
Inheritance is a mechanism where a new class
inherits the properties and behaviors of an The Java Bean class is the example of a fully
encapsulated class.
ti

existing class.
Super Class: The class being inherited from. 3.5 Polymorphism
Polymorphism in Java is a fundamental concept
ul

Sub Class: The class that inherits from the


super class. in object-oriented programming (OOP) that
class Animal {
allows objects of different classes to be treated
as objects of a common superclass. This allows
M

void eat() {
System.out.println("This animal eats food.");
}
for flexibility and extensibility in your code.
}
class Dog extends Animal { (Think of it this way: you have a group of
void bark() { superheroes with different abilities, but they can
System.out.println("The dog barks.");
}} all be referred to as "superheroes".)
public class Main {
public static void main(String[] args) { There are two main types of polymorphism in
Dog dog = new Dog();
Java:
dog.eat(); // Inherited method
dog.bark(); // Sub class method Compile-time Polymorphism: This is
}}
achieved through method overloading.
Runtime Polymorphism: This is achieved
through method overriding.

Notes by MULTI ATOMS PLUS Youtube Channel


3.6 Abstraction
4. Packages:
Abstraction in Java is another core concept of 4.1 Defining Package:
object-oriented programming (OOP), alongside In Java, a package is a mechanism for organizing
encapsulation, inheritance, and polymorphism. It classes, interfaces, and Sub-Packages, which
involves hiding the complex implementation helps in avoiding name conflicts and controlling
details of a system and showing only the essential access. Packages are also used to group related
features of the object. classes and interfaces together, making the code
Abstraction can be achieved in Java using two more modular and easier to manage.
main mechanisms:
Abstract Classes Package in java can be categorized in two form,
Interfaces built-in package and user-defined package.
Abstraction allows you to focus on what an object
does rather than how it does it, promoting code There are many built-in packages such as java,
reusability, maintainability, and flexibility in large lang, awt, javax, swing, net, io, util, sql etc.

s
software systems. Code Link: Click Here

lu
Abstract Classes: It is a class that cannot be package mypack;
instantiated on its own and may contain public class Simple{
abstract methods (methods without a body) as public static void main(String args[]){
System.out.println("package");

sP
well as concrete methods (methods with a
body). Abstract methods serve as }
placeholders for methods that must be }
implemented by subclasses. Abstract classes
4.2 CLASSPATH in Java
can have constructors and instance variables
om
just like any other class. The CLASSPATH is an environment variable used
by the Java compiler (javac) and the Java runtime
abstract class Shape {
(java) to locate classes that are referenced in your
abstract void draw();
program. Setting the CLASSPATH correctly is
}
crucial for compiling and running Java programs
class Circle extends Shape {
that are organized into packages.
At

void draw() {
You can set the CLASSPATH in various ways:
System.out.println("Drawing a circle");
a. Setting CLASSPATH Temporarily
}}
On Windows:
Interfaces: An interface in Java is a blueprint setPATH=.;C:\ProgramFiles\Java\JDK1.6.20
of a class that defines a set of abstract
ti

\bin
methods. Unlike abstract classes, interfaces On Unix/Linux/Mac:
cannot have instance variables or sudo <editor name> /etc/environment
ul

constructors. Classes can implement multiple


interfaces, allowing them to inherit behavior JAVA_HOME = "/usr/lib/jvm/<java folder
from multiple sources. (eg. java-1.8.0-openjdk-amd64>)/bin"
M

interface Animal {
void sound(); export JAVA_HOME
}
class Dog implements Animal { CLASSPATH=".:/usr/lib/jvm/<java
public void sound() { folder>/lib:/home/name/Desktop"
System.out.println("Dog barks");
}} export CLASSPATH

Notes by MULTI ATOMS PLUS Youtube Channel


b. Setting CLASSPATH Permanently
4.5 import and static import statement
On Windows: Java 5.0 introduced static import, also known as
1. Right-click on This PC or My Computer and the tiger version, as a new language feature. Static
select Properties. variables and static members can now be
2. Click on Advanced system settings. accessed directly without having to use class
3. Click on the Environment Variables button. names.
4. In the System variables section, click New or
select the existing CLASSPATH variable and We had normal import statements for every java
click Edit. class before static import was introduced; we
5. Add your paths to the CLASSPATH variable. used class names to call methods and classes.
Below is an example of a normal import for the
List class.
4.3 JAR files in Java
A JAR (Java Archive) is a package file format import java.util.List;

s
typically used to aggregate many Java class files import static java.lang.Math.*;
and associated metadata and resources (text,

lu
images, etc.) into one file to distribute application
software or libraries on the Java platform. Unit-1 is Completed

sP
In simple words, a JAR file is a file that contains a Please Subscribe
compressed version of .class files, audio files,
image files, or directories. We can imagine a .jar Multi Atoms
file as a zipped file(.zip) that is created by using &
WinZip software. Even, WinZip software can be
om
used to extract the contents of a .jar . So you can Multi Atoms Plus
use them for tasks such as lossless data
compression, archiving, decompression, and Playlist: Click Here
archive unpacking. Code Link: Click Here
Create a JAR file
At

jar cf jarfilename inputfiles


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
ti

pack.jar , we can give the command as:


C:\> jar cf pack.jar pack
ul

4.4 Naming Conventions for Java Packages:


For avoiding unwanted package names, we have
M

some following naming conventions which we use


in creating a package.
1. Use Lowercase Letters:
E.g: package com.example.myapp;
2. Period-Delimited Structure:
E.g: package com.example.myapp.controllers;
3. Base Names on Company or Organization:
E.g: package com.example.myapp.services;

Notes by MULTI ATOMS PLUS Youtube Channel

You might also like