[go: up one dir, main page]

0% found this document useful (0 votes)
58 views53 pages

Java Unit 1

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems. It has a wide range of applications including desktop applications, web applications, enterprise applications, and mobile applications. Java code is compiled into bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture.

Uploaded by

bagwerahul05
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)
58 views53 pages

Java Unit 1

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems. It has a wide range of applications including desktop applications, web applications, enterprise applications, and mobile applications. Java code is compiled into bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture.

Uploaded by

bagwerahul05
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/ 53

JAVA-UNIT I

S.Y.B.Sc. Data Science


Prepared BY: Prof. Sanjana Khemka
Java Programming Language
⚫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.
⚫Applications of Java

⚫Desktop Applications such as acrobat reader,


media player, antivirus, etc.
⚫Web Applications such as irctc.co.in,
javatpoint.com, etc.
⚫Enterprise Applications such as banking
applications.
⚫Mobile
⚫Embedded System
⚫Smart Card
⚫Robotics
⚫Games, etc.
Java Platforms / Editions
1) Java SE (Java Standard Edition)
2) Java EE (Java Enterprise Edition)
3) Java ME (Java Micro Edition ) For Mobile
Applications
4) JavaFX - to develop rich internet applications. It uses
a lightweight user interface API
History of Java
⚫ The history of Java starts with the Green Team. Java
team members (also known as Green Team), initiated
this project to develop a language for digital devices
such as set-top boxes, televisions, etc.
⚫ However, it was best suited for internet programming.
⚫ James Gosling, Mike Sheridan, and Patrick Naughton
initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.
⚫ First it was named a Oak.
⚫ Then it awas renamed as Java in 1995.
⚫ https://www.javatpoint.com/history-of-java
Features of Java
JAVA PLATFORM /
How JAVA Works and The Magic of
Bytecode
⚫As with many other programming languages Java uses
complier to convert human-readable source code into
executable programs.
⚫After compilation Java Compiler creates (.class file)
which is a platform-independent bytecode.
⚫Bytecode is a highly optimized set of instructions
designed to be executed by the JVM.
⚫In its standard form JVM is an interpreter for
bytecode.
⚫Translating a Java program into bytecode helps make
it much easier to run a program in a wide variety of
environments.
⚫To execute Java bytecode, the JVM uses a class loader
to fetch the bytecode from a disk or a network.
⚫Each class file is fed to a bytecode verifier that ensures
that the class is formatted correctly and will not
corrupt memory when it is executed.
⚫The execution unit of the JVM carries out the
instruction specified in the bytecode. The simplest
execution unit is an interpreter. But interpreters are
very slow.
⚫Fortunately there is an alternative to interpreting
code called – JIT (Just in Time) Compilation.
⚫The JIT converts the bytecode to native code
instruction on the user machine just before execution.
JVM (Java Virtual Machine)
⚫VM (Java Virtual Machine) is an abstract machine. It is
a specification that provides a runtime environment in
which Java bytecode can be executed.
⚫JVM acts as a run-time engine to run Java applications.
JVM is the one that actually calls the main method
present in a Java code.
⚫JVMs are available for many hardware and software
platforms (i.e. JVM is platform dependent).
⚫Java applications are called WORA (Write Once Run
Anywhere). This means a programmer can develop
Java code on one system and can expect it to run on
any other Java-enabled system without any
adjustment. This is all possible because of JVM.
JRE (Java Runtime Environment)

⚫The Java Runtime Environment is a set of software


tools that are used for developing Java applications.
⚫It is used to provide the runtime environment.
⚫It is the implementation of JVM. It physically exists.
⚫It contains a set of libraries + other files that JVM uses
at runtime.
⚫The Java Runtime Environment provides the
minimum requirements for executing a Java
application; it consists of the Java Virtual Machine
(JVM), core classes, and supporting files.
JDK (The Java Development Kit )
⚫JDK is a software development environment which is
used to develop Java applications and applets. It
physically exists.
⚫It is a Kit that provides the environment to develop
and execute(run) the Java program.
⚫JDK is a kit(or package) that includes two things
⚫ Development Tools(to provide an environment to
develop your java programs)
⚫ JRE (to execute your java program).
Applet
⚫Applet is a special type of program that is embedded
in the webpage to generate dynamic content.
⚫It runs inside the browser and works at client side.
⚫An applet is embedded in an HTML page using the
APPLET tag and hosted on a web server.
⚫Applets are used to make the website more dynamic
and entertaining.
Advantage of Applet
⚫There are many advantages of applet.
⚫ It works at the client side so less response time.
⚫ Secured
⚫ It can be executed by browsers running under many
platforms, including Linux, Windows, Mac Os etc.
Common Misconception about Java
1. Java is Slow
⚫ Yes, this concept was true regarding Java long back.
⚫ Bust as java matured over the years, this slowness
problem of java has been vanished off.
⚫ Java has evolved to be an effective programming
language that doesn’t have performance issues.
2. Memory-related Complaint
⚫ The garbage collector in Java is executing at poorly
timed intervals which causes the application to halt
for seconds till the collector sweeps and cleans.
⚫ JVM has different garbage collectors that can be fined
tuned from the command line.
3. All Java programs run inside a web page.
4. JavaScript and Java is a simpler.
5. Java is an extension of HTML.
6. The open JDK is for academic’s use and you cannot
use it in a bigger application production system.
4. Java version doesn’t matter
5. Java Installation is a nightmare
6. Applets can read your hard drive and delete your
files
7. You can do nothing in Java without an IDE
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:
⚫ Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
⚫ Non-primitive data types: The non-primitive data
types include Classes, Interfaces, and Arrays.
⚫ Reference - https://www.javatpoint.com/java-data-
types
Operators
⚫ Operator in Java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
⚫ Reference - https://www.javatpoint.com/operators-
in-java
Scanner Class
The Scanner class is used to get user input, and it is
found in the java.util package.
To use the Scanner class, create an object of the class
and use any of the available methods found in the
Scanner class
Create object of Scanner class
import java.util.Scanner;
Scanner sc=new Scanner(System.in);
Methods of Scanner class
String class
In Java, string is basically an object that represents
sequence of char values. An array of characters works
same as Java string.
String is a sequence of characters. In java, objects of
String are immutable which means a constant and
cannot be changed once created.
The java.lang.String class is used to create a string
object.
Creating a String
There are two ways to create string in Java:

● String literal
String s = “GeeksforGeeks”;
● Using new keyword
String s = new String (“GeeksforGeeks”);
Methods of String class
Big Numbers
⚫ If the precision of the basic integer and floating-
point types is not sufficient, we can use other classes
in the java.math package, called BigInteger and
BigDecimal.
⚫ These are classes for manipulating numbers with an
arbitrarily long sequence of digits.
⚫ BigInteger class is used for the mathematical
operation which involves very big integer
calculations that are outside the limit of all available
primitive data types.
⚫ The BigInteger class implements arbitrary precision
integer arithmetic, and BigDecimal does the same
for floating-point numbers.
Methods of java.math.BigInteger class
⚫ BigInteger add(BigInteger other)
⚫ BigInteger subtract(BigInteger other)
⚫ BigInteger multiply(BigInteger other)
⚫ BigInteger divide(BigInteger other)
⚫ BigInteger mod(BigInteger other)
Return the sum, difference, product, quotient, and
remainder of this big integer and other.
⚫ int compareTo(BigInteger other)
⚫ static BigInteger valueOf(long x)
⚫ Returns a big integer whose value equals x.
Reference:
https://www.informit.com/articles/article.aspx?p=10176
6&seqNum=9
Methods of java.math.BigDecimal
class
⚫ BigDecimal add(BigDecimal other)
⚫ BigDecimal subtract(BigDecimal other)
⚫ BigDecimal multiply(BigDecimal other)
⚫ int compareTo(BigDecimal other)
Returns 0 if this big Decimal equals other, a negative
result if this big decimal is less than other, and a
positive result otherwise.
⚫ static BigDecimal valueOf(long x)
Control Flow in Java
⚫ Java compiler executes the code from top to bottom.
The statements in the code are executed according
to the order in which they appear.
⚫ However, Java provides statements that can be used
to control the flow of Java code.
⚫ Such statements are called control flow statements.

Reference: https://www.javatpoint.com/control-flow-
in-java
Control Flow Statements
Array
An array is a collection of similar type of elements which has
contiguous memory location.
We can store only a fixed set of elements in a Java array.
Advantages
⚫ Code Optimization: It makes the code optimized, we can

retrieve or sort the data efficiently.


⚫ Random access: We can get any data located at an index

position.
Disadvantages
⚫ Size Limit: We can store only the fixed size of elements

in the array. It doesn't grow its size at runtime.


Reference: https://www.javatpoint.com/array-in-java
Class
A class is a group of objects which have common
properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be
physical.
A class in Java can contain:
Fields
Methods
Constructors
Object in Java
An entity that has state and behavior is known as an
object e.g., chair, bike, marker, pen, table, car, etc.
It is a physical entity
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
Syntax to create Object
syntax:
classname objectname=new classname(parameters)

