0% found this document useful (0 votes)
3 views39 pages

Java

The document provides an overview of Java programming, covering syntax, variables, data types, operators, strings, arrays, and object-oriented programming concepts such as constructors and access modifiers. It explains the use of the main method, variable types, type casting, and various operators, as well as methods for string manipulation and mathematical operations. Additionally, it discusses encapsulation and the importance of access modifiers in controlling data visibility.

Uploaded by

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

Java

The document provides an overview of Java programming, covering syntax, variables, data types, operators, strings, arrays, and object-oriented programming concepts such as constructors and access modifiers. It explains the use of the main method, variable types, type casting, and various operators, as well as methods for string manipulation and mathematical operations. Additionally, it discusses encapsulation and the importance of access modifiers in controlling data visibility.

Uploaded by

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

JAVA

 JAVA SYNTAX :

EXAMPLE EXPLAINATION :
Every line of code that runs in Java must be inside a class. The class
name should always start with an uppercase first letter. In our
example, we named the class Main.

 Any code placed inside the main() method will be executed

Inside the main method println() function is used to print a line of text.

VARIABLES IN JAVA:
 In Java, there are different types of variables, for example:
 String - stores text, such as "Hello". String values are surrounded by
double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or
-123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

EXAMPLE :

 Constants (final keyword):


 When you do not want a variable's value to change, use
the final keyword.
 A variable declared with final becomes a constant, which means
unchangeable and read-only.

 Eg.

 Java Data Types


 Data types are divided into two groups:
Primitive data types -
includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes (you
will learn more about these in a later chapter)
NOTE : Once a variable is declared with a type, it cannot change to
another type later in the program.
Eg.

2
The Var keyword :
 The var keyword was introduced in Java 10 (released in 2018).
 The var keyword lets the compiler automatically detect the type of a
variable based on the value you assign to it.
 This helps you write cleaner code and avoid repeating types,
especially for long or complex types.
 For example, instead of writing int x = 5;, you can write:

NOTE :
1. var only works when you assign a value at the same time (you
can't declare var x; without assigning a value):

2. Once the type is chosen, it stays the same. See example below:

JAVA TYPE CASTING:

3
 Type casting means converting one data type into another. For
example, turning an int into a double.
 In Java, there are two main types of casting:
 Widening Casting (automatic) - converting a smaller type to a
larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manual) - converting a larger type to a smaller


type size
double -> float -> long -> int -> char -> short -> byte

Widening Casting:
Widening casting is done automatically when passing a
smaller size type into a larger size type.
This works because there is no risk of losing information. For
example, an int value can safely fit inside a double:

Narrowing Casting:
Narrowing casting must be done manually by placing the type in
parentheses () in front of the value.

This is required because narrowing may result in data loss (for example,
dropping decimals when converting a double to an int):

4
JAVA OPERATORS :
I)Arithmetic Operators
Operato Name
r Description Example

+ Addition Adds together x+y


two values
- Subtraction Subtracts one x-y
value from
another
* Multiplicati Multiplies two x*y
on values
/ Division Divides one x/y
value by another
% Modulus Returns the x%y
division
remainder
++ Increment Increases the ++x
value of a
variable by 1

5
-- Decrement Decreases the --x
value of a
variable by 1

EXAMPLE:

II) ASSIGNMENT OPERATOR:


Example :

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3

6
%= x %= 3 x = x %3
&= x &= 3 x = x &3
|= x |= 3 x = x |3
^= x ^= 3 x = x ^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

iii) COMPARISN OPERATORS :


 Operator  Name  Example

 ==  Equal to  x == y

 !=  Not equal  x != y

 >  Greater than  x>y

 <  Less than  x<y

 >=  Greater than or  x >= y


equal to

 <=  Less than or equal  x <= y


to

IV) LOGICAL OPERATORS:

7
Operator Name Description Example
&& Logical and Returns true x < 5 && x
if both < 10
statements
are true
|| Logical or Returns true x < 5 || x <
if one of the 4
statements
is true

! Logical not Reverse the !(x < 5 && x


result, < 10)
returns false
if the result
is true

JAVA OPERATOR PRECCEDENCE :


 Here are some common operators, from highest to lowest priority:
 () - Parentheses
 *, /, % - Multiplication, Division, Modulus
 +, - - Addition, Subtraction
 >, <, >=, <= - Comparison
 ==, != - Equality
 && - Logical AND
 || - Logical OR
 = - Assignment

JAVA STRING :

8
 Strings are used for storing text.
 A String variable contains a collection of characters surrounded by
double quotes (""):
Eg.

I) STRING LENGTH :

 A String in Java is actually an object, which means it


contains methods that can perform certain operations on
strings.
 For example, you can find the length of a string with
the length() method:

OUTPUT = 26
II) charAt(int index) : Returns character at given index.

iii) equalsIgnore() : Ignores case .

9
iv) equals() : checks content equally.

v)compareTo () : Lexicographical comparison .

 vi) compareToIgnoreCase(String s)
 Ignores case.
 "Java".compareToIgnoreCase("java"); // 0

 3️⃣ Searching Methods


 🔹 contains(CharSequence s)
 Checks if substring exists.
 "Java Programming".contains("Java"); // true
 🔹 indexOf(String s)
 Returns first index.

10
 "banana".indexOf("a"); // 1
 🔹 lastIndexOf(String s)
 Returns last index.
 "banana".lastIndexOf("a"); // 5
 🔹 startsWith(String prefix)
 "Java".startsWith("Ja"); // true
 🔹 endsWith(String suffix)
 "Java".endsWith("va"); // true

 4️⃣ Case Conversion Methods


 🔹 toUpperCase()
 "java".toUpperCase(); // JAVA
 🔹 toLowerCase()
 "JAVA".toLowerCase(); // java

 5️⃣ Trimming & Cleaning


 🔹 trim()
 Removes leading & trailing spaces.
 " Java ".trim(); // Java
 🔹 strip() (Java 11+)
 Unicode-aware trim.
 " Java ".strip();
 🔹 stripLeading()

11
 " Java".stripLeading();
 🔹 stripTrailing()
 "Java ".stripTrailing();

 6️⃣ Replacing Methods


 🔹 replace(char old, char new)
 "java".replace('a', 'o'); // jovo
 🔹 replace(CharSequence old, CharSequence new)
 "java".replace("ja", "ka"); // kava
 🔹 replaceAll(String regex, String replacement)
 Uses regex.
 "abc123".replaceAll("[0-9]", "");
 🔹 replaceFirst(String regex, String replacement)
 "banana".replaceFirst("a", "o"); // bonana

 7️⃣ Substring & Splitting


 🔹 substring(int beginIndex)
 "Programming".substring(3); // gramming
 🔹 substring(int begin, int end)
 "Programming".substring(0, 7); // Program
 🔹 split(String regex)
 String[] arr = "Java Python C".split(" ");

12

CHECKING EMPTY/BLANK:
🔹 isEmpty()
Checks length = 0.
"".isEmpty(); // true

🔹 isBlank() (Java 11+)


Checks spaces too.
" ".isBlank(); // true

ADDING NUMBERS AND STRING:


 Java uses the + operator for both addition and
concatenation.
 Numbers are added. Strings are concatenated.

If you add one string and one int ,result will be String .

JAVA MATH CLASS :


I) [Link] (x,y) :
The [Link](x,y) method can be used to find the
highest value of x and y.
ii) [Link] :

13
The [Link](x,y) method can be used to find the lowest
value of x and y.
iii)[Link]():
The [Link](x) method returns the square root of x.
IV) [Link](x)
The [Link](x) method returns the absolute (positive) value
of x:
V) [Link](x, y)
The [Link](x, y) method returns the value of x raised to
the power of y.

 Rounding Methods
 Java has several methods for rounding numbers:
 [Link](x) - rounds to the nearest integer
 [Link](x) - rounds up (returns the smallest integer
greater than or equal to x)
 [Link](x) - rounds down (returns the largest integer
less than or equal to x)

ARRAYS IN JAVA:

14
 Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
 To declare an array, define the variable type with square
brackets [ ] .
 Eg. String[] cars;
CREATE EMPTY ARRAY FOR USER INPUT:
You can also create an array by specifying its size with new. This
makes an empty array with space for a fixed number of
elements, which you can fill later.
Eg.

ARRAY LENGTH :
To find out how many elements an array has, use
the length property.
Eg.

MULTIDIMENTIONAL ARRAY:

15
 A multidimensional array is an array that contains other
arrays.
 You can use it to store data in a table with rows and
columns.
 To create a two-dimensional array, write each row inside its
