Unit I
Unit I
UNIT- I
UNIT-I
Java Programming Fundamentals: Introduction to Java, Stage for Java, Origin,
Challenges of Java, Java Features, Java Program Development, Object Oriented Programming.
Java Essentials: Elements of Java Program, Java API, Variables and Literals, Primitive Data
Types, The String class, Variables, Constants, Operators, Scope of Variables & Blocks, Types of Comment
in Java.
Introduction To Java:
Java is an object-oriented, class-based programming language. The intention of using this language
is to give relief to the developers from writing codes or every platform. In the year 1995, java
language was developed by “James Gosling”. It is mainly used to develop we, desktop, and mobile
devices applications. Java makes writing, compiling, and debugging programming easy. It helps
to create reusable code and modular programs. The Java Language is known for its robustness
(मजबूती), Security, and simplicity features.
History: -
It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick
Naughton were the team of “Sun Microsystems” Engineers known as the ‘Green Team’. The green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as JAVA 1.0.
1
JAVA (UGCA-1932)
UNIT- I
Remember that, before we begin creating the program, the Java Development Kit (JDK) must be
properly installed on our system and also path will be set.
1. Creating Program:
We can create a program using Text Editor i.e. Notepad, VS code Editor, Sublime Text Editor,
etc.
Syntax:
{
Public static void main(String args[])
{
System.out.println(“My First Java program”);
}
};
2
JAVA (UGCA-1932)
UNIT- I
Compilation Level:
Once the source code is written, it needs to be compiled into bytecode before it can be executed.
This is the role of the Java compiler. The compiler translates the human-readable source code into
an intermediate form called bytecode, which is a low-level representation of the program. This
bytecode is platform-independent and can be executed on any device with a Java virtual machine
(JVM).
Bytecode Level:
The bytecode is the foundation of Java’s portability. It’s a machine-independent representation of
the source code that can be interpreted by the JVM. This level serves as a bridge between the high-
level source code and the low-level machine code. The JVM, installed on the target device,
interprets the bytecode and translates it into native machine instructions that the device’s hardware
can understand.
Origin 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,
televisions, etc.
Originally C++ was considered to be used in the project but the idea was rejected for several
reasons i.e. C++ required more memory and many more.
James Gosling and his team called their project “Greentalk” and its file extension was .gt and later
became known as “OAK”.
OAK is an image of solidarity (एकजटु ता ) and was 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”.
Gosling and his team had collections of names such as JAVA, DNA, SLIK, RUBY, etc. Java's
name was decided after much discussion since it was so unique.
Java is the name of an ‘island’ in Indonesia where the first coffee (named java coffee) was
produced. James Gosling chose this name while he was having coffee near his office. Note that
JAVA is just a name, not an acronym.
Challenges of Java
In Java Programming, students encounter several common challenges in their learning journey.
These challenges includes difficulties in understanding and applying programming concepts and,
a lack of knowledge in Object-Oriented programming. Students often struggle with problem-
solving approaches and may have misconceptions about certain aspects of the Java language.
The increasing demand for IT professionals, including Java programmers, puts pressure on
institutions to train more students, leading to resource constraints and administrative challenges.
3
JAVA (UGCA-1932)
UNIT- I
To address these challenges, adaptive and adaptable learning environments, video tutorials,
programming tasks, quizzes, and multiple-choice tests have been introduced to help learners.
Tutorials on different platforms have shown the positive impacts of reducing programming errors
and improving students' programming skills.
Educators can provide guidance and support to help students learn successful problem-solving
approaches and avoid unsuccessful ones.
Java Features
4
JAVA (UGCA-1932)
UNIT- I
High Performance
Multithreaded
Distributed
Dynamic
Simple:
Java is designed to be easy to learn. If you understand the basic concept of OOP java, it would be
easy to master.
Java is very easy to learn. It inherits many features from C, C++ and removes complex features
like pointers, operator overloading, multiple inheritance, explicit memory allocation etc. It
provides automatic garbage collection. With a rich set of libraries with thousands of useful
functions.
Object-Oriented:
In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
As a language that has the Object-Oriented feature, Java supports the following fundamental
concepts of OOPs:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Portable:
Java is portable because it allows you to carry the Java bytecode to any platform. It does not require
any implementation and configuration.
Platform Independent:
Java is platform-independent because it is different from other languages like C, C++, etc. Which
are compiled into platform-specific machines while Java is a write-once-run-anywhere (WORA)
language.
A platform is the hardware or software environment in which a program runs. There are two types
of platforms software-based and hardware-based. Java provides a software-based platform.
Secured:
Java is best known for its security. With java, we can develop virus-free systems. It is secured for
the various point of view:
Memory leak
Buffer overflow
5
JAVA (UGCA-1932)
UNIT- I
No explicit pointer
Java Programs run inside virtual machine.
Java language provides these securities by default. Java exception handling mechanism allows
developers to handle almost all types of errors/exceptions which can happen during program
execution. Automatic garbage collection helps maintain the system's memory space utilization.
Robust:
The term robust ensures the strongness of anything. Java is considered strong because:
It uses strong memory management.
There is a lack of pointers that avoid security problems.
Java provides automatic garbage collection which runs on the Java Virtual machine to rid
of objects which are not being used by a Java application anymore.
The are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Interpreted:
In an interpreted language, the source code is executed line by line, with each instruction and
executed sequentially. Java is an interpreted programming language.
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. Java is an interpreted
language that is why is slower than compiled languages e.g., C, C++, etc.
Multi-threaded:
A thread is like separate programs executing simultaneously. We can write Java programs that
deal with many tasks at once because of multi-threaded.
Java’s multi-threading feature allows the developers to construct interactive applications that can
run smoothly.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently/simultaneously in the same program.
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 like garbage collection.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java. This feature
of Java makes us able to access files by calling the methods from any machine on the internet.
6
JAVA (UGCA-1932)
UNIT- I
Java Essentials:
Java supports several data types that can be broadly categorized into primitive and reference
types.
Primetive Types:
The are the most basic data types in Java. They include intergers (int) , floating-point
numbers (double), characters (char), Booleans (Boolean), etc.
Reference Type:
This include objects, arrays, and interfaces. Objects are instances of classes, arrays are
collections of elements of the same type, and interfaces define contracts for classes.
7
JAVA (UGCA-1932)
UNIT- I
Examples:
int myInt = 42; // Primitive Type
double myDouble = 3.14; // Primitive Type
char myChar = 'A'; // Primitive Type
boolean myBoolean = true; // Primitive Type
String myString = "Hello, World!"; // Reference Type
3. Operators:
4. Methods:
Methods are blocks of code that perform specific tasks. They can accept parameters and return
values. They play a crucial role in organizing and reusing code.
Example:
A class is a blueprint for objects. It defines the properties and behaviors that objects of that class
will have.
An object is an instance of a class. It encapsulated data/ fields and behavior/methods.
8
JAVA (UGCA-1932)
UNIT- I
Example:
public class Person { //class
String name;
int age;
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
Person john = new Person(); //objec
john.name = "John";
john.age = 30;
john.sayHello(); // Output: "Hello, my name is John"
Java API
A Java API (Application Programming Interfaces) is a set of classes, interfaces, and methods
provided by the Java platform that allows developers to interact with and utilize various features
and functionalities of the java programming language. APIs provide a standardized way for
applications to communicate with each other or with various services, libraries, or frameworks.
Java APIs are used to perform a wide range of tasks such as:
1. System Interaction:
APIs allow programs to interact with underlying operating system, hardware, and other low-level
system resources.
2. Data Manipulation:
They provide mechanisms for data processing, such as reading and writing files, manipulating
strings, handling data structures, and more.
3. Networking:
Java APIs include classes and methods for network communication, such as creating web servers,
sending HTTP requests, and handling network protocols.
5. Database Access:
APIs enable Java applications to connect and interact with databases.
9
JAVA (UGCA-1932)
UNIT- I
Types of APIs:
There are four types of APIs in Java and they are as follow:
1. Public APIs:
Public APIs are designed to be accessible to developers outside the organization that provides API.
They are intended for public use and often come with documentation, guidelines, and developer
support.
2. Partner APIs:
Partner APIs are specifically designed for selected partners or affiliates of an organization. These
APIs are shared with trusted partners who have established agreements or business relationships
with API provider.
3. Private APIs:
Private APIs, as the name suggests, are internal APIs that are not made available to external
developers or partners. They are used within an organization or enterprise to facilitate
communication and integration between different systems, services, or applications.
4. Composite APIs:
Composite APIs, also known as aggregated APIs, are APIs that combine multiple underlying APIs
or services into a single interface. Composite APIs enable developers to access a combination of
functionalities from different APIs through a single API call.
Java Variables
A variable is a location in memory or storage area to hold data. To indicate the storage area, each
variable should be given a unique name also called an identifier.
here, number is a variable of int data type and we have assigned value 786 to it. The int data type
suggests that the variable can only hold integers. Int the example, we have assigned value to the
variable during declaration. However, it’s not mandatory. You can declare variables and assign
variables separately.
For example:
int number;
number = 786;
10
JAVA (UGCA-1932)
UNIT- I
Note: Java is a statically-typed language. It means that all variables must be declared before they
can be used.
Java programming language has its own set of rules and conventions for naming variables. Here's
what you need to know:
1. Java is case-sensitive. Hence, age and AGE are two different variables. For example,
int age = 24;
int AGE = 25;
System.out.println(age); // prints 24
System.out.println(AGE); // prints 25
2. Variables must start with either a letter or an underscore, _ or a dollar, $ sign. For example,
int age; // valid name and good practice
int _age; // valid but bad practice
int $age; // valid but bad practice
6. If you choose one-word variable names, use all lowercase letters. For example, it's better to
use speed rather than SPEED, or sPEED.
11
JAVA (UGCA-1932)
UNIT- I
Java Literals
Literals are data used for representing fixed values. They can be used directly in the code. For
example,
int a = 1;
float b = 2.5;
char c = 'F';
Here, 1, 2.5, and 'F' are literals.
1.Integer Literals
Integer literals are numeric values (associated with numbers) without any fractional or exponential
part. There are 4 types of integer literals in Java:
binary (base 2)
decimal (base 10)
octal (base 8)
hexadecimal (base 16)
For example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
12
JAVA (UGCA-1932)
UNIT- I
In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.
Note: Integer literals are used to initialize variables of integer types like byte, short, int, and long.
Floating-point Literals
Floating-point literals are numeric literals that have either a fractional form or an exponential form.
For example,
class Main {
public static void main(String[] args) {
// 3.445*10^2
double myDoubleScientific = 3.445e2;
2. Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in a single quote ('')
mark. It is always a type of char.
For example,
char letter = 'a';
Here, a is the character literal.
We can also use escape sequences as character literals.
For example, \b (backspace), \t (tab), \n (new line), etc.
13
JAVA (UGCA-1932)
UNIT- I
3. String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It may
be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.
4. Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.
14
JAVA (UGCA-1932)
UNIT- I
15
JAVA (UGCA-1932)
UNIT- I
Example:
int a = 1000;
int b = -2000
16
JAVA (UGCA-1932)
UNIT- I
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
In the above example, we have created three strings named first, second, and third. Here, we are
directly creating strings like primitive types.
17
JAVA (UGCA-1932)
UNIT- I
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}
}
Output
String: Hello! World
Length: 12
In the above example, the length() method calculates the total number of characters in the string
and returns it.
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
18
JAVA (UGCA-1932)
UNIT- I
Output
First String: Java
Second String: Programming
Joined String: Java Programming
In the above example, we have created two strings named first and second. Notice the statement,
String joinedString = first.concat(second);
Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.
We can also join two strings using the + operator in Java.
19
JAVA (UGCA-1932)
UNIT- I
Output
Strings first and second are equal: true
Strings first and third are equal: false
In the above example, we have created 3 strings named first, second, and third. Here, we are
using the equal() method to check if one string is equal to another. The equals() method checks
the content of strings while comparing them.
Note: We can also compare two strings using the == operator in Java. However, this approach
is different than the equals() method.
2. Char charAt(int i)
Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
20
JAVA (UGCA-1932)
UNIT- I
8. String toLowerCase()
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
21
JAVA (UGCA-1932)
UNIT- I
9. String toUpperCase()
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
Java Variables
A variable is a location in memory or storage area to hold data. To indicate the storage area, each
variable should be given a unique name also called an identifier.
here, number is a variable of int data type and we have assigned value 786 to it. The int data type
suggests that the variable can only hold integers. Int the example, we have assigned value to the
variable during declaration. However, it’s not mandatory. You can declare variables and assign
variables separately.
For example:
int number;
number = 786;
Note: Java is a statically-typed language. It means that all variables must be declared before they
can be used.
Java Constants
As the name suggests, a constant is an entity in programming that is immutable. In other words,
the value that cannot be changed. Java does not directly support the constants. There is an
alternative way to define the constants in Java by using the non-access modifiers static and final.
22
JAVA (UGCA-1932)
UNIT- I
To declare a constant:
In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must be
in capital letters.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;
Where static and final are the non-access modifiers. The double is the data type and PRICE is
the identifier name in which the value 432.78 is assigned.
23
JAVA (UGCA-1932)
UNIT- I
Output:
24
JAVA (UGCA-1932)
UNIT- I
Local scope:
This refers to variables that are defined within a method or block of code. These variables are only
accessible within the method or block where they were declared, and they are not visible to any
code outside of that scope.
Example:
class Scopecheck{
obj.local();
25
JAVA (UGCA-1932)
UNIT- I
OUTPUT
Example 2:
public SumExample
int sum = a + b;
OUTPUT
Instance scope
This refers to variables that are defined as fields of a class (also known as instance variables).
These variables are accessible within the entire class, including any methods, constructors, and
nested classes.
Example:
class Scopecheck{
26
JAVA (UGCA-1932)
UNIT- I
obj.instance = 50;
obj.inst();
obj2.inst();
OUTPUT
27
JAVA (UGCA-1932)
UNIT- I
Example 2:
Static scope
This refers to variables that are defined as static fields of a class. These variables are also accessible
within the entire class, including any methods, constructors, and nested classes. Although they are
shared among all instances of the class; these variables are accessible from anywhere in the code,
even outside the class.
Syntax:
// ...
Example:
class Scopecheck{
System.out.println( "'static' can be accessed throught the class and other classes");
28
JAVA (UGCA-1932)
UNIT- I
Scopecheck.stat = 60;
obj.stat();
obj2.stat();
OUTPUT
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There
are many types of operators in Java which are given below:
1. Arithmetic Operator,
2. Assignment Operator,
3. Logical Operator,
4. Relational Operator,
29
JAVA (UGCA-1932)
UNIT- I
5. Bitwise Operator,
6. Unary Operator,
7. Ternary Operator
8. Shift Operator.
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Example:
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
OUTPUT
15
50
30
JAVA (UGCA-1932)
UNIT- I
Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.
Example:
OUTPUT
13
18
3.Logical Operator
Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the
function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is,
while using AND operator, the second condition is not evaluated if the first one is false. Whereas
while using OR operator, the second condition is not evaluated if the first one is true.
31
JAVA (UGCA-1932)
UNIT- I
AND Operator ( && ) – if( a && b ) [if true execute else don’t]
This operator returns true when both the conditions under consideration are satisfied or are
true. If even one of the two yields false, the operator results false. In Simple terms, cond1
&& cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).
Syntax:
Example:
int a=10;
int b=5;
int c=20;
}}
This operator returns true when one of the two conditions under consideration is satisfied
or is true. If even one of the two yields true, the operator results true.
Syntax:
condition1 || condition2
Example:
32
JAVA (UGCA-1932)
UNIT- I
int a=10;
int b=5;
int c=20;
//|| vs |
}}
Unlike the previous two, this is a unary operator and returns true when the condition under
consideration is not satisfied or is a false condition. Basically, if the condition is false, the
operation returns true and when the condition is true, the operation returns false.
Syntax:
!(condition)
Example:
a = 10, b = 20
4.Relational Operator
Java Relational Operators are a bunch of binary operators used to check for relations between two
operands, including equality, greater than, less than, etc. They return a boolean result after the
comparison.
Syntax:
variable1 relation_operator variable2
33
JAVA (UGCA-1932)
UNIT- I
34
JAVA (UGCA-1932)
UNIT- I
Example:
var1 = 10
var2 = 20
var1 < var2 results in true
35
JAVA (UGCA-1932)
UNIT- I
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
}}
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.
36
JAVA (UGCA-1932)
UNIT- I
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Comments are used to make the program more readable by adding the details of the code.
It makes easy to maintain the code and to find the errors easily.
The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
It can also be used to prevent the execution of program code while testing the alternative
code.
CommentExample1.java
} }
Output:
10
37
JAVA (UGCA-1932)
UNIT- I
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use
single-line comments there). Multi-line comments are placed between /* and */. Any text between
/* and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
CommentExample2.java
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
/* float j = 5.9;
float k = 4.4;
System.out.println( j + k ); */
}
}
Output:
10
Note: Usually // is used for short comments and /* */ is used for longer comments.
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.
Syntax:
/**
*
38
JAVA (UGCA-1932)
UNIT- I
*/
39