where
new - new keyword in Java
The new keyword is used to allocate memory at
runtime.
Example
Scanner sc=new Scanner(System.in);
Object Variable
A reference is nothing but a pointer pointing to the
object. In other words, it is holding the memory address
of the object created by new keyword.
Employee emp = new Employee();
In the above example, emp is a reference to the object
which is created using the new keyword.
Multiple object variables can exist which store the same
reference to an object's memory location.
Employee emp1=emp;
Both emp and emp1 are referring to the same memory
location
Accessor in Java
Accessor methods, also known as getter methods, are
methods that allow to retrieve the value of an object's
private instance variables.
These methods provide read-only access to the object's
state.
public class Person {
private String name;
public String getName() {
return name;
}
}
Mutator Methods in Java
Mutator methods, also known as setter methods, are
methods that allow you to modify the value of an
object's private instance variables.
These methods provide write-only access to the object's
state.
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
LocalDate class in Java
Java LocalDate class is an immutable class that represents
Date with a default format of yyyy-mm-dd.
This class belongs to java.time package
import java.time.LocalDate;
Methods of LocalDate Class
1. static LocalDate now() - It is used to obtain the current
date from the system clock in the default time-zone.
2. LocalDate minusDays(long daysToSubtract) It is used to
return a copy of this LocalDate with the specified
number of days subtracted.
3. boolean isLeapYear() It is used to check if the year is a
leap year, according to the ISO proleptic calendar system
rules.
Reference: https://www.javatpoint.com/java-localdate
Example Program
import java.time.LocalDate;
public class LocalDateExample1 {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Today date: "+date);
System.out.println("Yesterday date: "+yesterday);
System.out.println("Tomorrow date: "+tomorrow);
}
}
Static Members
In Java, static members are those which belongs to the
class and we can access these members without creating
object of the class.
The static keyword in Java is mainly used for memory
management.
There is only one copy of static members in the memory
which can be shared among all the objects of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Note: To create a static member(block, variable,
method, nested class), precede its declaration with the
keyword static.

Characteristics of static keyword:


⚫ Shared memory allocation:

⚫ Accessible without object instantiation:

⚫ Associated with class, not objects:

⚫ Cannot access non-static members:

⚫ Can be overloaded, but not overridden:


Static Variable (field)
A variable preceded with static keyword is known as
static field or variable.
When a variable is declared as static, then a single copy
of the variable is created and shared among all objects
at the class level.
Static variables are, essentially, global variables.
All instances of the class share the same static variable.
example:
static String college=”KES”;
Static Method
When a method is declared with the static keyword, it
is known as the static method.
The most common example of a static method is the
main( ) method.
Any static member can be accessed before any objects
of its class are created, and without reference to any
object.
Methods declared as static have several restrictions:
⚫ They can only directly call other static methods.
⚫ They can only directly access static data.
⚫ They cannot refer to this or super in any way.
class Test
{ // static variable
static int a = 10;
static void m1()
{
a++; System.out.println(a);
}
}
Constructor
• Constructor in java is used to create the instance of
the class.
• Constructors are almost similar to methods except
for two things - its name is the same as the class
name and it has no return type.
• Sometimes constructors are also referred to as
special methods to initialize an object.
• Rules for creating Java constructor
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final,
and synchronized
Types of constructor
⚫ Default constructor (no-arg constructor) - A
constructor is called "Default Constructor" when it
doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
• Parameterized constructor - A constructor which
has a specific number of parameters is called a
parameterized constructor.
Syntax of parameterized constructor:
<class_name>(parameters){}
Method Overloading
• Method overloading in java is a feature that allows a
class to have more than one method with the same
name, but with different parameters.
• Java supports method overloading through two
mechanisms:
• By changing the number of parameters
• By changing the data type of parameters Overloading
by changing the number of parameters A method can
be overloaded by changing the number of
parameters.
• Example –
• void Sum();void Sum(int a);void sum(int a,int b);
Package in Java
A java package is a group of similar types of classes,
interfaces and sub-packages.
There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Class path in Java
CLASSPATH is an environment variable which is used by
Application ClassLoader to locate and load the .class files.
The CLASSPATH defines the path, to find third-party and user-
defined classes that are not extensions or part of Java platform.
The CLASSPATH has a directory name or file name at the end.
Steps to set classpath:
1. Click on the Windows button and choose Control Panel.
Select System
2. Click on Advanced System Settings.
3. A dialog box will open. Click on Environment Variables.
4. If the CLASSPATH already exists in System Variables, click
on the Edit button then put a semicolon (;) at the end.

You might also like