own curly braces.
 Eg.
 int[][] myNumbers = { {1, 4, 2}, {3, 6, 8} };
Note: Notice how rows can have different lengths - In this
example, the second row has more elements than the first,
and that's perfectly valid in Java.
Eg.

LOOP THROUGH MULTIDIMENTIONAL ARRAY:

FOR LOOP
 int[][] myNumbers = { {1, 4, 2}, {3, 6, 8, 5, 2} };

 for (int row = 0; row < [Link]; row++) {
 for (int col = 0; col < myNumbers[row].length; col++) {

16
 [Link]("myNumbers[" + row + "][" + col + "] =
" + myNumbers[row][col]);
 }
 }
FOR EACH LOOP

OBJECT ORIENTED PROGRAMMING (OOP)


Constructor :
A special method which initialise the object it is first created. It is special because
It has the same name as that of the class name .
It doesn’t have any return type, not even [Link] generally defined in public
section .

Type of Constructor :
[Link] Constructor
[Link] Constructor

17
[Link] Constructor :

Here when we declair the line


Main myObj = new Main() the compliler call a constructor which is default .
It is supplied by the compiler,No nned to define explicitely.
[Link] Constructor :

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor,

18
we pass aparameter to the constructor (5), which will set the value of x to 5.
 Java this Keyword
 The this keyword in Java refers to the current object in a method or
constructor.
 The this keyword is often used to avoid confusion when class attributes have
the same name as method or constructor parameters.

 Accessing Class Attributes


 Sometimes a constructor or method has a parameter with the same name as
a class variable. When this happens, the parameter temporarily hides the
class variable inside that method or constructor.
 To refer to the class variable and not the parameter, you can use
the this keyword.

19
Access Modifiers
 For classes, you can use either public or default.

Modifier  Description

public  The class is accessible by any other class

default  The class is only accessible by classes in the same package.


 This is used when you don't specify a modifier.

 For attributes, methods and constructors, you can use the one of the
following:

 Modifier  Description

 public  The code is accessible for all classes

 private  The code is only accessible within the declared class

 default  The code is only accessible in the same package.


 This is used when you don't specify a modifier.

 protected  The code is accessible in the same package and subclasses.

Non-Access Modifiers

20
1. Non-access modifiers do not control visibility (like public or private), but
instead add other features to classes, methods, and attributes.
2. The most commonly used non-access modifiers are final, static, and abstract.

 Final
3. If you don't want the ability to override existing attribute values, declare
attributes as final:
Example
public class Main {
final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final
variable
[Link] = 25; // will generate an error: cannot assign a value to a final
variable
[Link](myObj.x);
}
}
2. Static
A static method belongs to the class, not to any specific object. This means you
can call it without creating an object of the class.
Example
A simple example showing how to call a static method directly:
public class Main {
// Static method

21
static void myStaticMethod() {
[Link]("Static methods can be called without creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
[Link](); // Or call it using the class name
}
}
3. Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass.

22
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
from users. To achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of
a private variable

Get and Set


You learned from the previous chapter that private variables can only
accessed within the same class (an outside class has no access to it). However,
it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name
of the variable, with the first letter in upper case:

23
Example

Inheritence
Inheritance in Java is a core OOP concept that allows a class to acquire
properties and behaviors from another class. It helps in creating a new class
from an existing class, promoting code reusability and better organization.
A subclass can reuse the fields and methods of the parent class without
rewriting the code
A subclass can add its own fields and methods or modify existing ones to
extend functionality.

24
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It
inherits the properties and behavior of a single-parent class. Sometimes, it is
also known as simple inheritance.

25
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also acts as the base class for other classes.

26
3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single
base class. i.e. more than one derived class is created from a single base class.
For example, cars and buses both are vehicle.

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java,
we can achieve multiple inheritances only through Interfaces.

27
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can
achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance.

Polymorphism
The word polymorphism means having many forms, and it comes from the
Greek words poly (many) and morph (forms), this means one entity can take
many forms. In Java, polymorphism allows the same method or object to
behave differently based on the context, specially on the project's actual
runtime class.

28
Method Overloading
In Java it allows a class to have multiple methods with the same name but
different parameters, enabling compile-time polymorphism.
 Methods can share the same name if their parameter lists differ.
 Cannot overload by return type alone; parameters must differ.
 The compiler chooses the most specific match when multiple methods
could apply.
The different ways of method overloading in Java are mentioned below:
1. Changing the Number of Parameters
Method overloading can be achieved by changing the number of parameters
when passing to different methods.
2. Changing Data Types of Parameters
In many cases, methods can be considered overloaded if they have the same
name but have different parameter types, methods are considered to be
overloaded.
3. Changing the Order of Parameters
Method overloading can also be implemented by rearranging the parameters
of two or more overloaded methods.

29
Overriding in Java
 When a subclass provides a specific implementation for a method that is
already defined in its parent class, it is called method overriding. The
overridden method in the subclass must have the same name, parameters,
and return type as the method in the parent class.
 Rules for Method Overriding
 Name, parameters, and return type must match the parent method.
 Java picks which method to run at run time, based on the actual object
type, not just the reference variable type.
 Static methods cannot be overridden.
 The @Override annotation catches mistakes like typos in method names.

30
 Abstraction in Java
Abstraction in Java is the process of hiding internal implementation details and
showing only essential functionality to the user. It focuses on what an object does
rather than how it does it.
 Abstraction hides the complex details and shows only essential features.

31
 Abstract classes may have methods without implementation and must be
implemented by subclasses.
 By abstracting functionality, changes in the implementation do not affect
the code that depends on the abstraction.
 We can implement abstaraction by
 Abstract Classes (Partial Abstraction)
 Interface (provides abstraction for behavior, may contain default or
static methods)

Interface
 An interface is a blueprint for a class that defines a set of methods a class
must implement. It is commonly used to achieve abstraction in Java. Modern
Java interfaces can contain abstract methods, constants, and also default or
static methods with implementations.
 Implementation: To implement an interface we use the keyword
“implements” with class.

Relationship Between Class and Interface


A class can extend another class and similarly, an interface can
extend another interface. However, only a class can implement an
interface and the reverse (an interface implementing a class) is not
allowed.

