0% found this document useful (0 votes)
28 views39 pages

Unit I

The document outlines the fundamentals of Java programming, including its history, features, and essential concepts such as syntax, data types, and object-oriented programming principles. It details the stages of Java application development, from creating and compiling to running a program, and discusses challenges faced by learners. Additionally, it introduces Java APIs and the importance of variables in Java programming.

Uploaded by

KUSH SHARMA
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)
28 views39 pages

Unit I

The document outlines the fundamentals of Java programming, including its history, features, and essential concepts such as syntax, data types, and object-oriented programming principles. It details the stages of Java application development, from creating and compiling to running a program, and discusses challenges faced by learners. Additionally, it introduces Java APIs and the importance of variables in Java programming.

Uploaded by

KUSH SHARMA
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/ 39

JAVA (UGCA-1932)

UNIT- I

Course Code: UGCA1932 (PTU)


Course Name: Programming in Java
Semester: 5th

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.

Java Programming Fundamentals:

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.

Why it is named Java?


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.

Implementation of a JAVA application program involves the following steps:


1. Creating the program
2. Compiling the Program
3. Running the Program

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”);
}
};

Save this file: File -> Save -> d:\Test.java

2. Compiling the Program:


To compile the program, we just run the Java compiler. With name of the source file on the
“command prompt” can also be run.
If everything is OK, the compiler creates a file called “Test.class” containing the byte code of the
program.

3. Running the Program:


We need to use Java Interpreter to run a program.

Stage for Java


Java Programming operates on four various levels/stages of code execution and translation.
These levels are:
 Source code Level
 Compilation Level
 Bytecode Level
 Machine Code Level

Source Code Level:


At the highest level, we have the source code. This is where programmers create their Java
programs using a human-readable syntax. Java’s syntax is similar to other popular programming
languages, making it easy for developers. The source code is composed of classes and methods
that define the program’s behavior. At this stage, the code is written in plain text and saved with
the “.java” extension.

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

Various features are as follow:


 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Interpreted

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 Program Development

Visit the link for complete Tutorials:


https://www.instructables.com/How-to-Make-Your-First-Computer-Program/

Object Oriented Programming


You will go through OOPs concept into UNIT –II

Java Essentials:

Elements of Java program


Java is a versatile and widely-used programming language known for its platform independence
and robustness. It is employed in a diverse (विविध ) range of applications, from web development
to mobile app creation and even in large-scale enterprise systems. To grasp (पकड़) the essence (तत्ि
) of Java, it’s essential to understand its fundamental elements of Java programming language.

Key components of Java that form the backbone of Java programming:

1. Syntax and Structure:


Java programs are structured in a way that promotes code organization and reusability. The basic
building block is a class that contains fields or variables and methods/functions.
Syntax:
Public class Person {
String name; //Field
Int age; // field
Void sayHello() { //method
System.out.println(“Hello, my name is “+name);
}
}
2. Data Types:

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:

Operators are symbols that perform operations on variables or values.


Example:
Arithmetic Operators: These include + (addition), - (subtraction), * (multiplication), /
(division), % (modulo).
Assignment Operators: These assign values to variables. Examples include =, +=, -=.
Comparison Operators: These are used for comparing values. They include == (equals), !=
(not equals), >, <, >=, <=.
Logical Operators: These are used for combining boolean expressions. They include &&
(and), || (or), ! (not).
Example:
int a = 5;
int b = 3;
int sum = a + b; // sum is now 8

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:

Public int add(int a, int b)


{
Return a+b;
}

5. Class and Objects:

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.

4. User Interface (UI):


Java APIs provide tools for building graphical user interfaces (GUIs) with components like
buttons, windows, and text fields.

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.

Creating Variable in Java:


Here’s how we create a variable in Java.

int number = 786;

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.

Rules for Naming Variables in Java

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

3. Variable names cannot start with numbers. For example,


int 1age; // invalid variables

4. Variable names can't use whitespace. For example,


int my age; // invalid variables
Here, we need to use variable names having more than one word, use all lowercase letters for the
first word and capitalize the first letter of each subsequent word. For example, myAge.

5. When creating variables, choose a name that makes sense.


For example, score, number, level makes more sense than variable names such as s, n, and l.

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.

Types of Literals in Java:


There are the majorly four types of literals in Java:
 Integer Literal
 Character Literal
 Boolean Literal
 String Literal

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

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445*10^2
double myDoubleScientific = 3.445e2;

System.out.println(myDouble); // prints 3.4


System.out.println(myFloat); // prints 3.4
System.out.println(myDoubleScientific); // prints 344.5
}
}
Note: The floating-point literals are used to initialize float and double-type variables.

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.

Primitive Data Types


