0% found this document useful (0 votes)
2 views15 pages

Java Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, and polymorphism, emphasizing their benefits such as modularity and reusability. It also discusses Java's features, structure, and the implementation process of Java programs, including variable declaration and command line arguments. Additionally, it covers the Java Virtual Machine (JVM) and the concept of symbolic constants.
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)
2 views15 pages

Java Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, and polymorphism, emphasizing their benefits such as modularity and reusability. It also discusses Java's features, structure, and the implementation process of Java programs, including variable declaration and command line arguments. Additionally, it covers the Java Virtual Machine (JVM) and the concept of symbolic constants.
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 – I

FUNDAMENTALS OF OBJECT – ORIENTED PROGRAMMING


Introduction of Object-Oriented Programming
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in
programming. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.
OOPs Concepts:
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
● Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can be
accessed and used by creating an instance of that class. It represents the set of properties or methods
that are common to all objects of one type. A class is like a blueprint for an object.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object is an
instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
3. Data Abstraction: Data abstraction is one of the most essential and important features of object-
oriented programming. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation.
4. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. As in encapsulation, the data in a
class is hidden from other classes, so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a class to
derive properties and characteristics from another class is called Inheritance. When we write a class,
we inherit properties from other classes.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form.

7. Dynamic Binding:
Linking a procedure call to the code to be executed only at runtime, often associated with
polymorphism and inheritance
8. Message Passing:
Objects communicate by sending and receiving information, similar to how people pass messages.
Benefits of OOPs

1. Modularity
● OOP promotes the division of a software program into distinct modules or classes, each
representing a specific component or functionality.
● This modularity makes the code easier to manage, maintain, and understand.
2. Reusability
● OOP encourages code reuse through inheritance and composition.
● By creating new classes from existing ones, developers can leverage pre -existing code,
reducing redundancy and effort.
3. Improved Maintainability
● OOP's modularity and encapsulation make updating, modifying, and debugging code easier.
● Changes in one part of the system have minimal impact on other parts, enhancing
maintainability.
4. Ease of Troubleshooting
● OOP simplifies the process of debugging and troubleshooting by isolating functionality into
separate classes.
● Problems can be localized and resolved more efficiently.
5. Real-World Modelling
● OOP helps in the modelling of real-world entities and relationships in software.
● This makes the code more intuitive and aligned with human understanding of the problem
domain.
Application of OOPs

Java has a wide range of applications across various domains. Java is also used in areas like
gaming, big data technologies, cloud computing, and embedded systems.

1. Mobile Applications: Java is the primary language for developing Android applications.
2. Web Applications: Java is widely used for developing web applications and web services
using frameworks like Spring and Jakarta EE.
3. Enterprise Applications: Java is a popular choice for building complex, large-scale
enterprise applications due to its robustness, scalability, and security features.
4. Scientific Applications: Java's stability and security make it suitable for developing
applications that handle large amounts of scientific data.
5. Gaming Applications: Java, along with game engines like LibGDX, is used for
developing both 2D and 3D games.
6. Big Data Technologies: Java plays a crucial role in big data technologies like Hadoop and
Apache Kafka.
7. Cloud-based Applications: Java is used in various cloud platforms and services.

Java Features
Java programming language was initially developed to work on embedded systems, settop boxes,
television. So, by requirements, it was initially designed to work on varied platforms. Over the period
of multiple years, Java evolved to become one of the most popular language used to develop internet-
based applications.
Java is a feature rich language and with every new version, it is continuously evolving. It is widely
used across billions of devices. Following are the main features of the Java language -
● Object Oriented
● Platform Independent
● Simple
● Secure
● Architecture-neutral
● Portable
● Robust
● Multithreaded
● Interpreted
● High Performance
● Distributed
● Dynamic
Structure of the Java Program

When we are writing any program in any language, we need to follow a standard structure for writing
the program, which is recommended by the language experts. A Java program may contain many
classes, of which only one class will have a main method. The class will contain data members and
methods that operate on the data members of the class.
Basic Blocks of a Java Program
To write a Java program, we first need to define classes and then put them together. Generally, a
standard Java program consists of the following blocks, as shown below:

package list;
public class ClassName {
// Data members
// Constructor functions
// User-defined methods
public static void main(String[] arguments) {
// Block of statements
}
}

Java Tokens
Java Tokens are the smallest individual building block or smallest unit of a Java program; the Java
compiler uses it for constructing expressions and statements. Java program is a collection of different
types of tokens, comments, and white spaces.
There are various tokens used in Java:
1. Reserved Keywords:
Reserved words with predefined meanings. Ex: public, class, static, void, int, if, else,
for, and while.

2. Identifiers:
Names used for variables, methods, classes, packages, etc. myVariable, calculateSum,
HelloWorld (class name), main (method name), and args (parameter name).

3. Literals:
Constant values used directly in the code.
● Integer literals: 42, 100
● Floating-point literals: 3.14, 2.5f
● Character literals: 'A', '@'
● String literals: "Hello Java", "Programming"
● Boolean literals: true, false
4. Operators:
Symbols that perform specific operations on operands.
● Arithmetic: +, -, *, /, %
● Relational: ==, !=, <, >, <=, >=
● Logical: &&, ||, !
● Assignment: =, +=, -=

5. Separators:
Used to separate different parts of the code and define structure.
● ( ) (parentheses for method calls, expressions)
● { } (curly braces for blocks of code)
● [ ] (square brackets for arrays)
● ; (semicolon to terminate statements)
● , (comma to separate elements in lists)
● . (dot operator for accessing members)

Java Statements

In Java, statements are instructions that tell the program what actions to perform. They form the
fundamental building blocks of a Java program, appearing inside methods and classes to describe the
program's activities.
There are several types of statements in Java:
[Link] Statements:
These statements perform an action and often involve expressions that produce values. They are
formed by terminating an expression with a semicolon (;).
Examples:
● int x = 10; (Assignment statement)
● [Link]("Hello"); (Method call statement)
● new MyObject(); (Object creation statement)

[Link] Statements:
These statements are used to declare variables or other program elements, specifying their data type
and name.
Example:
● String name;
● double price = 99.99;

[Link] Flow Statements:


These statements determine the order in which other statements are executed, allowing for decision -
making, looping, and jumping within the program.
● Decision-Making Statements:
● Looping Statements (Iteration Statements)
● Jump Statements
Implementing a Java Program

Steps to Implement a Java Program


The implementation of a Java program involves the following steps. They include:
● Creating the program
● Compiling the program
● Running the program

1. Create a Java Program


Java programs can be written in a text editor (Notepad, VS Code) or an IDE (IntelliJ, Eclipse,
NetBeans).

// Simple Java Hello World Program


public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello, World");
}
}

Note: Save the file as [Link]

2. Compile the Java Program


To compile the program, we must run the Java compiler (javac), with the name of the source file on
the "command prompt" (Windows) or "Terminal" (Mac/Linux) as follows:

javac [Link]

Note:
Before running the command, make sure you navigate to the correct directory where
your [Link] file is saved.
3. Run the Java Program
We need to use the Java Interpreter to run a program. Execute and compile Java program with below
command:

java HelloWorld

Output:

Hello, World

Java Virtual Machine

A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well
as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by
a specification that formally describes what is required in a JVM implementation. Having a
specification ensures interoperability of Java programs across different implementations so that
program authors using the Java Development Kit (JDK) need not worry about idiosyncrasies of the
underlying hardware platform.
The JVM reference implementation is developed by the OpenJDK project as open source code and
includes a JIT compiler called HotSpot. The commercially supported Java releases available
from Oracle are based on the OpenJDK runtime. Eclipse OpenJ9 is another open source JVM for
OpenJDK.
Command Line Arguments

In Java, command line arguments is a way to pass inputs to the java program during application
execution. Command line arguments can be passed by multiple ways to Java application or program.
Most commonly, command line arguments are passed from console where a java program is executed.
command-line arguments, provided during program execution, are captured in the main() method as
a string array.

Passing & Accessing Command Line Arguments


Consider the below syntax of passing command-line arguments:

javac [Link]
java tester arg1 arg2 arg3

Here we've compiled one java file namely [Link] and while running the tester class using java, we're
passing three arguments which are separated by space. We can pass any number of command line
arguments to java program. The Java Virtual Machine (JVM) encapsulates these inputs into
the args[] array. We can check the number of arguments passed using [Link]. In case no command
line argument is present, then this array is empty.

class Tester {
public static void main(String[] args){
...
}
}

We can pass Strings, integers and any other primitive value using command line arguments. Each
argument passed is available in the array in the order of entry, starting from args[0].

Constants, Variables and Data types


In Java, constants, variables, and data types are fundamental concepts for storing and
manipulating data within a program.
[Link]:
Variables are named storage locations in memory that hold data. Their values can change
during program execution. In Java, variables must be declared with a specific data type
before use.
● Local Variables:
Declared inside a method, constructor, or block. Their scope is limited to that specific
block.
● Instance Variables:
Declared within a class but outside any method, constructor, or block. They belong to an
object (instance) of the class.
● Static (Class) Variables:
Declared within a class with the static keyword. They belong to the class itself, not to any
specific object, and are shared among all instances of the class.
[Link]:
Constants are variables whose values, once assigned, cannot be changed during the program's
execution. In Java, constants are typically declared using the final keyword. They are often
also declared as static to make them accessible directly via the class name and in public for
wider accessibility. By convention, constant names are written in all uppercase letters with
underscores separating words.
[Link] Types:
Data types define the kind of data a variable can hold and the operations that can be
performed on it. Java has two main categories of data types:
● Numeric: byte, short, int, long (for whole numbers); float, double (for floating-point
numbers).
● Character: char (for single characters).
● Boolean: boolean (for true or false values).
● String: Used to store sequences of characters (text). String is a class, not a primitive
data type.
● Arrays: Used to store collections of elements of the same data type.
● Classes and Interfaces: User-defined data types that encapsulate data and behavior.

Declaration of Variables
Variable declaration in Java involves specifying the variable's data type and its name. This
informs the compiler about the type of data the variable will store and reserves the
appropriate amount of memory.
Syntax:

dataType variableName;

Example:
int age; // Declares an integer variable named 'age'
String name; // Declares a String variable named 'name'
Giving Values to Variables (Initialization and Assignment)
Values can be given to variables during declaration (initialization) or later through
assignment.
Initialization (during declaration):
dataType variableName = initialValue;

Example:
int age = 30; // Declares and initializes 'age' to 30
String name = "Alice"; // Declares and initializes 'name' to "Alice"

Assignment (after declaration):


variableName = newValue;

Example:
int score; // Declaration
score = 100; // Assignment

Scope of Variables
The scope of a variable defines the region of the program where the variable can be
accessed. Java primarily has three types of variable scope:
● Local Scope (Method/Block Scope):
o Variables declared inside a method or a block (e.g., if statement, for loop)
have local scope.
o They are accessible only within the method or block where they are declared.
o Their lifetime is limited to the execution of that method or block.
Example:
public void calculateSum() {
int a = 10; // 'a' has local scope within calculateSum()
if (a > 5) {
int b = 20; // 'b' has local scope within the if block
[Link](a + b);
}
// 'b' is not accessible here
}
● Instance Scope (Class Level Scope):
o Variables declared within a class but outside any method, constructor, or block
are instance variables.
o They are accessible by all methods within that class.
o Each object of the class has its own copy of instance variables.
Example:
public class MyClass {
int instanceVariable; // 'instanceVariable' has instance scope

public void setVariable(int value) {


[Link] = value;
}
}

● Static Scope (Class Level Scope):


o Variables declared with the static keyword within a class are static variables.
o They belong to the class itself, not to any specific object.
o There is only one copy of a static variable, shared by all instances of the class.
o They can be accessed using the class name.
Example:
public class Counter {
static int count = 0; // 'count' has static scope

public Counter() {
count++;
}
}

Symbolic Constants
In Java, a symbolic constant is a named constant value defined once and used throughout a
program. Symbolic constants are declared using the final keyword.
● Which indicates that the value cannot be changed once it is initialized.
● The naming convention for symbolic constants is to use all capital letters with
underscores separating words.
Syntax of Symbolic Constants:
final data_type CONSTANT_NAME = value;
Example:
// Java Program to print an Array
import [Link].*;
public class Example {
public static final int MAX_SIZE = 10;

public static void main(String[] args)


{
int[] array = new int[MAX_SIZE];

for (int i = 0; i < MAX_SIZE; i++) {


array[i] = i * 2;
}

[Link]("Array: ");
for (int i = 0; i < MAX_SIZE; i++) {
[Link](array[i] + " ");
}
[Link]();
}
}

Output:
Array: 0 2 4 6 8 10 12 14 16 18

Type Casting
Type casting in Java is the process of converting a variable from one data type to another.
There are two main types of casting in Java:
[Link] Type Casting (Implicit/Automatic):
o This occurs when converting a smaller data type to a larger data type.
o Java automatically performs this conversion because there is no risk of data
loss.
Example:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myDouble); // Output: 9.0
[Link] Type Casting (Explicit/Manual):
o This occurs when converting a larger data type to a smaller data type.
o This conversion requires explicit casting using a cast operator () because there
is a potential for data loss (e.g., losing decimal places when converting
a double to an int).
Example:
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myInt); // Output: 9 (decimal part is truncated)

Operators
Java provides a wide range of operators categorized by their function:
Arithmetic Operators: Perform mathematical calculations.
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)
Relational (Comparison) Operators: Compare two operands and return a boolean result
(true or false).
== (Equals), != (Not equals), > (Greater than), < (Less than), >= (Greater than or
equals), <= (Less than or equals)
Logical Operators: Combine or modify boolean expressions.
&& (Logical AND), || (Logical OR), ! (Logical NOT)
Assignment Operators: Assign values to variables.
= (Simple assignment), +=, -=, *=, /=, %= (Compound assignment operators)
Unary Operators: Operate on a single operand.
++ (Increment), -- (Decrement), + (Unary plus), - (Unary minus), ! (Logical NOT)
Bitwise Operators: Perform operations at the bit level (for integer types).
& (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT), << (Left
shift), >> (Right shift), >>> (Unsigned right shift)
Ternary (Conditional) Operator: A shorthand for simple if-else statements.
condition ? expression1 : expression2
Expressions
An expression in Java evaluates to a single value. It can be simple, like a literal (5) or a
variable (x), or complex, involving multiple operators and operands.

// Arithmetic expression
int sum = a + b;

// Relational expression
boolean isEqual = (x == y);

// Logical expression
boolean isValid = (age > 18 && hasLicense);

// Assignment expression
int count = 10;
count += 5; // Equivalent to count = count + 5;

// Ternary expression
String status = (score >= 60) ? "Pass" : "Fail";

You might also like