0% found this document useful (0 votes)
5 views

Java Unit-1

Java is a high-level, object-oriented programming language designed for platform independence, enabling applications to run on any device with a Java Virtual Machine. Key features include its robust security, multi-threading capabilities, and a rich standard library, making it popular for various applications. The document also compares Java with C++, discusses Java's role in internet programming, and outlines the Java environment and program structure.

Uploaded by

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

Java Unit-1

Java is a high-level, object-oriented programming language designed for platform independence, enabling applications to run on any device with a Java Virtual Machine. Key features include its robust security, multi-threading capabilities, and a rich standard library, making it popular for various applications. The document also compares Java with C++, discusses Java's role in internet programming, and outlines the Java environment and program structure.

Uploaded by

gglk371
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/ 12

Unit-I

Introduction of java
Java is a widely-used, high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle Corporation) in 1995. It was designed to be platform-
independent, meaning that programs written in Java can run on any device that has a Java Virtual
Machine (JVM) installed, regardless of the underlying hardware and operating system. This "write
once, run anywhere" capability has made Java immensely popular for developing a variety of
software applications, ranging from enterprise systems to mobile apps and embedded devices.
Key features of Java include:
1. Object-oriented: Java follows the object-oriented programming (OOP) paradigm,
allowing developers to create modular, reusable code by organizing data into objects and
defining their behavior through classes and methods.
2. Platform independence: Java programs are compiled into bytecode, which can be
executed on any device with a Java Virtual Machine (JVM). This enables developers to
write code once and deploy it across multiple platforms without modification.
3. Robust and secure: Java's strong type system, automatic memory management (garbage
collection), and exception handling mechanisms contribute to its robustness. Additionally,
Java's security features, such as the sandbox environment for executing untrusted code,
help prevent malicious attacks.
4. Multi-threaded: Java provides built-in support for concurrent programming through its
multithreading capabilities, allowing developers to create applications that can perform
multiple tasks simultaneously.
5. Rich standard library: Java comes with a comprehensive standard library (Java API) that
provides ready-to-use classes and methods for common programming tasks, including
input/output operations, networking, data manipulation, and GUI development.
6. Community support: Java has a large and active community of developers, which
contributes to its extensive ecosystem of frameworks, libraries, and tools. This ecosystem
includes popular frameworks like Spring, Hibernate, and Apache Struts, as well as
integrated development environments (IDEs) like Eclipse and IntelliJ IDEA.
Java's combination of versatility, portability, and robustness has made it a cornerstone of modern
software development, powering a wide range of applications across various industries.

Difference Between C++ and Java


Feature C++ Java
Programming Procedural, Object-Oriented Primarily Object-Oriented, with
Paradigm some procedural features
Memory Manual (new/delete), Smart Automatic (Garbage Collection)
Management Pointers
Platform Platform-dependent executables Platform-independent bytecode
Dependency (JVM)
Syntax Closer to C, Supports Pointers, Influenced by C and C++, Simpler
Operator Overloading Syntax
Standard Standard Template Library (STL), Java API, Rich Standard Libraries
Libraries Extensive third-party libraries
Concurrency Traditionally lacked, C++11 Built-in support for
introduced std::thread, std::async multithreading and concurrency
Exception try, catch, throw, Supports stack try, catch, throw, No stack
Handling unwinding unwinding support
Use Cases System programming, Game Enterprise applications, Web
development, Embedded systems development, Mobile (Android)

Java and Internet


Internet helped Java to bring it to the forefront and Java influenced Internet by simplifying the web
programming and inventing applets. Applets expanded the scope of internet. Java also addressed
two other important issues of internet, which are security and portability.
 Java Applets - An applet is a special kind of program that is transmitted over the Internet
and automatically executed by the Java-compatible web browser. Applets are usually small
programs and these helped in moving some user interactive programs from server to client,
hence improving the usability of the web application. The typical examples of applets are
tax calculator or some forms with input fields having lots of interaction between them.
 Security - Since applets are automatically downloaded and run on the client machine, there
