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

unit 1 java

Uploaded by

manthantiwariwd
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

unit 1 java

Uploaded by

manthantiwariwd
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Introduction to java

Unit 1
What is java?
Java is a high-level, versatile, and object-oriented
programming language developed by James Gosling and
his team at Sun Microsystems in the mid-1990s. It was
designed with the goal of creating a language that is
platform-independent, meaning that Java programs can
run on any device with a Java Virtual Machine (JVM),
regardless of the underlying hardware and operating
system.
Evolution of java:-
The evolution of Java can be traced through various versions and updates, each introducing new features, enhancements, and improvements
to the language. Here is a brief overview of the major milestones in the evolution of Java:
1. Java 1.0 (January 23, 1996): This was the initial release of Java, which included many of the core features of the language, such as the
applet architecture for web browsers.
2. Java 1.1 (February 19, 1997): This version introduced significant enhancements, including inner classes, JavaBeans, and the Abstract
Window Toolkit (AWT) event model.
3. Java 1.2 (December 8, 1998): Also known as Java 2, version 1.2 brought major improvements, including the Swing GUI toolkit,
Collections framework, and the introduction of the Java Naming and Directory Interface (JNDI).
4. Java 1.4 (February 6, 2002): This version included the introduction of the assert keyword, the Logging API, and the incorporation of
the Java Web Start technology.
5. Java 5 (September 30, 2004): Also known as Java 1.5 or J2SE 5.0, this release was significant for introducing major language
enhancements such as generics, metadata annotations, the enhanced for loop, and the Java Virtual Machine Profiler Interface (JVMPI).
6. Java 6 (December 11, 2006): Often referred to as Java 1.6, this version focused on performance improvements, introduced the Java
Compiler API, and included enhancements to the Java Virtual Machine, such as support for scripting languages through the inclusion of
the Java Compiler API.
7. Java 7 (July 28, 2011): This release introduced several new features, including the try-with-resources statement, the diamond operator
for simplified generics, the Fork/Join framework for parallel programming, and the inclusion of the invokedynamic bytecode instruction to
support dynamic languages.
8. Java 8 (March 18, 2014): One of the most significant releases, Java 8 introduced lambda expressions, the Stream API for functional
programming, the java.time package for modern date and time handling, and the Nashorn JavaScript engine.
9. Java 9 (September 21, 2017): This version featured the modularization of the platform with the introduction of the Java Platform
Module System (JPMS), allowing for more modular and scalable applications.
10. Java 10 (March 20, 2018): Introduced local-variable type inference (var), allowing developers to declare variables without explicitly
specifying their types.
11. Java 11 (September 25, 2018): This version marked a Long-Term Support (LTS) release, featuring several improvements and removing
older features, including the removal of the Java EE and CORBA modules.
Features of Java:

Here are some feature of java:


1. Simple and Easy to Learn: Java's syntax is designed to be familiar and easy for
developers to learn, especially for those with experience in C or C++.
2. Object-Oriented Programming (OOP): Java is fully object-oriented, emphasizing
the use of classes and objects for code organization and reusability.
3. Platform Independence (Write Once, Run Anywhere): Java applications can run
on any device with a Java Virtual Machine (JVM), regardless of the underlying
hardware and operating system.
4. Automatic Memory Management: Java features automatic garbage collection,
which helps manage memory by automatically deallocating memory occupied by
objects that are no longer in use.
5. Rich Standard Library: Java comes with a comprehensive standard library that
provides pre-built modules and classes for various programming tasks. This simplifies
common programming tasks and enhances developer productivity.
6. Security: java has built-in security features to protect systems from potentially
harmful code. The Java Runtime Environment (JRE) includes a security manager that
controls access to system resources.
7. Scalability:Java is suitable for developing scalable applications, making it a popular
choice for both small-scale projects and large enterprise-level applications.
Comparison of java with C and C++
java C C++
Primarily an object-oriented programming A procedural programming language with A hybrid language that supports both
(OOP) language, emphasizing classes and limited support for object-oriented procedural and object-oriented
objects. It also supports procedural programming. programming, providing features like
programming. classes, inheritance, and polymorphism.
Utilizes automatic memory management Requires manual memory management. Offers both automatic memory management
(garbage collection) to handle memory Developers need to explicitly allocate and (through features like smart pointers) and
allocation and deallocation, reducing the risk deallocate memory, which provides more manual memory management (using
of memory leaks. control but can lead to errors if not managed traditional pointers).
carefully.
Achieves platform independence through Platform-dependent; the source code needs Like C, it is platform-dependent, and code
the Java Virtual Machine (JVM). Java code is to be recompiled for each target platform. often needs recompilation for different
compiled into bytecode, which can run on platforms.
any device with a compatible JVM.
Has a comprehensive standard library, Has a minimal standard library compared to Extends the C standard library and
offering a wide range of functionalities, Java and C++. It provides basic introduces the Standard Template Library
including networking, file I/O, and data functionalities and relies on external (STL), providing additional data structures,
structures. libraries for additional features. algorithms, and container classes.
Program Structure of java:

A typical Java program follows a specific structure, which includes various components and elements.
Here's an overview of the basic structure of a Java program:
1. Package Declaration (Optional):If your program is organized into packages, you'll start with a
package declaration. A package is a way to organize related classes. This part is optional, and if
omitted, the classes belong to the default package.
package com.example.myprogram;
2. Import Statements:Import statements are used to bring in classes from other packages. They come
after the package declaration and before the class declaration
import java.util.Scanner;
3. Class Declaration:A Java program must have at least one class, and the main class should have a
“public static void main(String[] args)” method where the execution begins.
public class MyClass {
public static void main(String[] args) {
// Program logic goes here
}
}
4.Variables and Constants:Declare any variables or constants that your program will use. This is where
you define the data types and names of the variables you'll be working with.
int age = 25;
final double PI = 3.14;
5.Methods (Functions):Define methods that encapsulate specific functionality. The “main” method
is where the program starts executing.
public class MyClass {
public static void main(String[] args) {
// Program logic goes here
sayHello();
}

static void sayHello() {


System.out.println("Hello, World!");
}
}
6.Comments:Use comments to provide explanations and documentation for your code. Comments
are ignored by the compiler and are for the benefit of developers.
// This is a single-line comment

/*
* This is a multi-line comment
* It can span multiple lines
*/
Tokens in Java:-

In Java, tokens are the smallest individual units or building blocks of a program. When
you write a Java program, the source code is first tokenized before it is compiled.
Tokenization is the process of breaking down the source code into individual tokens,
which are then analyzed by the compiler.
The basic types of tokens in Java include:
1. Keywords: These are reserved words in Java that have a specific meaning and
cannot be used for other purposes. Examples include Class, public, static, void,
etc.
2. Identifiers: These are names given to various program elements such as classes,
methods, variables, etc. Identifiers must follow certain naming conventions and rules
in Java.
3. Literals: Literals are constant values used in the program. Examples include numeric
literals (e.g.,42,3.14) character literals (e.g., ’a’, ’b’), and string literals (e.g., “Hello,
World!”).
4. Operators: Operators perform operations on variables and values. Examples include
+(addition), -(subtraction), *(multiplication), /(division), and so on.
5. Separators: Separators are symbols used to separate different parts of the program.
Examples include parentheses (), braces {}, comma”,”, semicolon “;”, etc.
Keywords in Java:-
In Java, keywords are reserved words that have specific meanings and cannot be used as identifiers
(names for classes, methods, variables, etc.) or for any other purpose. Here is a list of keywords in Java:

Note: It's important to note that the “const” keyword was reserved in earlier versions of Java but
has not been used and is not a keyword in recent versions (Java 10 onwards).
Variables in Java:
In Java, a variable is a container that holds a value. It is a way
to represent and store data in a program. Variables in Java are
defined by a data type and a name. The data type specifies the
type of value the variable can hold, and the name is used to
reference the variable in the code.
Variables are fundamental to programming, as they allow you
to store and manipulate data dynamically during the execution
of a program. The data type of a variable determines the type
of values it can hold (e.g., integers, floating-point numbers,
characters), and it also affects the memory allocation for the
variable.
Here's a basic syntax for declaring a variable in Java:
data_type variable_name;
Rules of declaring Variables in Java:-
1) Variable names must start with a letter, underscore, or dollar
sign, and subsequent characters can include letters, digits,
underscores, or dollar signs.
2) Java is case-sensitive, so variable names like "myVariable" and
"MyVariable" are distinct.
3) Declare variables with specific data types before use; primitive
types (e.g., int, double) or reference types (e.g., String).
4) Initialization is mandatory before using variables, and constants,
if intended, should use the final keyword.
5) Follow naming conventions such as camelCase for readability,
avoid reserved words, and choose meaningful names that
convey the variable's purpose for clearer and maintainable code.
Data Types In Java:-
In Java, data types are used to define the type of data that a variable can
hold. Java supports two main categories of data types: primitive data types
and
1. reference
Primitive Datadata types
Types: 2. Reference Data Types:
• byte: 8-bit signed integer. Range: -128 to 1. Class Types: Objects of user-
127. defined classes.
• short: 16-bit signed integer. Range: - 2. Interface Types: Instances of
32,768 to 32,767. interfaces.
• int: 32-bit signed integer. Range: -2^31 to 3. Array Types: Arrays of elements,
2^31 - 1. including arrays of primitive types or
• long: 64-bit signed integer. Range: -2^63 reference types.
to 2^63 - 1. 4. Enumeration Types: Special types
• float: 32-bit floating-point. Used for that represent a finite set of values.
decimal numbers with single precision.
• double: 64-bit floating-point. Used for
decimal numbers with double precision.
• char: 16-bit Unicode character. Represents
a single character.
• boolean: Represents true or false values.
Constants in Java:-
In Java, a constant refers to an identifier (name) for a
simple value that does not change during the execution
of a program. Once a constant is assigned a value, it
cannot be modified or reassigned throughout the
program. Constants are often used to represent fixed
values, such as mathematical constants or configuration
parameters.
In Java, constants are typically declared using the final
keyword. The final keyword indicates that the value of
the variable cannot be changed. Constant naming
conventions often involve using all uppercase letters with
underscores to separate words (e.g., MAX_VALUE, PI).
Typecasting in Java:-
Type casting, also known as type conversion, is the process of converting a variable from one data
type to another. In programming, variables have specific data types that define the kind of data
they can hold and the operations that can be performed on them. Type casting allows you to
change the data type of a variable when needed.
There
1) are two
Implicit main types
Casting of type casting:
(Widening): 2) Explicit Casting (Narrowing):
• Automatically performed by the • Requires manual intervention with an
compiler. explicit cast operator.
• Converts a smaller data type to a • Converts a larger data type to a smaller
larger data type. data type.
• No loss of data, as the larger type can • May result in data loss if the value cannot be
represent all possible values of the represented in the smaller type.
smaller type.
Statements in Java:-
In Java, a statement is a single, executable unit of code that performs a specific action. Java programs are
composed of a sequence of statements that are executed in order. There are several types of statements in Java,
each serving a different purpose:
• Declaration Statements:
• Declare a variable by specifying its type and name.
• Assignment Statements:
• Assign a value to a variable.
• Expression Statements:
• Combine variables, literals, and operators to form an expression.
• Control Flow Statements:
• Control the flow of execution in a program.
• Includes:
• Conditional Statements (if, else, switch)
• Loop Statements (for, while, do-while)
• Branching Statements:
• Alter the normal flow of control in a program.
• Includes:
• break:
• Terminates the nearest enclosing loop or switch statement.
• continue:
• Skips the rest of the loop's code and starts the next iteration.
• return:
• Exits a method, optionally returning a value.
Operators and Expressions in Java:
In Java, operators are symbols that perform operations on operands. An operand is a
variable, literal, or expression that an operator operates on. Expressions are
combinations of operators and operands that produce a result. Here are some common
operators and expressions in Java:
1. Arithmetic Operators: 4. Assignment Operators:
1. `+` (Addition) 1. `=` (Assignment)
2. `-` (Subtraction) 2. `+=` (Add and Assign)
3. `*` (Multiplication) 3. `-=` (Subtract and Assign)
4. `/` (Division) 4. `*=` (Multiply and Assign)
5. `%` (Modules, returns the remainder of a division) 5. `/=` (Divide and Assign)
2. Relational Operators: 6. `%=` (Modules and Assign)
1. `<` (Less Than) 5. Increment and Decrement Operators:
2. `>` (Greater Than) 1. `++` (Increment by 1)
3. `<=` (Less Than Equal To) 2. `--` (Decrement By 1)
4. `>=` (Greater Than Equal To) 6. Bitwise Operators:
5. `==` (Equal To) 1. `&` (Bitwise AND)
6. `!=` (Not Equal To) 2. `|` (Bitwise OR)
3. Logical Operators: 3. `^` (Bitwise XOR)
1. `&&` (Logical AND) 4. `~`(Bitwise NOT)
2. `||` (Logical OR) 5. `<<` (Left shift)
3. `!` (Logical Not) 6. `>>` (Right shift)
7. Conditional (Ternary) Operator:
1. `?:` (Conditional expression)
Conditional Statements in Java:-
Conditional statements are programming constructs that
enable a program to make decisions based on certain
conditions. These statements allow you to control the
flow of the program, executing different code blocks
depending on whether a specified condition is true or
false.
These conditional statements help in creating flexible and
dynamic programs by allowing the execution of specific
code based on various conditions. They are fundamental
to control the logical flow of a program and make it
responsive to different scenarios.
Different Types of conditional
Statements:-
1. If Statement
2. If-Else Statement
3. If-else-If Statement
4. Switch Statement
If Statement:-
In Java, the if statement is a fundamental conditional statement
that allows you to execute a block of code if a specified condition
evaluates to true . The basic syntax of an if statement is as
follows:

Here's a simple example:


In this example, if the value of x
is greater then 5, the code inside
the curly braces will be
executed, and “x is greater than
5” will be printed on console
If-else Statement in Java:-
The if-else statement in Java allows you to create a decision-
making structure where a block of code is executed if a specified
condition is true, and a different block of code is executed if the
condition is false. The basic syntax of an if-else statement is as
follows:

Here's an example:
In this example, if the value of x is even (i.e.,
the remainder when divided by 2 is 0), the
code inside the first block is executed, printing
"x is even" to the console. If the value of x is
odd, the code inside the else block is
executed, printing "x is odd" to the console.
If- Else-if Statement In Java:-

In Java, The if-else-if statement allows you to create a sequence of


conditions, where each condition is checked in order, and the
corresponding block of code associated with the first true condition
is executed. The basic syntax is as follows:

Here's an example:
In this example, the program checks three
conditions sequentially. If num is greater than
0, it prints "Number is positive." If num is less
than 0, it prints "Number is negative." If
neither of these conditions is true (i.e., num is
equal to 0), it prints "Number is zero."
Switch Statement in Java
In Java, the switch statement is a control flow statement that allows you to select and execute code
based on the value of a variable or an expression. It provides an alternative way to handle multiple
conditions compared to a series of if-else-if statements. The basic syntax of a switch statement is as
follows:

Here's a simple example:


In this example, the switch statement checks
the value of the doyofweek variable, and
depending on its value, it executes the
corresponding block of code. If dayofweek is
3, it prints "Tuesday" to the console. If
dayofweek doesn't match any of the
specified cases, the default block is executed
Key points of switch statement:-
1. The expression must evaluate to a byte, short, char, int,
String (since Java 7), or an enumeration type.
2. Each case block should end with a break statement to exit
the switch block. Without the break, the program would "fall
through" to the next case.
3. The default case is optional and is executed if none of the
cases match.
4. Starting from Java 12, switch expressions were introduced,
providing a more concise syntax for some scenarios.
Loop Statements in Java:-
Loop statements in programming are used to repeatedly
execute a block of code as long as a certain condition is
true or for a specified number of iterations. They allow for
efficient handling of repetitive tasks. In Java, there are
several types of loop statements:
1. For loop
2. While loop
3. Do-while loop
4. For each loop
For loop in Java:-
In Java, the for loop is a control flow statement used for iterative execution
of a block of code. It is particularly useful when you know in advance the
number of times you want to repeat a certain operation. The basic syntax
of a for loop is as follows: •Initialization: This is where you initialize the loop control
variable. It is typically used to set a counter variable to an initial
value.
•Condition: The loop continues executing as long as this
condition is true. Once the condition becomes false, the loop
exits.
•Iteration: After each iteration of the loop, the iteration
expression is executed. It is commonly used to increment or
Here's a simple example of a for loop:
decrement the loop control variable.
In this example, the loop
initializes int i to 1, continues as
long as i is less than or equal to
5, increments i by 1 after each
iteration, and prints the value of i
in each iteration.
While loop in Java:-

In Java, the while loop is a control flow statement that allows


you to repeatedly execute a block of code as long as a
specified condition is true. The basic syntax of a while
loop is as follows: The loop continues to execute as long as the specified
condition remains true. If the condition becomes false, the
control passes to the next statement after the while loop

Here's a simple
In this example, example
the loop ofi a
initializes int to while
1, loop:
continues as long as i is less than or equal to
5, prints the value of i in each iteration, and
increments i by 1 after each iteration.
Note: It's important to be cautious when using a
while loop to ensure that the loop control variable
is properly updated inside the loop. If not, you
may end up with an infinite loop, where the
condition never becomes false, leading to the
program continuously executing the same block
of code.
Do-while loop in Java:-
In Java, the do-while loop is a control flow statement that is similar to the while loop. The primary
difference is that the do-while loop guarantees that the code block within the loop is executed at
least once, regardless of whether the loop condition is initially true or false. The basic syntax of a do-
while loop is as follows:- In this loop:
1.The code block is executed first.
2.The condition is evaluated.
3.If the condition is true, the loop continues; otherwise, it terminates.

Here's an example of a do-while loop:


In this example, the loop initializes int
i to 1, prints the value of i in each
iteration, increments i by 1 after each
iteration, and continues as long as i is
less than or equal to 5.

Note: The do-while loop is useful when you want to ensure that a block of code is executed at least
once, even if the loop condition is initially false. It's important to be cautious with loop conditions
to avoid unintentional infinite loops.

You might also like