 Use a Class when:


 Use a class when you need to represent a real-world entity
with attributes (fields) and behaviors (methods).

32
 Use a class when you need to create objects that hold state
and perform actions
 Classes are used for defining templates for objects with
specific functionality and properties.
 Use an Interface when:
 Use an interface when you need to define a contract for
behavior that multiple classes can implement.
 Interface is ideal for achieving abstraction and multiple
inheritance.

1. Aggregation (Weak Association)


Aggregation represents a “has-a” relationship where one class contains a
reference to another class, but both can exist independently.
 It is a weak relationship
 Objects have independent lifecycles
 One object can exist without the other

33
 Example: A Department has Employees, but employees can exist even if
the department is removed
2. Composition (Strong Association)
Composition is a strong form of association where one class owns another
class. If the parent object is destroyed, the child object also gets destroyed.
 It is a strong relationship
 Objects have dependent lifecycles
 Child object cannot exist without the parent
 Example: A Car has an Engine

Java List Interface


The List interface is part of the Java Collections Framework and represents
an ordered collection of elements.
You can access elements by their index, add duplicates, and maintain the
insertion order.
Since List is an interface, you cannot create a List object directly.
Instead, you use a class that implements the List interface, such as:
 ArrayList - like a resizable array with fast random access
 LinkedList - like a train of cars you can easily attach or remove

34
Java ArrayList
 An ArrayList is like a resizable array.
 It is part of the [Link] package and implements the List interface.
 The difference between a built-in array and an ArrayList in Java, is that the
size of an array cannot be modified (if you want to add or remove elements
to/from an array, you have to create a new one). While elements can be
added and removed from an ArrayList whenever you want.

35
Wrapper Class :
 In Java, wrapper classes allow primitive data types to be represented as
objects. This enables primitives to be used in object-oriented features such as
collections, generics, and APIs that require objects.
 Each wrapper class encapsulates a corresponding primitive value inside an
object (e.g., Integer for int, Double for double).
 Java provides wrapper classes for all eight primitive data types to support
object-based operations.
 Example: Converting Primitive to Wrapper (Autoboxing)

 Autoboxing and Unboxing


1. Autoboxing
 The automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing. For example:
conversion of int to Integer, long to Long, double to Double, etc.
 Java program to demonstrate the automatic conversion of primitive to
wrapper class (Autoboxing).

Example :

36
2. Unboxing
Unboxing is the automatic conversion of a wrapper class object back into its
corresponding primitive type.

37
38
Common methods of wrapper class

39

You might also like