are restrictions on what can be done in Applets. They can use only a subset of all the
functions supported by Java. e.g., They cannot access local file system or they cannot
launch other programs on the client system. Java achieved this protection by restricting an
applet to Java execution environment and not allowing it access to other parts of the
computer.
 Portability - Since Internet is comprised of many different types of computers and
operating systems, it is important for the programs to run on all these systems. Either we
have to have a separate program for every operating system or write a portable (or platform
independent) program like Java Applet which runs everywhere. This portability is
achieved by using Bytecode in Java
Java Support System
Java offers a rich ecosystem of libraries, frameworks, and tools that support various aspects of
software development. Here are some key categories of support systems within the Java
ecosystem:
1. Integrated Development Environments (IDEs): IDEs provide developers with
comprehensive tools for writing, debugging, and deploying Java applications. Popular Java
IDEs include Eclipse, IntelliJ IDEA, and NetBeans. These IDEs offer features such as code
editors with syntax highlighting, code completion, debugging tools, version control
integration, and project management capabilities.
2. Build Tools: Build tools automate the process of compiling, testing, and packaging Java
applications. Apache Maven and Gradle are widely-used build automation tools in the Java
ecosystem. They manage project dependencies, execute build tasks, and generate artifacts
such as JAR files and WAR files. These tools also support integration with continuous
integration (CI) and continuous delivery (CD) pipelines.
3. Dependency Management: Dependency management tools help Java developers manage
external dependencies required by their projects. Maven and Gradle, mentioned earlier,
excel in this area by providing dependency resolution capabilities. Developers specify
project dependencies in configuration files (e.g., pom.xml for Maven, build.gradle for
Gradle), and the build tools automatically download and include the required libraries in
the project.
4. Testing Frameworks: Testing frameworks enable developers to write and execute
automated tests for their Java code. JUnit is a popular unit testing framework for Java, used
for writing and running unit tests to ensure the correctness of individual components.
Additionally, frameworks like TestNG and Mockito provide features for more
comprehensive testing, including integration tests and mock object creation.
5. Web Frameworks: Web frameworks simplify the development of web applications in
Java by providing reusable components, request handling mechanisms, and MVC
architecture support. Some popular Java web frameworks include Spring MVC, JavaServer
Faces (JSF), Struts, and Play Framework. These frameworks offer features for handling
HTTP requests, managing application state, and integrating with databases and other
services.
6. Persistence Frameworks: Persistence frameworks facilitate the interaction between Java
applications and databases, allowing developers to store and retrieve data. Java Persistence
API (JPA) is a standard Java EE specification for object-relational mapping (ORM), which
provides a set of interfaces and annotations for mapping Java objects to relational database
tables. Hibernate and EclipseLink are popular JPA implementations used in Java
applications.
7. Enterprise Integration: Enterprise integration frameworks enable Java applications to
communicate with external systems, services, and messaging platforms. Apache Camel
and Spring Integration are examples of integration frameworks that provide a wide range
of components and patterns for building enterprise integration solutions. These frameworks
support integration with messaging systems, web services, databases, and other enterprise
technologies.
These support systems, along with many others in the Java ecosystem, contribute to the
productivity, reliability, and scalability of Java-based software development. Developers can
leverage these tools and frameworks to build a wide variety of applications, from small utilities to
large-scale enterprise systems.

Java Environment
The Java environment consists of several components that collectively enable the development,
execution, and management of Java applications. Here are the key components of the Java
environment:
1. Java Development Kit (JDK): The JDK is a software development kit that provides the
tools and libraries necessary for developing Java applications. It includes the Java Compiler
(javac) for compiling Java source code into bytecode, the Java Virtual Machine (JVM) for
executing bytecode on various platforms, and a set of standard libraries and development
tools (such as the Java Development Kit (JDK)). The JDK also includes the Java Runtime
Environment (JRE), which is needed to run Java applications on a computer.
2. Java Runtime Environment (JRE): The JRE is a runtime environment that provides the
necessary libraries and components to run Java applications. It includes the JVM, which
interprets and executes Java bytecode, as well as core libraries and runtime support files.
The JRE does not include development tools like the JDK; it is intended for end-users who
only need to run Java applications.
3. Java Virtual Machine (JVM): The JVM is a crucial component of the Java environment
responsible for executing Java bytecode. It abstracts the underlying hardware and operating
system, providing a platform-independent execution environment for Java applications.
The JVM interprets bytecode or, in some cases, just-in-time (JIT) compiles it into native
machine code for improved performance.
4. Java Standard Library: Java comes with a comprehensive standard library (also known
as the Java API or Java SDK), which provides a wide range of classes and packages for
common programming tasks. The standard library includes classes for input/output
operations, networking, collections, concurrency, GUI development (with AWT and
Swing), database connectivity (with JDBC), and more.
5. Integrated Development Environments (IDEs): IDEs are software applications that
provide developers with tools and features to write, debug, and deploy Java code more
efficiently. Popular Java IDEs include Eclipse, IntelliJ IDEA, NetBeans, and Oracle
JDeveloper. These IDEs typically offer features such as code editors with syntax
highlighting, code completion, debugging tools, version control integration, and project
management capabilities.
6. Build Tools: Build tools automate the process of compiling, testing, and packaging Java
applications. Apache Maven and Gradle are widely-used build automation tools in the Java
ecosystem. They manage project dependencies, execute build tasks, and generate artifacts
such as JAR files and WAR files. These tools also support integration with continuous
integration (CI) and continuous delivery (CD) pipelines.
7. Application Servers: For developing and deploying enterprise Java applications,
application servers provide a runtime environment that supports features such as
transaction management, security, scalability, and reliability. Examples of Java application
servers include Apache Tomcat, WildFly (formerly JBoss), Apache TomEE, and IBM
WebSphere.
These components collectively form the Java environment, providing developers with the tools,
libraries, and runtime support necessary for building and running Java applications across different
platforms and environments.

Java Program Structure


// 1. Package Declaration (optional)
package com.example.myprogram;

// 2. Class Declaration
public class MyClass {

// 3. Main Method (Entry Point of the Program)


public static void main(String[] args) {

// 4. Program Logic
System.out.println("Hello, World!");
}

// 5. Additional Methods (optional)


// Other methods can be defined within the class as needed
}
1. Package Declaration (optional): If your class belongs to a specific package, you can
declare it using the package keyword. Packages help organize related classes and prevent
naming conflicts. This statement is optional but recommended for larger projects.
2. Class Declaration: Every Java program consists of at least one class. The class contains
the program's code and serves as a blueprint for creating objects. The class name should
match the filename (with the extension .java). In this example, the class is named
MyClass.
3. Main Method (Entry Point of the Program): The main method is the entry point of a
Java program. It has a specific signature: public static void main(String[] args). When
you run a Java program, the JVM starts executing from the main method. This method can
receive command-line arguments as an array of strings (args).
4. Program Logic: Within the main method or other methods, you define the logic of your
program. This includes statements to perform calculations, manipulate data, interact with
users, etc. In this example, a simple output statement (System.out.println) is used to print
"Hello, World!" to the console.
5. Additional Methods (optional): Besides the main method, you can define other methods
within the class to encapsulate specific functionality. These methods can be called from
the main method or other methods within the class. In this basic example, no additional
methods are defined, but you can add them as needed for more complex programs.
Tokens
A token is the smallest individual unit of a program. Tokens are the basic building blocks of Java
code and are used by the compiler to understand and interpret the program. The Java compiler
recognizes several types of tokens, including:
1. Keywords: Keywords are reserved words in Java that have predefined meanings and
cannot be used as identifiers (such as variable names or method names). Examples of
keywords in Java include class, public, static, void, if, else, for, while, and return.
2. Identifiers: Identifiers are names given to various elements in a Java program, such as
classes, variables, methods, and packages. Identifiers must follow certain rules, such as
starting with a letter, underscore (_), or dollar sign ($) and consisting of letters, digits,
underscores, or dollar signs.
3. Literals: Literals represent constant values in Java code. They can be of various types,
including integer literals (e.g., 10, 42), floating-point literals (e.g., 3.14, 2.718), character
literals (e.g., 'a', 'b'), string literals (e.g., "Hello", "World"), boolean literals (true and
false), and null literal (null).
4. Operators: Operators perform operations on operands (variables or values). Java supports
various types of operators, such as arithmetic operators (e.g., +, -, *, /), assignment
operators (e.g., =, +=, -=), comparison operators (e.g., ==, !=, <, >), logical operators (e.g.,
&&, ||, !), and bitwise operators (e.g., &, |, ^, ~).
5. Separators: Separators are characters used to separate tokens or indicate the beginning or
end of a statement or block of code. Common separators in Java include parentheses (),
braces {}, brackets [], commas ,, semicolons ;, periods ., colons :, and the ellipsis ....
6. Comments: Comments are not technically tokens, but they are ignored by the compiler
and are used to provide explanatory notes or documentation within the code. Java supports
single-line comments (//) and multi-line comments (/* */).
These tokens collectively form the syntax of a Java program and are essential for writing,
compiling, and executing Java code.

Statements
A statement is a single line or a block of code that performs a specific action. Java statements are
the building blocks of Java programs, and they are executed sequentially, one after another, unless
control flow statements alter the normal flow of execution. There are several types of statements
in Java:
1. Declaration Statements: Declaration statements are used to declare variables or constants.
They typically include the variable's data type followed by the variable name, and
optionally, an initial value. For example:
int age; double pi = 3.14; final int MAX_VALUE = 100;
2. Expression Statements: Expression statements are used to evaluate expressions.
Expressions can be simple variables, method calls, or more complex mathematical
calculations. For example:
int sum = a + b; System.out.println("Hello, World!");
3. Assignment Statements: Assignment statements are used to assign values to variables.
They typically include the variable name followed by the assignment operator (=) and the
value to be assigned. For example:
int x = 10;
4. Control Flow Statements: Control flow statements are used to control the flow of
execution in a Java program. They include conditional statements (such as if, else, switch),
looping statements (such as for, while, do-while), and branching statements (such as
break, continue, return).
For example:
if (x > 0) {
System.out.println("Positive");
}
else
{
System.out.println("Non-positive");
}
5. Block Statements: Block statements are used to group multiple statements together. They
are enclosed within curly braces {}. Block statements are commonly used with control flow
statements to execute multiple statements conditionally or repeatedly. For example:
int a = 10; int b = 20;
int sum = a + b;
System.out.println("Sum: " + sum);
These are some of the fundamental types of statements in Java, and they are used extensively to
define the behavior of Java programs.

Data Types
1. Primitive Data Types: Primitive data types represent basic values and are predefined by
the Java language. They are divided into four categories: integer types, floating-point types,
boolean type, and character type.
 Integer Types:
 byte: 8-bit signed integer. Range: -128 to 127.
 short: 16-bit signed integer. Range: -32,768 to 32,767.
 int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
 long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
 Floating-Point Types:
 float: 32-bit floating-point number. Range: ±1.4E-45 to ±3.4E+38. Suffix:
f or F.
 double: 64-bit floating-point number. Range: ±4.9E-324 to ±1.7E+308.
 Boolean Type:
 boolean: Represents true or false values only. Size: Not precisely defined.
 Character Type:
 char: 16-bit Unicode character. Range: '\u0000' (0) to '\uffff' (65,535).
2. Reference Data Types: Reference data types are used to refer to objects. They include
classes, interfaces, arrays, and enumerations.
 Classes: User-defined data types created using the class keyword.
 Interfaces: Similar to classes but define a contract for the behavior of a class.
 Arrays: Ordered collections of elements of the same data type.
 Enumerations: Special types that define a set of constants.
Data Type Size (in bits) Range Default Value Wrapper Class
byte 8 -128 to 127 0 Byte
short 16 -32,768 to 32,767 0 Short
Integer
int 32 -2^31 to 2^31 - 1 0 Integer
long 64 -2^63 to 2^63 - 1 0 Long
float 32 ±1.4E-45 to ±3.4E+38 0.0 Float
double 64 ±4.9E-324 to ±1.7E+308 0.0 Double
boolean Not precisely Not precisely defined false Boolean
defined
char 16 '\u0000' (0) to '\uffff' '\u0000' Character
(65,535)

Constants:
 Constants are values that do not change during the execution of a program.
 They are fixed and immutable.
 Constants are typically used to represent values that remain constant throughout the
program, such as mathematical constants (e.g., pi), configuration parameters, or
fixed values used in calculations.
 In Java, constants are often declared using the final keyword to indicate that their
value cannot be modified once initialized.
Example
final double PI = 3.14159; final int MAX_SIZE = 100;
2. Variables:
 Variables are named memory locations used to store data that can vary or change
during the execution of a program.
 They are used to hold values that may be modified or updated as the program runs.
 Variables have a data type (such as int, double, String) that determines the type of
data they can hold.
 In Java, variables must be declared with a specific data type before they can be
used, and they can be assigned values using the assignment operator =.
Example:
int age = 25; double temperature = 98.6; String name = "John";
Constants represent fixed values that do not change, while variables represent mutable data that
can be modified during program execution. Both constants and variables are essential for storing
and manipulating data in Java programs.

Operators
1. Arithmetic Operators:
 Used to perform mathematical operations.
 Include addition +, subtraction -, multiplication *, division /, modulus % (remainder), and
unary minus -.
 Example:
 int a = 10, b = 5;
 int sum = a + b; // Addition
 int difference = a - b; // Subtraction
 int product = a * b; // Multiplication
 int quotient = a / b; // Division
 int remainder = a % b; // Modulus
 int negation = -a; // Unary minus

Relational Operators:
 Used to compare values.
 Include equal to ==, not equal to !=, greater than >, less than <, greater than or equal to >=,
and less than or equal to <=.
 Return boolean values (true or false).
 Example:
 int x = 10, y = 5;
 boolean isEqual = (x == y); // Equal to
 boolean isNotEqual = (x != y); // Not equal to
 boolean isGreater = (x > y); // Greater than
 boolean isLess = (x < y); // Less than
 boolean isGreaterOrEqual = (x >= y); // Greater than or equal to
 boolean isLessOrEqual = (x <= y); // Less than or equal to

Logical Operators:
 Used to perform logical operations on boolean values.
 Include logical AND &&, logical OR ||, and logical NOT !.
 Example:
 boolean condition1 = true, condition2 = false;
 boolean resultAnd = condition1 && condition2; // Logical AND
 boolean resultOr = condition1 || condition2; // Logical OR
 boolean resultNot = !condition1; // Logical NOT

Assignment Operators:
 Used to assign values to variables.
 Include simple assignment =, compound assignment +=, -= , *=, /=, and %=.
 Example:
 int x = 10;
 x += 5; // Equivalent to x = x + 5;

Increment and Decrement Operators:


 Used to increase or decrease the value of a variable by one.
 Include increment ++ and decrement --.
 Example:
 int count = 0;
 count++; // Increment count by 1
 count--; // Decrement count by 1

Conditional (Ternary) Operator:


 Also known as the ternary operator.
 Used for conditional expressions.
 Syntax: condition ? expression1 : expression2.
 Example:
int result = (x > y) ? x : y;

Bitwise Operators:
 Used to perform operations at the bit-level.
 Include bitwise AND &, bitwise OR |, bitwise XOR ^, bitwise complement ~, left shift <<,
right shift >>, and zero-fill right shift >>>.
 Example:
 int a = 5, b = 3;
 int bitwiseAnd = a & b; // Bitwise AND
 int bitwiseOr = a | b; // Bitwise OR
 int bitwiseXor = a ^ b; // Bitwise XOR
 int bitwiseComplement = ~a; // Bitwise complement
 int leftShift = a << 1; // Left shift
 int rightShift = a >> 1; // Right shift
Special Operators:
 Include the ternary operator ? : and the instanceof operator instanceof.
 Example:
 int result = (x > y) ? x : y; // Ternary operator
 boolean isString = (obj instanceof String); // instanceof operator

Expressions and Evaluation:


 Expressions are combinations of operators, variables, and constants that produce a single
value.
 Expressions are evaluated according to operator precedence and associativity rules.
 Example:
int result = (5 * (10 + 3)) / 2; // Example expression

You might also like