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

Java

Uploaded by

princepatna936
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)
14 views

Java

Uploaded by

princepatna936
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/ 21

Java

What is Java?
Java is a programming language. Java is a high-level, object-oriented, and
secure programming language.

Need Of Java
It is a fast, secure, reliable programming language for coding everything from
mobile apps and enterprise software to big data applications and server-side
technologies.

Java continues to evolve, with new versions released regularly, incorporating


modern features like lambda expressions and modules and improving
performance.

Java’s memory management and garbage collection process improves


resource utilization and application performance.

Java has built-in security features like the Java Security Manager, which helps
restrict unauthorized access to system resources, and strong encryption
libraries, making it a preferred choice for applications that require high
security.

Introductions to Java
Java is a widely used, high-level, object-oriented programming language
designed to be simple, portable, secure, and efficient. It was created by
James Gosling and his team at Sun Microsystems in the mid-1990s and is
now owned by Oracle Corporation.

Java has become one of the most popular programming languages in the
world, largely due to its ability to run on a variety of platforms, its extensive

Java 1
ecosystem, and its widespread use in enterprise applications, mobile
development, web applications, and more.

Before Java, its name was ‘Oak.’ Oak was already a registered company, so
James Gosling and his team decided to change the name to ‘Java’.

Java is designed to be platform-independent, which means that a Java


program can run on any machine with a JVM (Java Virtual Machine),
regardless of the underlying hardware and operating system.

Java Files Contains .java Extension

Key Features Of Java


Object-Oriented:

Java follows the principles of Object-Oriented Programming (OOP). OOPs


is a programming style that uses objects to represent and manipulate
data, using classes and methods to define behavior. The core principles of
OOP are:

Encapsulation: Wrapping up of data members and member Functions.

Inheritance: Allowing one class to inherit the behavior and properties


of another.

Polymorphism: Allows different objects to respond to the same


message or method call in multiple ways.

Abstraction: hiding the implementation details of a code and exposing


only the necessary information to the user.

Platform Independence:

Java is famous for its "Write Once, Run Anywhere" (WORA) philosophy.
When a Java program is compiled, it is converted into bytecode rather
than machine-specific code. This bytecode can then be run on any device
that has a Java Virtual Machine (JVM), which is available for virtually
every operating system.

Robust and Secure:

Java 2
Java is designed to be robust, meaning it is reliable and minimizes errors.
It has strong memory management and error-handling mechanisms like
exception handling and automatic garbage collection.

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

Class Loader

ByteCode Verifier, etc.

Simple and Easy to Learn:

Java was designed to be easy to use and understand, even for beginners.
It simplifies certain aspects of programming (such as memory
management and syntax) compared to older languages like C++, which
makes it more accessible to developers.

Its syntax is similar to C, which means that developers familiar with C or


C++ can easily transition to Java.

Multithreading:

Java has built-in support for multithreading, which allows multiple tasks
to run concurrently within a program. This is particularly useful for
applications that require high performance, like games, servers, or media
applications.

Memory Management:

Java manages memory automatically using a process known as garbage


collection. This means that unused objects are automatically cleaned up,
which reduces the chance of memory leaks or errors related to manual
memory management.

Rich Standard Library:

Java provides a vast collection of libraries and APIs that cover everything
from basic data structures to advanced features like networking, file I/O,
database access, GUI (Graphical User Interface) components, and more.

Java 3
The Java Standard Library (also known as the Java API) is one of the key
strengths of the language.

Portability:

As mentioned earlier, Java programs can be run on any platform that has a
JVM. This makes Java an excellent choice for cross-platform
development, including applications for Windows, macOS, Linux, and
mobile platforms like Android.

Compilation and Execution of a Java Program


Compilation and execution of a Java Program Involves the Steps described
below:-

Writing Java Code:

Developers write Java code using a simple text editor or a more advanced
Integrated Development Environment (IDE) such as Eclipse, IntelliJ IDEA,
or NetBeans.

Compiling the Code:

Java code is saved in files with the .java extension. These files are then
compiled into bytecode by the Java Compiler ( javac ), producing .class

files.

Running the Code:

The bytecode is executed by the Java Virtual Machine (JVM). The JVM
translates the bytecode into machine code, which can be executed by the
operating system.

Basic Structure of a Java Program


// This is a single-line comment

/*

Java 4
This is a multi-line comment
*/

public class MyFirstJavaProgram {


// Main method - the entry point of any Java program
public static void main(String[] args) {
// Print statement to output text to the console
System.out.println("Hello, World!");
}
}

1. Comments:

Comments are used to explain the code and are ignored by the compiler.
There are two types of comments:

Single-line comments ( // ): Everything after // on that line is a


comment.

Multi-line comments ( /* ... */ ): Everything between /* and / is a


comment.

2. Class Declaration:

public class MyFirstJavaProgram : This line declares a class


named MyFirstJavaProgram . In Java, every application must have at least one
class definition. The keyword public is an access modifier that means the
class is accessible from other classes.

3. Main Method:

public static void main(String[] args) : This is the entry point of any Java
application. The Java Virtual Machine (JVM) looks for this method when
executing a Java program.

public : Access modifier indicating that the method can be called from
anywhere.

static: This means that the method belongs to the class, rather than
instances of the class.

Java 5
void : Indicates that the method does not return any value.

: This is an array of
String[] args String objects that can hold
command-line arguments.

4. Statements:

System.out.println("Hello, World!"); : This is a statement that prints "Hello,


World!" to the console. System.out is a built-in output stream that is
connected to the console, and println is a method that prints the specified
message followed by a new line.

Points to be noted:-

Java is a case-sensitive language, so main , System , and println must be


written in the correct case.

The file name should match the class name (e.g., MyFirstJavaProgram.java ), and
the class must be declared public if it is in a public file.

Data Types and Variables

Variable
A variable is a container that holds data that can be changed during the execution
of a program. Variables allow you to store and manipulate data.

Types of Variable
There are three types of variables in Java:

local variable:- A variable declared inside the body of the method is called a
local variable. You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.

instance variable:- A variable declared inside the class but outside the body
of the method is called an instance variable.

Static variable: A variable that is declared static is called a static variable. It


cannot be local. You can create a single copy of the static variable and share it

Java 6
among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

public class V
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}

Data Types in Java


Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float, and double.

2. Non-primitive data types: The non-primitive data types


include Classes, Interfaces, and Arrays.

Data Type Default Size Range

Boolean 1 byte true/false


char 2 byte '\u0000' (or 0) to '\uffff’
byte 1 byte -127 to 128

short 2 byte -32,768 to 32767

Java 7
int 4 byte - 2,147,483,648 to

long 8 byte 2,147,483,647


-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 byte
Its value range is unlimited
double 8 byte
Its value range is unlimited

Operators
Operators in Java are special symbols that perform operations on variables and
values. They can be categorized based on the type of operation they perform.

The different types of Operators are as follows:-

1. Arithmetic Operators
Arithmetic operators perform basic mathematical operations.

Operator Description Example


+ Addition 5 + 3 = 8

- Subtraction 5 - 3 = 2

* Multiplication 5 * 3 = 15

/ Division 5 / 3 = 1

% Modulus 5 % 3 = 2

2. Relational (Comparison) Operators


Relational operators are used to compare two values and return a boolean result
( true or false ).

Operator Description Example


== Equal to 5 == 3 returns false

!= Not equal to 5 != 3 returns true

> Greater than 5 > 3 returns true

Java 8
< Less than 5 < 3 returns false

>= Greater than or equal to 5 >= 3 returns true

<= Less than or equal to 5 <= 3 returns false

3. Logical Operators
Logical operators are used to perform logical operations on boolean values.

Operator Description Example


&& Logical AND true && false returns false

! Logical NOT !true returns false

4. Assignment Operators
Assignment operators are used to assign values to variables.

Operator Description Example


= Assigns value to a variable x = 5;

x += 5; (equivalent to x = x +
+= Adds the value to the variable
5; )

Subtracts the value from the x -= 5; (equivalent to x = x -


-=
variable 5; )

x *= 5; (equivalent to x = x *
*= Multiplies the variable by a value
5; )

x /= 5; (equivalent to x = x /
/= Divides the variable by a value
5; )

x %= 5; (equivalent to x = x %
%= Takes the modulus of the variable
5; )

5. Unary Operators
Unary operators perform operations on a single operand. They can be used to
increment/decrement a value, invert a boolean, or change the sign.

Operator Description Example

Java 9
++ Increment (increases value by 1) x++ or ++x

-- Decrement (decreases value by 1) x-- or --x

! Logical NOT (inverts boolean) !true returns false

6. Bitwise Operators
Bitwise operators perform operations on individual bits of integer values.

Operator Description Example


& Bitwise AND 5 & 3 results in 1 (in binary: 0101 & 0011 = 0001 )

| BItwise OR 5 | 3 result is 7(in binary)

^ Bitwise XOR 5 ^ 3 results in 6 (in binary: 0101 ^ 0011 = 0110 )

~5 results in -6 (in binary: ~0101 = 1010 , which is


~ Bitwise NOT
-6 in two's complement representation)

<< Left shift 5 << 1 results in 10 (in binary: 0101 << 1 = 1010 )

>> Right shift 5 >> 1 results in 2 (in binary: 0101 >> 1 = 0010 )

Unsigned right -5 >>> 1 results in a large positive number (ignores


>>>
shift sign bit)

7. Ternary (Conditional) Operator


The ternary operator is a shorthand for if-else statements. It evaluates a
condition and returns one of two values based on the result.

Syntax Example Explanation

condition ? trueValue : int x = (a > b) ? a If a > b is true, x = a ;


falseValue; : b; otherwise, x = b

8. New Operator
The new operator is used to create new objects or arrays.

Operator Description Example


new Creates new objects or arrays MyClass obj = new MyClass();

Java 10
Conditions
1. If Statement
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of code
if the expression evaluates to true.
The syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}

2. if-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the if-
block is evaluated as false.
Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

3. If-Else If-Else Statement


The if-else if-else statement is useful when you have multiple conditions to
check. It allows you to test several conditions in sequence. The first true condition
executes its block of code, and the rest are skipped.

Java 11
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

4. Switch Statement
The switch statement is an alternative to a series of if-else if statements when
you have many possible conditions based on a single variable. It evaluates an
expression and compares it to the values of each case in the switch block.

Syntax:

switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if no cases match
}

Loop

Java 12
loops are used to repeatedly execute a block of code as long as a specified
condition is true . There are three main types of loops in Java:

1. For Loop

2. While Loop

3. Do-While Loop

1. For Loop
The for loop is typically used when the number of iterations is known
beforehand. It consists of three parts: initialization, condition, and
increment/decrement.

Syntax:

for (initialization; condition; update) {


// Code to execute repeatedly
}

Example:

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


System.out.println("i = " + i);
}

Variants of For Loop:


1. For-Each Loop (Enhanced For Loop): Used to iterate through elements in an
array or a collection (like List , Set ).
Syntax:

Java 13
for (Type element : collection) {
// Code to execute
}

Example:

int[] numbers = {1, 2, 3, 4, 5};


for (int num : numbers) {
System.out.println(num);
}

2. While Loop
The while loop is used when you don't know in advance how many times the loop
will run, but you want to keep looping as long as a condition is true. The condition
is checked before each iteration.

Syntax:

while (condition) {
// Code to execute repeatedly
}

Example:

int i = 0;
while (i < 5) {
System.out.println("i = " + i);

Java 14
i++;
}

3. Do-While Loop
The do-while loop is similar to the while loop, but the condition is checked after
the loop body is executed. This ensures that the loop will execute at least once,
even if the condition is false initially.

Syntax:

do {
// Code to execute
} while (condition);

The body of the loop is executed first.

After the body is executed, the condition is evaluated.

If the condition is true , the loop continues. If false , it exits.

4. Break Statement
The break statement is used to exit a loop (or a switch statement).

Example:

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


if (i == 3) {
break; // Exits the loop when i equals 3
}
System.out.println("i = " + i);

Java 15
}

5. Continue Statement
The continue statement is used to skip the current iteration of a loop and proceed
to the next iteration.

Example:

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


if (i == 3) {
continue; // Skips printing when i equals 3
}
System.out.println("i = " + i);
}

Explanation:
When i == 3 , the continue statement causes the loop to skip printing that value
and jump to the next iteration.

Methods
In Java,
methods are blocks of code that perform a specific task. They allow you to write
reusable code that can be executed when called. Methods in Java are similar to
functions in other programming languages.
method also provides the easy modification and readability of code, just by
adding or removing a chunk of code. The method is executed only when we call
or invoke it.

Java 16
The most important method in Java is the main() method.

Key Concepts Related to Methods:


1. Method Declaration/Definition

2. Method Invocation/Calling

3. Method Parameters and Arguments

4. Method Return Type

5. Static Methods

1. Method Declaration/Definition
A method is defined with the following components:

Access Modifier: Determines the visibility of the method (e.g., public , private ,
protected ).

Return Type: Specifies the type of value the method returns (e.g., int , String ,
void ).

Method Name: The name used to call the method (e.g., addNumbers ).

Parameters (Optional): Input values that are passed to the method (e.g., int

a, int b ).

Method Body: The block of code that defines what the method does.

Syntax:

access_modifier return_type method_name(parameter_list) {


// Method body
}

Example:

Java 17
public int addNumbers(int a, int b) {
return a + b;
}

2. Method Invocation/Calling
To execute a method, you need to invoke it. Methods can be called in two main
ways:

Instance Method Call: If the method is not static , you need to create an
object of the class to call the method.

Static Method Call: If the method is static , you can call it directly using the
class name without creating an object.

Example of calling an instance method:

public class Calculator {


public int addNumbers(int a, int b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator(); // Creating an o
bject
int result = calc.addNumbers(3, 5); // Calling the m
ethod
System.out.println(result); // Output: 8
}
}

Example of calling a static method:

Java 18
public class Calculator {
public static int multiplyNumbers(int a, int b) {
return a * b;
}

public static void main(String[] args) {


int result = Calculator.multiplyNumbers(4, 5); // Ca
lling static method
System.out.println(result); // Output: 20
}
}

3. Method Parameters and Arguments


Parameters are defined in the method signature and act as placeholders for
values passed to the method.

Arguments are the actual values passed to the method when it's called.

Example:

public void hi(String name) {


System.out.println("Hello, " + name);
}

hi("java"); // Output: Hello, java

4. Method Return Type


The return type of a method specifies the type of value the method will return to
the caller. If the method doesn't return anything, it uses void .

void: This means the method does not return any value.

Return Type (e.g., int, String, etc.): Specifies the type of value the method
returns.

Java 19
Example of a method with return type:

public int subtractNumbers(int a, int b) {


return a - b; // Returns an integer
}

In this example, int is the return type, meaning the method will return an integer
value. The return keyword is used to return the result.

Example with void (no return type):

public void printMessage(String message) {


System.out.println(message);
}

7. Static Methods
A static method belongs to the class rather than to any specific object. Static
methods can be called without creating an instance of the class.

Accessing static methods: Static methods can be called directly using the
class name.

Restrictions: Static methods cannot directly access instance variables or


instance methods.

Example of a static method:

public class MathUtils {


public static int add(int a, int b) {
return a + b;
}

Java 20
public static void main(String[] args) {
int result = MathUtils.add(10, 20); // Calling a sta
tic method
System.out.println(result); // Output: 30
}
}

OOP’s

OOP’s

Java 21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy