Java 1st Unit
Java 1st Unit
Computers are powerful tools capable of performing complex operations at very fast
speeds. CPU relies on binary sequences (it means —strings of 0s and 1s—) because
the CPU only understands machine language. Writing instructions in binary for even
simple tasks would be difficult and error-prone for humans. This is where programming
languages come into play, acting as a bridge between human-readable instructions and
the binary sequences understood by computers.
The CPU (Central Processing Unit) is the brain of a computer. It follows a series of steps
to process instructions:
Programming languages, like English or any natural language, need translators for a CPU
to understand them. These translators are categorized into two types:
1. Compilers
• A compiler translates the entire source code of a program into machine code
before execution.
• Once compiled, the machine code can be executed directly by the CPU without the
need for further translation.
• Examples of compiled languages include C, C++, and Go.
2. Interpreters
• An interpreter processes the code line by line, translating and executing each
instruction sequentially.
• Interpreters are more flexible but often slower compared to compilers because
the translation happens during runtime.
• Examples of interpreted languages include Python, Ruby, and JavaScript.
Introduction to Java
Java is one of the most popular languages, it was introduced in 1995 by Sun Microsystems
(now owned by Oracle Corporation). Its unique features like platform independence and
robustness have made it the preferred choice for millions of developers globally.
Here, we are going to discuss the reasons for the popularity of the Java Programming
language
1. Platform Independent
One of the key reasons for Java's popularity is platform independence. Java achieves
platform independence through its unique compilation and runtime process. Before we
talk about how Java is platform-independent let's discuss the concept of a platform. A
platform is the combination of hardware and software environment where a program
runs. For example Windows, macOS, and Linux.
How Java Works?
Java’s compilation process is different from programming languages like C/C++. When
we write a Java program, the Java compiler compiles it into an intermediate, platform-
independent code called bytecode. This bytecode can run on any platform that has
JVM(Java Virtual Machine) installed.
The Java Virtual machine is a software responsible for running Java bytecode on a
physical machine. Each platform (Windows, Linux, macOS) has its own implementation
of the JVM. However, the bytecode remains the same which ensures that Java programs
are truly platform-independent. As a programmer, you don’t need to worry about
installing the JVM separately, as it comes bundled with the JDK installation.
2. Popular
Java is a very popular language. Java covers over 3 billion devices worldwide and has a
community of 9 million developers and is the primary language for Android development.
3. Simple
Java syntax is very straight forward and very easy to learn. Java removes complex
features like pointers and multiple inheritance, which makes it more beginner friendly.
4. Secure
• Built-in Safeguards: Java has features to stop harmful code from running.
• Runtime Checks: Java checks the code while it’s running to ensure nothing
dangerous happens.
• Protects Your System: This helps prevent viruses or malicious programs from
causing damage.
5. Statically Typed
In Java every variable must be explicitly declared with a type, which minimizes runtime
errors.
• Java borrows much of its syntax and structure from C/C++, such as curly braces
and the use of semicolons.
• Java eliminates complexities like pointers and manual memory management.
• Java requires explicit declarations of variables. Java is more organized and better
at avoiding error while running
• In Python you do not need to specify the type of a variable
JDK stands for Java Development Kit. It is a software development kit that provides tools
and libraries for developing Java applications.
• Java Virtual Machine (JVM): The JVM is the engine that runs Java programs. It
converts bytecode into machine code to execute your program. The JVM ensures
Java's "Write Once, Run Anywhere" capability.
• Java Class Libraries: These are pre-written code libraries that help simplify
complex tasks.
• Together, the JVM and class libraries form the Java Runtime Environment (JRE),
which is required to execute Java applications.
JRE stands for Java Runtime Environment. It is required to run the Java Program. It
provides the libraries, JVM, and other components necessary to execute Java applications.
JVM stands for Java Virtual Machine. JVM is called an abstract virtual machine because it
does not exist physically, but it is a kind of specification that provides a secure runtime
environment to execute the bytecode generated through the compiler, JVM invokes the
main ( ) method present in the Java program. JVM is the part of JRE.
Output
Hello, World
Explanation: The "Hello World!" program consists of three primary components: the Test
class definition, the main method, and the source code comments. The following explanation
will provide you with a basic understanding of the code:
1. Class Definition
Syntax:
class Test
• Test is the name of the class (an identifier). The class name must match the file name
([Link])
• Everything inside the class is enclosed within { and }
2. Main Method
Syntax:
3. Printing Output
Syntax:
[Link]("Hello, World!");
4. Comments
Multi-line Comments
Start with /* and end with */. Used for multi-line explanations.
Single-line Comments
Begin with // and end at the line break. Used for brief explanations.
Important Points
In Java, Tokens are the smallest elements of a program that is meaningful to the
compiler. They are also known as the fundamental building blocks of the program.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators
1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing
so, we are trying to assign a new meaning to the keyword which is not allowed.
Eg : int, float, if, else, break, continue etc
2. Identifiers
Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore (_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords
as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value.
3. Constants/Literals
Constants are also like normal variables. But the only difference is, their values cannot
be modified by the program once they are defined. Constants refer to fixed values.
They are also called as literals. Constants may belong to any of the data type.
Syntax:
These statements are used to declare variables, methods, or classes. They introduce new
entities into the program and specify their type and often their initial value.
2. Expression Statements:
These statements govern the order in which other statements are executed, allowing for
decision-making and repetition.
• Decision-Making Statements:
• if-else statement: Executes one block if a condition is true, and another if it's false.
• for loop: Executes a block of code a specific number of times or iterates over
collections.
• do-while loop: Similar to while, but guarantees at least one execution of the loop
body.
• Jump Statements:
• break statement: Exits from a loop or a switch statement.
• continue statement: Skips the rest of the current loop iteration and proceeds to the
next.
• return statement: Exits from the current method and optionally returns a value.
4. Block Statements:
Eg: if (condition) {
Java command-line argument is an argument, i.e., passed at the time of running the
Java program. In Java, the command line arguments passed from the console can be
received in the Java program, and they can be used as input. The users can pass the
arguments during the execution, bypassing the command-line arguments inside
the main( ) method.
int a=[Link](args[0);
int b=[Link](args[1]);
[Link](a+b);
}
}
Variables in Java
A variable is a name given to a memory location. It is the basic unit of storage in a program.
Examples:
Variable Naming
Java has specific rules and conventions for naming variables:
Rules
• Variable names can include letters (a-z, A-Z), numbers (0-9), underscore (_),
and dollar sign ($).
• Variable names must not begin with a number.
• Reserved keywords (e.g., else, for, while) cannot be used as variable names.
First, one is a Statically typed language where each variable and expression type is already
known at compile time. Once a variable is declared to be of a certain data type, it cannot hold
values of other data types. For example C, C++, and Java.
The other is Dynamically typed languages. These languages can receive different data types
over time. For example Ruby, Python
Java is statically typed and also a strongly typed language because, in Java, each type of
data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as
part of the programming language and all constants or variables defined for a given program
must be described with one of the data types.
1) Primitive Data Types
Primitive data types are the basic or built-in data types provided by java to store values.
There are again classified into Non-numeric and numeric data types.
These data types are used for textual or logical data. There are two categories in it:
a) Boolean Type
In Java, the boolean data type is used to store true or false values. It is one of the primitive
data types in Java.
Syntax:
boolean a=true;
The default value of Boolean type is false when declared inside the class as it is treated as
instance variable.
-> Here true or false values are not strings, so no quotes required. Here true or false are
Boolean literals.
Eg:
class Asc{
//boolean boolval=true;
Output:
-> The default value of char is ‘\u0000’ which is a null character in Unicode. Generally it is a
space when the char value is declared inside the class.
Range: 0 to 65,535
These data types are used to represent numbers, either whole numbers (integers) or floating-
point(decimals).
a) Integer Type
1) byte
-> The default value of byte is 0 when declared inside the class.
2) short
-> The default value of short is 0 when declared inside the class.
3) int
-> The default value of int is 0 when declared inside the class.
4) long
-> The default value of long is 0 when declared inside the class
b) Floating-point Type
1) float
-> The default value of float is 0.0 when declared inside the class.
-> The default value of double is 0.0 when declared inside the class.
Non-primitive data types are also known as reference types. Unlike primitive types which
store actual values, non-primitive types store references (addresses) to memory locations
where data is stored.
1. String:
Unlike primitive types, it supports many built-in methods (e.g., length(), toUpperCase()).
2. Array:
A container object that holds multiple values of the same data type.
3. Class:
4. Object:
An instance of a class.
Escape sequences in java are special characters preceded by a backslash (\), that are used to
represent characters that are either invisible, non-printable, printable or have a special
meaning in strings and characters.
They help format output or represent characters that are hard to type directly, such as
newline, tab, or double quotes.
Comments
Comments are lines in a java program that are ignored by the compiler. They are used to:
2) Multi-line Comments:
-> Used for long explanations generally used for the multiple lines of comments.
Eg: /* this is
a multi line
comment*/
3) Documentation comments
Programming style refers to a set of guidelines and conventions that make your Java code:
Type Casting:
Type casting in Java is the process of converting a variable from one data type to another. This
is crucial when performing operations involving different data types or when converting
between primitive data types and their corresponding wrapper classes.
A lower data type is transformed into a higher one by a process known as widening type
casting. Implicit type casting and casting down are some names for it. It occurs naturally.
Since there is no chance of data loss, it is secure. Widening Type casting occurs when:
• The target type must be larger than the source type.
• Both data types must be compatible with each other.
2) Explicit Type Casting (Narrowing Type Casting):
The process of downsizing a bigger data type into a smaller one is known as narrowing type
casting. Casting up or explicit type casting are other names for it. It doesn't just happen by
itself. If we don't explicitly do that, a compile-time error will occur. Narrowing type casting
is unsafe because data loss might happen due to the lower data type's smaller range of
permitted values. A cast operator assists in the process of explicit casting.
Scope of a Variable in Java:
The scope of a variable in Java defines the region of the program where that variable can be
accessed and its lifetime in memory. Java has three primary types of variable scope:
1) Local Variables:
• Accessibility: Only accessible within the block where they are declared and
any nested blocks.
• Lifetime: Created when the block is entered and destroyed when the block is
exited.
• Scope: Declared within a class but outside any method, constructor, or block.
• Lifetime: Created when the class is loaded into memory by the JVM and
persists for the entire duration of the program's execution.
Static methods:
➢ The keyword static means "belonging to the class, not to any specific object".
➢ When a variable or method is marked static. It can be accessed without creating any object.
➢ Only one copy exists in the memory for the entire class.
Precedence and Associativity of operators:
In Java, precedence and associativity determine the order in which operators are evaluated
in expressions.
Precedence:
Precedence defines which operator is evaluated first when two different operators appear
in an expression.
Associativity:
Arithmetic operators:
Arithmetic operators in Java are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulo (remainder). These operators
work with primitive numeric types like int, float, double, long, etc.
Eg: +, -, *, /, %
Assignment Operators
Assignment operators in Java are used to assign values to variables. The most basic one is =,
but Java provides many compound assignment operators that combine arithmetic or bitwise
operations with assignment.
In Java, arithmetic operations on smaller data types like byte, short, or char are promoted to
int during evaluation. This is called automatic type promotion in expressions.
Output:
Increment and decrement operators
In Java, the increment (++) and decrement (--) operators are unary operators used to increase
or decrease a variable’s value by 1.
These operators help simplify code, especially in looping, counter logic, and array indexing.
Prefix:
++a or --a
Here variable is updated before its value is used
Postfix:
a++ or a--
Ternary Operator:
The Ternary Operator is a shorthand way of writing simple if-else conditions in a single line.
It is called "ternary" because it works with three operands.
Syntax:
20
Relational Operators:
Relational operators in Java are used to compare two values or expressions. They return a
boolean result (true or false) based on the comparison.
They are called "relational" because they test the relationship between two operands — like
greater than, equal to, etc.
Eg: ==
!=
>=
<=
Output:
Boolean logical operators in Java are used to perform logical operations on boolean expressions
(true or false). These operators are mostly used in decision-making statements (if, while, etc.)
and in expressions that evaluate conditions.
Returns true only if both operands are true else it returns false.
2. || (Logical OR)
Returns true if at least one operand is true and returns false if both operands are false.
Output:
Syntax:- !expr
Output:
false
Bitwise Operators:
Bitwise operators work on individual bits. It works with integer types (byte, short, int, long).
When a bitwise operation is performed, each bit of the particular number is treated as an
individual based on the operation.
2. Bitwise OR (|)
This operator is a binary operator, denoted by '|'. It returns bit by bit OR of input values, i.e.,
if either of the bits is 1, it gives 1, else it shows 0.
The signed right shift operator shifts all bits towards the right by a certain number of specified
bits. It is denoted by >>.
When we shift any number to the right, the least significant bits (rightmost) are discarded and
the most significant position (leftmost) is filled with the sign bit. (i.e. 0 for positive and 1 for
negative)
1073741821
Control Statements:
If-statement:
The if statement is the simple decision-making statement. If a certain condition is true then
a block of statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Flow Chart:
Eg:
2. If-else statement
If a certain condition is true then a block of statements is executed otherwise the else block
of statements will be executed.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
Flow chart:
3. nested-if Statement
A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
If-else-if ladder:
In Java, the if-else-if ladder is used to execute one block of code from multiple conditional
options. It checks conditions in sequence from top to bottom and executes the first true
condition. Once a condition is true, the rest are skipped.
Syntax:
if (condition1) {
} else if (condition2) {
} else {
}
Switch statement:
The switch statement in Java is a multi-way branch statement. It allows you to execute
one block of code among many alternatives based on the value of a single expression.
It's a cleaner alternative to multiple if-else-if statements when comparing the same
variable against many values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
Loops in programming allow a set of instructions to run multiple times based on a condition.
In Java, there are three types of loops:
• for loop
• while loop
• do-while loop
1) for loop
The for statement includes the initialization, condition, and increment/decrement in one line.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Flow chart:
In Java, a while loop is a control flow statement that allows code to be executed repeatedly
based on a boolean condition.
Syntax:
while (condition) {
}
Flow Chart:
do-while loop:
In Java, a do-while loop is a control flow statement that executes a block of code at least
once, and then repeats it as long as the condition evaluates to true.
This makes it different from a while loop, which checks the condition before executing the
code.
Syntax:
do {
} while (condition);
Flow Chart:
Break Statement:
The Break Statement in Java is a control flow statement used to terminate loops and switch
cases. As soon as the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first statement after the loop.
Syntax:
break;
Flow chart:
Continue:
The continue statement in Java is a control flow statement used within loops (for, while, and
do-while) to skip the current iteration and proceed to the next iteration of the loop.
Syntax:
Continue;
Flow Chart: