Java Unit - 1 First Part
Java Unit - 1 First Part
Using Java
Basic Concept of Java
• Java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming language.
1. Class
2. Object
3. Pillars of OOPs
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Objects and Classes in Java
object in Java
• An entity that has state and behavior is known as an object or An object
is an instance of a class.
• e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical
(tangible and intangible). The example of an intangible object is the
banking system.
An object has three characteristics:
• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.
Class in Java
• A class in Java is a blueprint for creating objects. It defines a datatype by
bundling data and methods that work on the data into one single unit.
Definition: A class is a template or blueprint from which objects are
created. It encapsulates data for the object and methods to manipulate
that data.
Components:
• Fields (Attributes): Variables that hold the state of an object.
• Methods: Functions that define the behavior of an object.
• Constructors: Special methods that are called when an object is
instantiated.
• Pillar 1: Abstraction
• Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components.
• Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details.
Ex: Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed or applying brakes will stop the car, but he does not know how
on pressing the accelerator, the speed is actually increasing. He does not know about the inner
mechanism of the car or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
• In Java, abstraction is achieved by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces.
• Pillar 2: Encapsulation
• It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together the code and the data it manipulates. Another way to think about encapsulation is
that it is a protective shield that prevents the data from being accessed by the code outside
this shield.
• Technically, in encapsulation, the variables or the data in a class is hidden from any other
class and can be accessed only through any member function of the class in which they are
declared.
• In encapsulation, the data in a class is hidden from other classes, which is similar to what
data-hiding does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
• Encapsulation can be achieved by declaring all the variables in a class as private and writing
public methods in the class to set and get the values of the variables.
• Pillar 3: Inheritance
• Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism
in Java by which one class is allowed to inherit the features of another class. We are achieving
inheritance by using extends keyword.
• Terminologies:
• Superclass: The class whose features are inherited is known as superclass (also known as base
or parent class).
• Subclass: The class that inherits the other class is known as subclass (also known as derived or
extended or child class).
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Pillar 4: Polymorphism(Many Forms)
Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) in Java. It refers to
the ability of a single interface to represent different underlying forms (data types). In simpler terms,
polymorphism allows one interface to be used for a general class of actions. The specific action is
determined by the exact nature of the situation.
Polymorphism can be classified into two types:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)
Method Overriding: Involves creating a method in a subclass with the same signature as a method in its
superclass, thereby replacing or extending the behavior of the superclass method.
Applications Of Java
1. Simulations and Modeling
Java is an excellent choice for developing simulations and modeling applications due to its robustness,
portability, and extensive libraries.
2. Real-Time Systems
Real-time systems require timely and predictable responses to events. Java, with its Real-Time Specification
for Java (RTSJ), is used to develop such systems.
4.Object-Oriented Databases
Object-oriented databases (OODBs) store data as objects, making them more aligned with object-oriented
programming principles compared to traditional relational databases.
Applications: Used where complex data structures need to be stored and retrieved efficiently, such as in
engineering simulations, CAD systems, and multimedia applications.
5.Neural Networks and Parallel Programming
Neural Networks
In Java, neural networks can be implemented and utilized through various libraries and frameworks that
provide the necessary tools for training, testing, and deploying models. Here are some key aspects of
neural networks in the context of Java
Parallel Programming
Parallel programming involves executing multiple tasks simultaneously, leveraging multiple processors
or cores to improve performance.
When Java came into being, a lot of developers were already working in the then programming language C++. In order to
tackle the migration problem, the Java syntax is actually very similar to the C++ syntax which made it easier for developers
to migrate from C++ to Java.
4.Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
5.Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java robust.
6.Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
7.Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
8.Interpreted programming
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
9.Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.
10.Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares
a common memory area. Threads are important for multi-media, Web applications, etc.
11.Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.
Structure Of Java Program
Java is an object-oriented programming,
platform-independent, and secure
programming language that makes it popular.
Using the Java programming language, we
can develop a wide variety of applications.
2.The package declaration is optional. It is placed just after the documentation section. In this section, we declare the
package name in which the class is placed. Note that there can be only one package statement in a Java program. It must be
defined before any class and interface declaration. It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these classes package belongs to a single parent directory. We
use the keyword package to declare the package name.
For example:
3.Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of a particular package, we
need to import that class. The import statement represents the class stored in the other package. We use the import
keyword to import the class. It is written before the class declaration and after the package statement. We use the import
statement in two ways, either import a specific class or import all classes of a particular package. In a Java program, we
can use multiple import statements. For example:
4.Interface Section
It is an optional section. We can create an interface in this section if required. We use the interface keyword to create an
interface. An interface is a slightly different from the class. It contains only constants and method declarations. Another
difference is that it cannot be instantiated. We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword. For example:
5.Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java program. A
Java program may conation more than one class definition. We use the class keyword to define the class. The class is a
blueprint of a Java program. It contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:
Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive Data Types
1.byte 1 byte
2.short 2 bytes
3.int 4 bytes
5.float 4 bytes
6.double 8 bytes
• Double-precision 64-bit IEEE 754 floating point.
• Provides greater precision for decimal values, with 15 significant decimal digits.
• Default type for decimal values, e.g., 3.14.
7.boolean
• Has only two possible values: true and false.
• Used for simple flags that track true/false conditions.
• Commonly used in control flow statements like if-else and loops.
8.char 1 or 2 bytes
2.Interfaces
3.Arrays
• Container objects that hold a fixed number of values of a single type.
• The length of an array is established when it is created and cannot be changed.
• Access elements using an index, starting at 0.
Strings
Ex:
int a=10;
float b=10.8;
boolean c=true;
Types of Variables
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
Definition: Local variables are declared inside a method, constructor, or block and are only
accessible within that method, constructor, or block.
2.Instance Variables (Non-Static Fields)
Instance variables are declared in a class but outside any method, constructor, or block. They are created when an object is
instantiated and are destroyed when the object is destroyed. They are associated with instances of the class.
3.Static variables
Definition: Class variables are declared with the static keyword inside a class but outside any method, constructor, or block.
They are associated with the class itself rather than instances of the class.
Operators in Java
In Java, operators are special symbols that perform operations on variables and values. Java operators can be
classified into several categories:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
* ,/ ,% ,+ ,-
2.Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.
3. ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators.
• Post-Increment: Value is first used for computing the result and then incremented.
• Pre-Increment: Value is incremented first, and then the result is computed. ++ , Increments by 1.
Post-Increment: Uses value first, then increments.
Pre-Increment: Increments first, then uses value.
4. – – : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators.
• Post-decrement: Value is first used for computing the result and then decremented. -- , Decrements by 1.
• Pre-Decrement: The value is decremented first, and then the result is computed. Post-Decrement: Uses value first, then
decrements.
Pre-Decrement: Decrements first, then uses value.
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
6.Ternary operator/Conditional Operator
• It has three operands and hence the name Ternary.
• The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute
the statements after the ‘:’.
7. Bitwise Operators(&,|,^,~)
• These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the
integer types. They are used when performing update and query operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the
input value, i.e., with all bits inverted.
Control Statement
Control statements decide the flow (order or sequence of execution of statements) of a Java program. In Java, statements are
parsed from top to bottom. Therefore, using the control flow statements can interrupt a particular section of a program based
on a certain condition.
1.Selection statements
In Java, selection statements are used to execute different blocks of code based on specified conditions. There are primarily
two types of selection statements:
1.if-else Statement:
• The if-else statement executes a block of code if a specified condition is true. If the condition evaluates to false, an
optional else block of code can be executed.
Ex
2. if-else:
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it
won’t. But what if we want to do something else if the condition is false? Here comes the else statement. We can use the
else statement with the if statement to execute a block of code when the condition is false.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Ex
3.else-if ladder
An "else-if ladder" in Java is a sequence of else if statements that follow an initial if statement, providing multiple conditions
to be evaluated in sequence until a matching condition is found or the default else block is executed.
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
4. nested-if:
A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if
statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
5. 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.
Syntax
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Looping Statement
1.For loop
2.While loop
3.do while loop
4.Nested loop
1.For Loop
In Java, a for loop is used to iterate a block of code a certain number of times or over elements of an array or collection.
There are two main types of for loops in Java: the traditional for loop and the enhanced for-each loop.
Syntax:
Ex:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
2.while loop
In Java, a while loop repeatedly executes a block of code as long as a specified condition is true. The while loop evaluates
the condition before executing the code block, so if the condition is false initially, the code block may not execute at all.
Syntax:
while (condition) {
// Code block to be executed
}
Ex:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
3.do while loop
A do-while loop in Java is similar to a while loop, but the key difference is that the do-while loop guarantees
that the code block will be executed at least once. This is because the condition is evaluated after the code
block is executed.
Syntax:
do {
// Code block to be executed
} while (condition);
Ex:
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}
}
4.Nested Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely
whenever outer loop executes.
Ex:
public class NestedForExample {
public static void main(String[] args) {
for(int i=1;i<=3;i++) //loop of i
{
for(int j=1;j<=3;j++) //loop of j
{
System.out.println(i+" "+j);
}
}
}
}
Jump Statements
Java, jump statements are used to transfer control to another part of the program. Java provides three primary jump
statements: break, continue. Each serves a different purpose and is used in different contexts.
• The continue statement skips the current iteration of a loop and proceeds with the next iteration.
• The break statement is used to terminate a loop (or a switch statement) immediately and transfer control to the next
statement after the loop.
Ex:
public class Main {
public static void main(String[] args) {
// Example with break and continue in a nested loop
for (int i = 0; i < 3; i++) {
System.out.println("Outer loop i = " + i);
for (int j = 0; j < 5; j++) {
if (j == 2) {
continue; // Skip the rest of the inner loop when j is 2
}
if (j == 4) {
break; // Exit the inner loop when j is 4
}
System.out.println(" Inner loop j = " + j);
}
}
}
}
Methods in Java
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.
Create a Method
• A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Ex:
import java.util.Scanner;
public class School{
void display()
{
System.out.println("hello world");
}
void display(int a)
{
System.out.println("welocome");
}
System.out.println(Math.max(5,8));
System.out.println(Math.min(5,8));
System.out.println(Math.sqrt(2));
System.out.println(Math.abs(-8.7));
System.out.println(Math.random());// from 0.0 to 1.0
int randomNum=(int)(Math.random()*101);//if wanted between 1 to 100 and the result is in float to convert to int we use type casting
System.out.println(randomNum);
}
}
Arrays in Java
• Array is a collection of Homogeneus element/store multiple values of the same type in a single variable.
Arrays are indexed, with the first element at index 0.
• Arrays may be stored in contiguous memory [consecutive memory locations].
Array Declaration:
int[] myArray;
Initialization:
myArray = new int[8]; // Creates an array of 8 integers
One Dimentional Array