You are on page 1of 33

Java Unit-1

What is Java?

Java is a programming language and a platform.


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

Java was developed by Sun Microsystems (which


is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of
Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James
Gosling and his team changed the name from
Oak to Java.

Platform: Any hardware or software environment


in which a program runs, is known as a platform.
Since Java has a runtime environment (JRE) and
API, it is called a platform.

Java Example

Let's have a quick look at Java programming


example. A detailed description of Hello Java
example is available in next page.

Simple.java
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

Application

According to Sun, 3 billion devices run Java.


There are many devices where Java is currently
used. Some of them are as follows:

1. Desktop Applications such as acrobat reader,


media player, antivirus, etc.
2. Web Applications such as irctc.co.in,
javatpoint.com, etc.
3. Enterprise Applications such as banking
applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

What is Java Bytecode?


Java bytecode is the instruction set for the Java
Virtual Machine. As soon as a java program is
compiled, java bytecode is generated. In other
words , java bytecode is the machine code in
the form of a .class file. With the help of java
bytecode we achieve platform independence in
java.

How does it works?

When we write a program in Java, firstly, the


compiler compiles that program and a
bytecode is generated for that piece of code.
When we wish to run this .class file on any
other platform, we can do so. After the first
compilation, the bytecode generated is now
run by the Java Virtual Machine and not the
processor in consideration. This essentially
means that we only need to have basic java
installation on any platforms that we want to
run our code on. Resources required to run the
bytecode are made available by the Java Virtual
Machine, which calls the processor to allocate
the required resources. JVM's are stack-based
so they stack implementation to read the
codes.
JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract


machine. It is a specification that provides
runtime environment in which java bytecode can
be executed.

JVMs are available for many hardware and


software platforms (i.e. JVM is platform
dependent).

What is JVM

It is:

1. A specification where working of Java Virtual


Machine is specified. But implementation
provider is independent to choose the
algorithm.
2. An implementation Its implementation is
known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java
command on the command prompt to run
the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
Features of Java

The primary objective of Java


programming language creation was to make it
portable, simple and secure programming
language. Apart from this, there are also some
excellent features which play an important role in
the popularity of this language. The features of
Java are also known as Java buzzwords.

A list of the most important features of the Java


language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Interpreted
8. High Performance
9. Multithreaded
10. Distributed
11. Dynamic
Simple

Java is very easy to learn, and its syntax is simple,


clean and easy to understand. According to Sun
Microsystem, Java language is a simple
programming language because:

o Java syntax is based on C++ (so easier for


programmers to learn it after C++).
o Java has removed many complicated and
rarely-used features, for example, explicit
pointers, operator overloading, etc.

Object-oriented

Java is an object-oriented programming


language. Everything in Java is an object. Object-
oriented means we organize our software as a
combination of different types of objects that
incorporate both data and behavior.

Object-oriented programming (OOPs) is a


methodology that simplifies software
development and maintenance by providing
some rules.

Basic concepts of OOPs are:


1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Secured

Java is best known for its security. With Java, we


can develop virus-free systems. Java is secured
because:

o No explicit pointer
o Java Programs run inside a virtual machine
sandbox

o Bytecode Verifier
o Security Manager

Java language provides these securities by


default. Some security can also be provided
by an application developer explicitly
through SSL, JAAS, Cryptography, etc.
Robust

The English mining of Robust is strong. Java is


robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security
problems.
o 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.
o There are exception handling and the type
checking mechanism in Java. All these points
make Java robust.

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.
Portable

Java is portable because it facilitates you to carry


the Java bytecode to any platform. It doesn't
require any implementation.

High-performance

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.

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.
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.

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++.

Java supports dynamic compilation and


automatic memory management (garbage
collection).

Differences between Java and C++ are as


follows:

SR Java C++

1. Platform-independent, Platform
SR Java C++

dependent, should
Java bytecode works
be compiled for
on any operating
different
system.
platforms.

C++ is platform-
It can run on any OS
2. dependent. Hence
hence it is portable.
it is not portable.

Java is both Compiled


C++ is a Compiled
3. and Interpreted
Language.
Language.

Memory
Memory Management
4. Management in
is System Controlled.
C++ is Manual.

It has limited support It strongly


5.
for pointers. supports pointers.

6. Java provides built-in C++ doesn’t have


support for built-in support
multithreading. for threads,
depends on third-
SR Java C++

party threading
libraries.

C++ is both a
Java is only an object- procedural and an
7. oriented programming object-oriented
language. programming
language.

Java uses the (System


C++ uses cin for
class): System.in for
input and cout for
8. input
an output
and System.out for
operation.
output.

Java doesn’t support C++ supports


9.
goto Keyword goto keyword.

C++ supports
10. Java doesn’t support
Structures and
Structures and Unions.
Unions.

11. It supports no global It supports both


scope. global scope and
SR Java C++

namespace scope.

C++ both
12. Java supports only call supports call by
by value. value and call by
reference.

Java is not so
13. C++ is nearer to
interactive with
hardware.
hardware.

Mozilla Firefox,
Wikipedia, LinkedIn, Amazon, Apple
14.
Android OS, Uber, and OS, Spotify,
Minecraft, Adobe Photoshop,
and Youtube.

Advantages and Disadvantages of java :

Advantages:

1. Simple
Java is a simple programming language since it is
easy to learn and easy to understand. Its syntax is
based on C++, and it uses automatic garbage
collection; therefore, we don't need to remove
the unreferenced objects from memory. Java has
also removed the features like explicit pointers,
operator overloading, etc., making it easy to read
and write.

2. Object-Oriented

Java uses an object-oriented paradigm, which


makes it more practical. Everything in Java is an
object which takes care of both data and
behavior. Java uses object-oriented
concepts like object, class, inheritance, encapsula
tion, polymorphism, and abstraction.

3. Secured

Java is a secured programming language because


it doesn't use Explicit pointers. Also, Java
programs run inside the virtual machine
sandbox. JRE also provides a classloader, which is
used to load the class into JVM dynamically. It
separates the class packages of the local file
system from the ones that are being imported
from the network.
4. Robust

Java is a robust programming language since it


uses strong memory management. We can also
handle exceptions through the Java code. Also,
we can use type checking to make our code more
secure. It doesn't provide explicit pointers so that
the programmer cannot access the memory
directly from the code.

5. Platform independent

Java code can run on multiple platforms directly,


I.e., we need not compile it every time. It is right
once, runs anywhere language (WORA) which can
be converted into byte code at the compile time.
The byte code is a platform-independent code
that can run on multiple platforms.

6. Multi-Threaded

Java uses a multi-threaded environment in which


a bigger task can be converted into various
threads and run separately. The main advantage
of multi-threading is that we need not provide
memory to every running thread.
Disadvantages

1. Performance

Java needs to be interpreted during runtime,


which allows it to run on every operating system,
but it also makes it perform slower than the
languages like C and C++. On the other hand, the
C++ program needs to be compiled on each
operating system, directly to binary and
therefore runs faster.

2. Memory consumption

Java program consumes more memory since it


runs on top of Java virtual machine.

3. Cost

Java programming language is a bit costly due to


its higher processing and memory requirements.
We need better hardware to run the Java
program.

4. Less machine interactive

Java lacks when it comes to interacting directly


with machines, making it less viable for the
software that needs to run quickly and run
directly with the machine, as explicit pointers are
also missing in Java.

5. Garbage collection

Java provides automatic garbage collection that


cannot be controlled by the programmer. It
doesn't provide the methods like delete() and
free() to free the memory.

Top 10 Applications of Java

 Desktop GUI Applications


 Mobile Applications
 Artificial intelligence
 Web applications
 Big Data technology
 Gaming applications
 Business applications
 Embedded systems
 Cloud applications
 Scientific applications

Java Applet

Applet is a special type of program that is


embedded in the webpage to generate the
dynamic content. It runs inside the browser and
works at client side.

Advantage of Applet

There are many advantages of applet. They are as


follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running
under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to
execute applet.
Hierarchy of Applet

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

1. Data Types:
- Primitive Data Types:
- `byte`: 8-bit signed integer, range from -128
to 127.
- `short`: 16-bit signed integer, range from -
32,768 to 32,767.
- `int`: 32-bit signed integer, range from -2^31
to 2^31-1.
- `long`: 64-bit signed integer, range from -
2^63 to 2^63-1.
- `float`: 32-bit floating-point number, used for
decimal numbers.
- `double`: 64-bit floating-point number,
higher precision than float.
- `char`: 16-bit Unicode character, representing
a single character.
- `boolean`: Represents true or false values.

- Examples:
```java
int age = 25;
double salary = 50000.50;
char grade = 'A';
boolean isStudent = true;
```

2. Identifiers and Variables:


- Identifiers:
- Should follow the camelCase naming
convention.
- Examples: `variableName`, `calculateTotal`,
`userInput`.
- Should be meaningful and descriptive.

- Variables:
- Must be declared before use.
- Example: `int count = 10;`
- Variables can be assigned values: `count =
20;` or initialized in one line: `int count = 20;`.

- Examples:
```java
// Identifiers
int studentAge;
double averageScore;

// Variables
int count = 10;
String name = "John Doe";
```

3. Operators and Expressions:


- Operators:
- Bitwise operators work on bits of integers.
- Logical operators perform logical AND, OR,
and NOT operations.
- Conditional operator (Ternary) provides a
concise way to write simple if-else statements.

- Expressions:
- Complex expressions can be simplified and
made more readable using parentheses.
- Example: `result = (num1 + num2) * (num3 -
num4);`

- Examples:
```java
int num1 = 10, num2 = 5, num3 = 8, num4 =
2;
int result = (num1 + num2) * (num3 - num4);
```

4. Type Conversion:
- Implicit Conversion (Automatic):
- Occurs when converting smaller data types
to larger ones.

- Explicit Conversion (Casting):


- Necessary when converting larger data types
to smaller ones.
- Examples:
```java
// Implicit Conversion
int num = 10;
double result = num;

// Explicit Conversion (Casting)


double num = 10.5;
int intValue = (int) num;
```

5. Control Flow:
- Conditional Statements:
- `if` statement: Executes a block of code if a
condition is true.
- `else if` statement: Additional conditions to
check.
- `else` statement: Executes if none of the
previous conditions are true.
- `switch` statement: Selects one of many code
blocks to execute.

- Looping Statements:
- `for` loop: Executes a block of code a
specified number of times.
- `while` loop: Repeats a block of code while a
condition is true.
- `do-while` loop: Similar to `while` but
ensures the code block is executed at least once.

- Branching Statements:
- `break`: Terminates the loop or switch
statement.
- `continue`: Skips the rest of the loop and
moves to the next iteration.
- `return`: Exits a method and can return a
value.
- Examples:
```java
// Conditional Statements
int score = 85;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 70) {
System.out.println("Good job!");
} else {
System.out.println("Keep practicing.");
}

// Looping Statements
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
```

6. Arrays:
- Declaration and Initialization:
- Arrays can store multiple values of the same
data type.

- Accessing Elements:
- Elements are accessed using indices, starting
from 0.
- Example: `int value = numbers[2];`

- Array Length:
- The `length` property returns the number of
elements in an array.

- Examples:
```java
// Declaration and Initialization
int[] numbers = new int[5];

// Accessing Elements
numbers[2] = 42;
int value = numbers[2];
```

7. Constants:
- Constants are declared using the `final`
keyword.

- Examples:
```java
final double PI = 3.14159;
final int MAX_VALUE = 100;
```

8. Methods:
- Method Signature:
- Includes the access modifier, return type,
method name, and parameters.
- Method Body:
- Contains the implementation of the method.

- Calling a Method:
- Methods are called using the method name
and passing arguments if needed.

- Examples:
```java
// Method Declaration
public int add(int a, int b) {
return a + b;
}

// Calling a Method
int sum = add(5, 7);
```

9. Using Class Libraries:


- java.lang:
- Provides fundamental classes like `String`
and `Object`.
- Automatically imported in every Java
program.

- java.io:
- Handles input and output operations.
- Example: `FileInputStream`,
`FileOutputStream` for file operations.

- java.math:
- Supports large integer and decimal
arithmetic.
- Example: `BigInteger`, `BigDecimal`.

- java.text:
- Deals with formatting and parsing text.
- Example: `SimpleDateFormat` for date
formatting.
- java.util:
- Offers utilities and data structures.
- Example: `ArrayList` for dynamic arrays,
`HashMap` for key-value pairs.

- Examples:
```java
// java.lang
String name = "John";
Object obj = new Object();

// java.io
// (Example: Reading from a file using
FileInputStream)

// java.math
BigInteger bigInt = new
BigInteger("12345678901234567890");
// java.text
SimpleDateFormat dateFormat = new
SimpleDateFormat("dd/MM/yyyy");

// java.util
ArrayList<String>

You might also like