unit-1 java
unit-1 java
History of java
Java’s history is as interesting as it is impactful. The journey of this
powerful programming language began in 1991 when James Gosling, Mike Sheridan,
and Patrick Naughton, a team of engineers at Sun Microsystems known as the “Green
Team,” set out to create a new language initially called “Oak.” Oak was later
renamed Java, inspired by Java coffee, and was first publicly released in 1995 as Java 1.0.
This initial version provided a no-cost runtime environment across popular platforms,
making it accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0
compiler to strictly comply with its specifications, ensuring its reliability and cross-
platform capabilities.
Java evolved over time, with Java 2 introducing multiple configurations tailored for
different platforms, showcasing its versatility.
In 1997, Sun Microsystems aimed to formalize Java through the ISO standards
body but eventually withdrew from the process.
Despite not formalizing through ISO, Sun Microsystems offered most Java
implementations at no cost, earning revenue by licensing specialized products such as
the Java Enterprise System.
A significant milestone in Java’s history occurred on November 13, 2006, when Sun
Microsystems released a large portion of the Java Virtual Machine (JVM) as free,
open-source software.
By May 8, 2007, the core JVM code was fully available under open-source distribution
terms.
Java was designed with core principles: simplicity, robustness, security, high
performance, portability, multi-threading, and dynamic interpretation. These
principles have made Java a preferred language for various applications, including
mobile devices, internet programming, gaming, and e-business.
Today, Java continues to be a cornerstone of modern software development, widely
used across industries and platforms.
Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code can run on any platform be it Windows, Linux,
or macOS which means if we compile a program on Windows, then we can run it
on Linux and vice versa. Each operating system has a different JVM, but the output
produced by all the OS is the same after the execution of the byte code. That is why we call
java a platform-independent language.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing
the program in the terms of a collection of objects is a way of object-oriented programming,
each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It
eliminates complex features like pointers and multiple inheritances, making it easier
to write, debug, and maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot
of effort into checking errors as early as possible, that is why the java compiler is able to
detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, exception handling, and
memory allocation.
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also, java
programs run in an environment that is independent of the os(operating
system) environment which makes java programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are
connected to each other through an internet connection.
7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a
program. This feature is particularly useful for applications that require high performance,
such as games and real-time simulations.
8. Portability
As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform-independent bytecode can be
taken to any platform for execution makes java portable. WORA(Write Once Run
Anywhere) makes java application to generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It provides architecture-neutral
ease, as bytecode is independent of any machine architecture. It is the primary reason java
is used in the enterprising IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at
some times java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basis where it only compiles those methods that are called making applications to
execute faster.
JDK Environment and tools
Beginners often get confused with JRE and JDK, if you are only interested in
running Java programs on your machine then you can easily do it using Java Runtime
Environment. However, if you would like to develop a Java-based software application
then along with JRE you may need some additional necessary tools, which is called JDK.
JDK=JRE+Development Tools
Java: The Java Application launcher Executes Java application and applets. it replaces the
older jre tool, combining development and deployment functionalities.
Javac: Java compiler converts Java Source code into Java bytecode, producing. Class files.
applet viewer: Runs and debugs Java applets, without a web browser
Jdb: Java debugger provides a command-line interface for debugging Java programs.
JVM: The JVM is a park of the Java platform that executes Java byte code, converting it into
machine code for the host system. it provides an abstraction layer between compiled Java
code and the operating system.
ENCAPSULATION :
Encapsulation is a process of giving controled access to very important aspect of an
object for Performing encapsulation.
1) we identify the important aspect.
2) we have to restric to direct access by declaring the important aspect as private.
(3) we have to give controled access to the Private Member by using Public Seters & geters
Hence we can conclude that encapsulation is process of binding data members with member
functions.
Example:
Class TextBook
{
private int Page-no:
public void setpageno (int x)
{
If(x>0)
{
Page-no=x;
}
else
{
System.out.println(“Invalid Page_no "),
}
}
public int getpage_no();
{
Return Page-no;
}
}
Class Encapsulation
{
public static void main (String []args)
{
TextBook tb=new TextBook();
tb.setpageno (100),
System.out.println(“page no of textbook is " + tb.getpageno());
}
}
INHERITANCE
Inheritance in Java enables a class to inherit properties and actions from another class,
called a superclass or parent class. A class derived from a superclass is called a subclass or
child group. Through inheritance, a subclass can access members of its superclass (fields and
methods), enforce reuse rules, and encourage hierarchy.
Syntax
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Employee
{
float salary=40000;
}
POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many forms.
Examples:
class Bike
{
void run(){System.out.println("running");}
}
ABSTRACT CLASS
In the world of Java programming, abstract classes play an important role in defining
the structure of classes and their behavior in the hierarchy. They provide a blueprint for other
teams to follow, and some methods remain undefined. This flexibility empowers developers
to generate a well-organized and scalable codebase. In this section, we will explore the
concept of abstract classes in Java, examining their features, advantages, and best practices.
A class that is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
Example:
C++ is platform-
It can run on any OS hence it
dependent. Hence it is
is portable.
Portability not portable.
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
Main Method Definition
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are
optional, but we suggest you use them because they are useful to
understand the operation of the program, so you must write comments within
the program.
Package You can create a package with any name. A package is a group of classes
statement that are defined by a name. That is, if you want to declare many classes
within one element, then you can declare it within a package. It is an optional
part of the program, i.e., if you do not want to declare any package, then
there will be no problem with it, and you will not get any errors. Here, the
package is a keyword that tells the compiler that package has been created.
It is declared as:
Ex : package package_name;
Import This line indicates that if you want to use a class of another package, then
statements you can do this by importing it directly into your program.
Example:
Ex : import calc.add;
Interface Interfaces are like a class that includes a group of method declarations. It's
statement an optional section and can be used when programmers want to implement
multiple inheritances within a program.
Class Definition A Java program may contain several class definitions. Classes are the main
and essential elements of any Java program.
Ex : Class classname
Main Method Every Java stand-alone program requires the main method as the starting
Class point of the program. This is an essential part of a Java program. There may
be many classes in a Java program, and only one class defines the main
method. Methods contain data type declaration and executable statements.
Example:
//Name of this file will be "Hello.java"
public class Hello
System.out.println("Hello 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,
String, and Arrays.
Java Primitive Data Types
In Java, primitive data types are the building blocks of data manipulation. These are the basic
data types.
In Java, there are mainly eight primitive data types which are as follows.
In Java, the boolean data type represents a single bit of information with two possible
states: true or false. The size of the Boolean data type is 1 byte (8 bits).
Syntax:
boolean flag;
Example:
Boolean a = false;
Boolean b = true;
The byte data type in Java is a primitive data type that represents an 8-bits signed two's
complement integer. It has a range of values from -128 to 127. Its default value is 0.
Syntax:
byte size;
Example:
byte a = 10;
byte b = -20;
Syntax:
short var;
Example:
short a = 10000;
short b = -5000;
The int data type in Java is a primitive data type that represents a 32-bits signed two's
complement integer. It has a range of values from -2,147,483,648 to 2,147,483,647.
Syntax:
Example
int a = 100000;
int b = -200000;
The long data type in Java is a primitive data type that represents a 64-bits signed two's
complement integer. It has a wider range of values than int, ranging from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Its default value is 0.0L or 0.0l.
Syntax:
Example:
long a = 5000000L;
long b = -6000000L;
The float data type in Java is a primitive data type that represents single-precision 32-
bits IEEE 754 floating-point numbers. It can represent a wide range of decimal values, but it
is not suitable for precise values such as currency. Its default value is 0.0f or 0.0F.
The float data type is useful for applications where a higher range of values is needed and
precision is not critical.
Syntax:
Example:
float f = 234.5f;
The double data type in Java is a primitive data type that represents double-precision 64-bits
IEEE 754 floating-point numbers. Its default value is 0.0. It provides a wider range of values
and greater precision compared to the float data type, which makes it suitable for applications
where accurate representation of decimal values is required.
Syntax:
Example:
double d = 12.3;
The char data type in Java is a primitive data type that represents a single 16-bits Unicode
character. It can store any character from the Unicode character set, which allows Java to
support the internationalisation and representation of characters from various languages and
writing systems.
Syntax:
Example:
char c = 'A';
Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called 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.
Output:
Variable: 10
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
class Student
{
//static variable
static int age;
}
Java Operators
Java operators are special symbols that perform operations on variables or
values. These operators are essential in programming as they allow you to manipulate
data efficiently. They can be classified into different categories based on their
functionality. In this article, we will explore different types of operators in Java,
including arithmetic, unary, relational, logical, and more, along with practical examples.
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate
a value.
- , Negates the value.
+ , Indicates a positive value (automatically converts byte, char, or short to int).
++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
-- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
! , Inverts a boolean value.
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side value must be declared before using it or
should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create shorthand
compound statements. For example, a += 5 replaces a = a + 5. Common compound
operators include:
+= , Add and assign.
-= , Subtract and assign.
*= , Multiply and assign.
/= , Divide and assign.
%= , Modulo and assign.
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less
than. They return boolean results after the comparison and are extensively used in looping
statements as well as conditional if-else statements. The general format is ,
variable relation_operator value
Relational operators compare values and return Boolean results:
== , Equal to.
!= , Not equal to.
< , Less than.
<= , Less than or equal to.
> , Greater than.
>= , Greater than or equal to.
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations, similar
to AND gate and OR gate in digital electronics. They have a short-circuiting effect,
meaning the second condition is not evaluated if the first is false.
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations
of the Binary indexed trees.
& (Bitwise AND): returns bit-by-bit AND of input values.
| (Bitwise OR): returns bit-by-bit OR of input values.
^ (Bitwise XOR): returns bit-by-bit XOR of input values.
~ (Bitwise Complement): inverts all bits (one’s complement).
Java Keywords
In Java, keywords are the reserved words that have some predefined
meanings and are used by the Java compiler for some internal process or represent
some predefined actions. These words cannot be used as identifiers such
as variable names, method names, class names, or object names.
Keywords Usage
Camel’s case in java programming consists of compound words or phrases such that each
word or abbreviation begins with a capital letter or first word with a lowercase letter, rest
all with capital. Here in simpler terms, it means if there are two
Type 2: Methods
Methods should be verbs, in mixed case with the first letter lowercase and with the
first letter of each internal word capitalized.
public static void main(String [] args) {}
As the name suggests the method is supposed to be primarily method which indeed it is as
main() method in java is the method from where the program begins its execution.
Type 3: Variables
Variable names should be short yet meaningful.
Variable names should not start with underscore _ or dollar sign $ characters, even though
both are allowed.
Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
One-character variable names should be avoided except for temporary variables.
Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for
characters.
int[] marks;
double double answer,
Type 5: Packages
The prefix of a unique package name is always written in all-lowercase ASCII
letters and should be one of the top-level domain names, like com, edu, gov, mil, net,
org.
Subsequent components of the package name vary according to an organization’s own
internal naming conventions.
java.util.Scanner;
java.io.*;