Primitive data are only single values and have no special capabilities.
There are 8 primitive data types:
1. int data type
2. float data type
3. double data type
4. long data type
5. short data type
6. char data type
7. boolean data type
8. byte data type

14
JAVA (UGCA-1932)
UNIT- I

1.Boolean data Type:


The Boolean data type is used to store only two possible values: true and false.
Example:
boolean one = false;

2.Byte Data Type:


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Exampel:
byte a = 10;
byte b = -20;

3.Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
Example:
short s = 1000;
short r = -500;

4.Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

15
JAVA (UGCA-1932)
UNIT- I

Example:
int a = 1000;
int b = -2000

5.Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1). Its minimum value
is - 9,223,372,036,854,775,808 and maximum value is 9,223,372,036,854,775,807. Its default
value is 0. The long data type is used when you need a range of values more than those provided
by int.
Example:
long a = 1000l;
long b = -2000;
6.Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1= 23.45f;

7.Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3;

8.Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive). The char data type is used to store characters.
Example:
char leeterA = ‘A’;

16
JAVA (UGCA-1932)
UNIT- I

The String class


The string is a sequence of characters. In Java, objects of String are immutable which means a
constant and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “This is a String”;
2. Using new keyword
String s = new String (“This is a String”);
Example:
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

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

Java String Operations:


Java provides various string methods to perform different operations on strings. We will look
into some of the commonly used string operations.
1. Get the Length of a String:
To find the length of a string, we use the length() method. For example,

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.

2. Join Two Java Strings


We can join two strings in Java using the concat() method. For example,

class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";

18
JAVA (UGCA-1932)
UNIT- I

System.out.println("First String: " + first);


// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}

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.

3. Compare Two Strings


In Java, we can make comparisons between two strings using the equals() method. For example,
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);

19
JAVA (UGCA-1932)
UNIT- I

System.out.println("Strings first and second are equal: " + result1);


// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}

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.

String Methods in Java


1. int length()
Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13

2. Char charAt(int i)
Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’

3. String substring (int i)


Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”

20
JAVA (UGCA-1932)
UNIT- I

4. String substring (int i, int j)


Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”

5. String concat( String str)


Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”

6. int indexOf (String s)


Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1

7. Int lastIndexOf( String s)


Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1

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”

10. String trim()


Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”

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.

Creating Variable in Java:


Here’s how we create a variable in Java.

int number = 786;

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.

Example 1: Declaring Constant as Private


ConstantExample1.java
import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
}
}

23
JAVA (UGCA-1932)
UNIT- I

Output:

Example 2: Declaring Constant as Public


public class ConstantExample3
{
//declaring PI as constant
public static final double PI= 3.14;
public static void main(String[] args)
{
printValue();
//trying to assign 3.15 in the constant PI
PI = 3.15;
printValue();
}
void printValue()
{
System.out.print("The value of PI cannot be changed to " + PI);
}
}
Output:

24
JAVA (UGCA-1932)
UNIT- I

Scope of Variables & Blocks


The scope of a variable refers to the portion of a program where the variable can be accessed. The
scope of a variable can be determined by its location in the source code, as well as by any blocks
of code (such as loops or conditional statements) that enclose it.

There are three main types of variable scope in Java:

 Local scope/method level


 Instance scope
 Static scope/class level

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{

public void local()

int local = 10;

System.out.println( "'local' can be accessed only inside this function");

System.out.println( "Scope of local: " + local);

public class main {

public static void main(String[] args) {

Scopecheck obj = new Scopecheck();

obj.local();

25
JAVA (UGCA-1932)
UNIT- I

OUTPUT

Example 2:

public SumExample

public void calculateSum() {

int a = 5; // local variable

int b = 10; // local variable

int sum = a + b;

System.out.println("The sum is: " + sum);

} // a, b, and sum go out of scope here

OUTPUT

The sum is: 15

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

int instance = 20;

public void inst(){

int local = 10;

System.out.println( "'local' can be accessed only inside this function");

System.out.println( "Scope of local: " + local);

System.out.println( "'instance' can be accessed throught the class with normal


functions");

System.out.println( "Scope of instance: " + instance);

public class main {

public static void main(String[] args) {

Scopecheck obj = new Scopecheck();

obj.instance = 50;

obj.inst();

Scopecheck obj2 = new Scopecheck();

obj2.inst();

OUTPUT

27
JAVA (UGCA-1932)
UNIT- I

Example 2:

public class Circle {

double radius; // instance variable

public double calculateArea() {

return Math.PI * radius * radius;

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:

public class Bank {

static double interestRate; // class variable

// ...

Example:

class Scopecheck{

static int stat = 20;

public void stat(){

int local = 10;

System.out.println( "'local' can be accessed only inside this function");

System.out.println( "Scope of local: " + local);

System.out.println( "'static' can be accessed throught the class and other classes");

System.out.println( "Scope of static: " + stat);

28
JAVA (UGCA-1932)
UNIT- I

public class main {

public static void main(String[] args) {

Scopecheck obj = new Scopecheck();

Scopecheck.stat = 60;

obj.stat();

Scopecheck obj2 = new Scopecheck();

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.

1. Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.

Example:

public class OperatorExample{

public static void main(String args[]){

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

2.Java Assignment Operator

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:

public class OperatorExample{


public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}

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

There three types of Logical Operators:

 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:

condition1 && condition2

Example:

public class OperatorExample{

public static void main(String args[]){

int a=10;

int b=5;

int c=20;

System.out.println(a<b&&a<c);//false && true = false

System.out.println(a<b&a<c);//false & true = false

}}

 OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t]

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:

public class OperatorExample{

public static void main(String args[]){

32
JAVA (UGCA-1932)
UNIT- I

int a=10;

int b=5;

int c=20;

System.out.println(a>b||a<c);//true || true = true

System.out.println(a>b|a<c);//true | true = true

//|| vs |

System.out.println(a>b||a++<c);//true || true = true

System.out.println(a);//10 because second condition is not checked

System.out.println(a>b|a++<c);//true | true = true

System.out.println(a);//11 because second condition is checked

}}

 NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

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

!(a<b) // returns false

!(a>b) // returns true

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

Various relational Operators are as follow:


1: Equal to Operator (==)
2: Not equal to Operator (!=)
3: Greater than Operator (>)
4: Less than Operator (<)
5: Greater than equal to (>=)
6: Less than equal to (<=)

Operator 1: ‘Equal to’ operator (==)


This operator is used to check whether the two given operands are equal or not. The operator
returns true if the operand at the left-hand side is equal to the right-hand side, else false.
Syntax:
var1 == var2
Example :
var1 = 10
var2 = 20
var1 == var2 //results in false

Operator 2: ‘Not equal to’ Operator(!=)


This operator is used to check whether the two given operands are equal or not. It functions
opposite to that of the equal-to-operator. It returns true if the operand at the left-hand side is not
equal to the right-hand side else false.
Syntax:
var1 != var2
Example:
var1 = 10
var2 = 20
var1 != var2 //results in true

Operator 3: ‘Greater than’ operator(>)


This checks whether the first operand is greater than the second operand or not. The operator
returns true when the operand at the left-hand side is greater than the right-hand side.
Syntax:
var1 > var2
Example:
var1 = 30
var2 = 20
var1 > var2 results in true

Operator 4: ‘Less than’ Operator(<)


This checks whether the first operand is less than the second operand or not. The operator returns
true when the operand at the left-hand side is less than the right-hand side. It functions opposite to
that of the greater-than operator.
Syntax:
var1 < var2

34
JAVA (UGCA-1932)
UNIT- I

Example:
var1 = 10
var2 = 20
var1 < var2 results in true

Operator 5: Greater than or equal to (>=)


This checks whether the first operand is greater than or equal to the second operand or not. The
operator returns true when the operand at the left-hand side is greater than or equal to the right-
hand side.
Syntax:
var1 >= var2
Example:
var1 = 20
var2 = 20
var3 = 10

var1 >= var2 //results in true


var2 >= var3 //results in true

Operator 6: Less than or equal to (<=)


This checks whether the first operand is less than or equal to the second operand or not. The
operator returns true when the operand at the left-hand side is less than or equal to the right-hand
side.
Syntax:
var1 <= var2
Example:
var1 = 10
var2 = 10
var3 = 9

var1 <= var2 results in true


var2 <= var3 results in false

5. Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a boolean

Java Unary Operator Example1: ++ and –


public class OperatorExample{
public static void main(String args[]){
int x=10;

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 Unary Operator Example 2: ++ and --


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21

}}

6.Java Ternary Operator

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.

Java Ternary Operator Example

public class OperatorExample{


public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5

36
JAVA (UGCA-1932)
UNIT- I

Types of Comment in Java


Java Comments

The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

Why do we use comments in a code?

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

Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment


The single-line comment is used to comment only one line of the code. It is the widely used and
easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by
Java.
Syntax:

//This is single line comment

CommentExample1.java

public class CommentExample1 {

public static void main(String[] args) {

int i=10; // i is a variable with value 10

System.out.println(i); //printing the variable i

} }

Output:
10

37
JAVA (UGCA-1932)
UNIT- I

2) Java Multi Line Comment

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.

3) Java Documentation Comment

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

*We can use various tags to depict the parameter

*or heading or author name

*We can also use HTML tags

*/

39

You might also like