0% found this document useful (0 votes)
2 views14 pages

java programming notes1

Cse

Uploaded by

diwakarkhushi69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

java programming notes1

Cse

Uploaded by

diwakarkhushi69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Unit 1

The Genesis of Java


Java is an Object-Oriented programming language developed by James Gosling in the early
1990s. The team initiated this project to develop a language for digital devices such as set-top
boxes, television, etc. Originally C++ was considered to be used in the project but the idea
was rejected for several reasons(For instance C++ required more memory). Gosling
endeavoured to alter and expand C++ however before long surrendered that for making
another stage called Green. James Gosling and his team called their project “Greentalk” and
its file extension was .gt and later became to known as “OAK”.
The name Oak was used by Gosling after an oak tree that remained outside his office. Also,
Oak is an image of solidarity and picked as a national tree of numerous nations like the
U.S.A., France, Germany, Romania, etc. But they had to later rename it as “JAVA” as it was
already a trademark by Oak Technologies. “JAVA” Gosling and his team did a brainstorm
session and after the session, they came up with several names such as JAVA, DNA, SILK,
RUBY, etc. Java name was decided after much discussion since it was so unique.
The name Java originates from a sort of espresso bean, Java. Gosling came up with this
name while having a coffee near his office.
The Java Development Kit (JDK) is a cross-platformed software development environment
that offers a collection of tools and libraries necessary for developing Java-based software
applications and applets. It is a core package used in Java, along with the JVM (Java Virtual
Machine) and the JRE (Java Runtime Environment).

Overview of Java
Java is a class-based, object-oriented programming language that is designed to have as
few implementation dependencies as possible. It is intended to let application
developers Write Once and Run Anywhere (WORA), meaning that compiled Java code
can run on all platforms that support Java without the need for recompilation. Java was
developed by James Gosling at Sun Microsystems Inc. in May 1995 and later acquired by
Oracle Corporation and is widely used for developing applications for desktop, web, and
mobile devices.
Java applications are compiled to byte code that can run on any Java Virtual Machine. The
syntax of Java is similar to C/C++. Bytecode is an intermediate, platform-independent code
generated after Java source code is compiled. It is not directly executed by the operating
system but runs on the Java Virtual Machine (JVM), which translates it into machine-
specific instructions.
Key Features of Bytecode:
 It is stored in .class files after compilation.
 It enables Write Once, Run Anywhere (WORA) functionality.
 It is interpreted or compiled by the JVM at runtime.
 It enhances security and portability across different systems.

Key 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 ease t architecture-neutral ease as bytecode is not
dependent on 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.
How Java Code Executes?
The execution of a Java application code involves three main steps:

How Java Code Executes


1. Creating the Program
Java programs are written using a text editor or an Integrated Development Environment
(IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source code is saved with
a .java extension.
2. Compiling the Program
The Java compiler (javac) converts the source code into bytecode, which is stored in
a .class file. This bytecode is platform-independent and can be executed on any machine with
a JVM.
3. Running the Program
The JVM executes the compiled bytecode, translating it into machine code specific to the
operating system and hardware.
Example Program:
public class HelloWorld {
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
Essential Java Terminologies You Need to Know
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM)
The JVM is an integral part of the Java platform, responsible for executing Java bytecode.
It ensures that the output of Java programs is consistent across different platforms.
 Writing a program is done by a java programmer like you and me.
 The compilation is done by the JAVAC compiler which is a primary Java compiler
included in the Java development kit (JDK). It takes the Java program as input and
generates bytecode as output.
 In the Running phase of a program, JVM executes the bytecode generated by the
compiler.
The Java Virtual Machine (JVM) is designed to run the bytecode generated by the Java
compiler. Each operating system has its own version of the JVM, but all JVMs follow the
same rules and standards. This means Java programs can run the same way on any device
with a JVM, regardless of the operating system. This is why Java is called a platform-
independent language.
2. Bytecode
Bytecode is the intermediate representation of Java code, generated by the Java compiler. It is
platform-independent and can be executed by the JVM.
3. Java Development Kit(JDK)
While we were using the term JDK when we learn about bytecode and JVM. So, as the name
suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), Java Debuggers, Java Docs, etc.
For the program to execute in java, we need to install JDK on our computer in order to create,
compile and run the java program.
4. Java Runtime Environment (JRE)
JDK includes JRE. JRE installation on our computers allows the java program to run,
however, we cannot compile it. JRE includes a browser, JVM, applet support, and plugins.
For running the java program, a computer needs JRE.
5. Garbage Collector
In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a
program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory
management. However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage cannot recover the
memory of objects being referenced.
6. ClassPath
The Classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries
they should be added to the classpath.
Basically everything in java is represented in Class as an object including the main function.
Advantages of Java
 Platform independent: Java code can run on any platform that has a Java Virtual
Machine (JVM) installed, which means that applications can be written once and run
on any device.
 Object-Oriented: Java is an object-oriented programming language, which means
that it follows the principles of encapsulation, inheritance, and polymorphism.
 Security: Java has built-in security features that make it a secure platform for
developing applications, such as automatic memory management and type checking.
 Large community: Java has a large and active community of developers, which
means that there is a lot of support available for learning and using the language.
 Enterprise-level applications: Java is widely used for developing enterprise-level
applications, such as web applications, e-commerce systems, and database systems.
Disadvantages of Java
1. Performance: Java can be slower compared to other programming languages, such as
C++, due to its use of a virtual machine and automatic memory management.
2. Memory management: Java’s automatic memory management can lead to slower
performance and increased memory usage, which can be a drawback for some
applications.

Java Data Types


Data types in Java are of different sizes and values that can be stored in the variable that is
made as per convenience and circumstances to cover up all test cases. Java has two categories
in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double.
The Boolean with uppercase B is a wrapper class for the primitive data type boolean
in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

1. boolean Data Type


The boolean data type represents a logical value that can be either true or false.
Syntax:
boolean booleanVar=true;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
2. byte Data Type
The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful
for saving memory in large arrays.
Syntax:
byte byteVar;
byte b = 4;
Size : 1 byte (8 bits)
3. short Data Type
The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is
used when memory savings matter, especially in large arrays where space is constrained.
Syntax:
short shortVar;
short s = 56;
Size : 2 bytes (16 bits)
4. int Data Type
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
int i = 89;
Size : 4 bytes ( 32 bits )
5. long Data Type
The long data type is a 64-bit signed two’s complement integer. It is used when an int is not
large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
long l = 12121;
Size : 8 bytes (64 bits)
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead
of double) if you need to save memory in large arrays of floating-point numbers. The size of
the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
float f = 4.7333434f;
Size : 4 bytes (32 bits)
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal
values, this data type is generally the default choice. The size of the double data type is 8
bytes or 64 bits.
Syntax:
double doubleVar;
double d = 4.355453532;
Size : 8 bytes (64 bits)
8. char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
char a = 'G';
Size : 2 bytes (16 bits)

Arrays in Java
Arrays are fundamental structures in Java that allow us to store multiple values of the same
type in a single variable. They are useful for storing and managing collections of data.
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same data type. It
is declared and instantiated using the following syntax:
dataType[] arr; (or) dataType []arr; (or) dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization of Java Array
In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated
below:
int a[]={33,3,4,5};

Example:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
33
3
4
5

Multidimensional Array in Java


A multidimensional array in Java is an array of arrays where each element can be an array
itself. It is useful for storing data in row and column format.
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column

Example:
class TestMultiArray {
public static void main(String args[]) {
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Output:
123
456
789

Jagged Arrays in Java


In Java, a jagged array is an array of arrays where each row of the array can have a different
number of columns. This contrasts with a regular two-dimensional array, where each row has
the same number of columns.
Declaring and Initializing a Jagged Array
To declare a jagged array in Java, you first declare the array of arrays, and then you initialize
each row separately with its own array of columns.
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];

Java Operators
Java operators are special symbols that perform operations on variables or values.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-
primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction

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

8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying or
dividing the number by two, respectively. They can be used when we have to multiply or
divide a number by two. The general format ,
number shift_op number_of_places_to_shift;
 << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
 >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
 >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always
0.
9. instanceof operator
The instance of operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format ,
object instance of class/subclass/interface
Example:
Person obj1 = new Person();
System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person));

Output
obj1 instanceof Person: true

You might also like