Java Programming Basics and Features
Java Programming Basics and Features
1
Unit 1
Introduction to Java
Java includes a wide range of powerful features that make it a reliable, secure, and easy-to-use
programming language. These features help developers build portable, efficient, and high-performance
applications for different platforms.
Java 2 features
1. Compiled and Interpreted
Java uses both compilation and interpretation, making it a two-stage programming language.
The compiler first converts the source code into platform-independent bytecode.
The interpreter then converts the bytecode into machine code during program execution.
3. Object-Oriented
Java is fully object-oriented because everything is written using objects and classes.
It supports key OOP features such as inheritance, polymorphism, and encapsulation.
Java provides a large set of built-in classes arranged in packages for easy reuse.
2
It uses automatic garbage collection to prevent memory leaks and related issues.
Java provides high security by avoiding pointers and controlling memory access.
5. Distributed
Java is designed for building applications that work across networked environments.
It allows programs to easily access data or objects located on remote systems.
This distributed nature helps multiple programmers collaborate from different locations.
8. High Performance
Java delivers high performance due to its efficient use of bytecode and JVM optimization.
Its execution speed is often comparable to programs written in C or C++.
Multithreading in Java further improves the speed and responsiveness of applications.
1. Ease of Development
J2SE 5.0 introduces features like Generics, Enhanced for Loop, Autoboxing, Enums, Varargs,
Static Import, and Annotations to simplify coding.
These features shift repetitive and reusable code generation to the compiler, reducing manual
work for programmers.
Since the compiler handles most repetitive tasks, the source code becomes more reliable and
less prone to human errors.
3
3. Monitoring and Manageability
Java provides APIs such as JVM Monitoring & Management API, JMX, and Logging APIs
to manage and monitor applications.
These APIs allow developers to track both application-level and JVM-level information in
large deployments.
Tools like jconsole, jps, jstat, and jdbstat help developers monitor JVM performance and
manage running applications.
4. Desktop Client
J2SE 5.0 enhances desktop application development through an improved Swing “Ocean”
look and feel.
This updated UI design helps in creating modern and visually appealing desktop applications.
It also supports OpenGL-based hardware acceleration for building high-performance graphics
applications.
5. Miscellaneous Features
a. Core XML Support
J2SE 5.0 includes built-in support for XML processing using SAX and DOM parsers.
Developers can parse, transform, and validate XML documents directly within Java
applications.
These XML tools enable easy data exchange between systems in a structured format.
4
static
Means the method belongs to the class, not to an object.
JVM can call main() without creating an object of the class.
void
The method does not return any value to the JVM.
main
It is the starting point of every Java program.
JVM begins program execution from this method.
String args[]
It is a String array.
Used to receive command-line arguments.
args is just a variable name—you can rename it (example: String myArgs[]).
Comments are statements written in a program that the Java compiler ignores.
They are used to explain code, improve readability, and help other programmers understand the logic.
Syntax: // comment
Example:
int x = 10; // Declare and initialize variable x
2. Multi-line Comment
Purpose: Used for longer explanations that span multiple lines or to temporarily disable a block of
code. All text between /* and */ is treated as a comment.
Syntax: /* comment */
Example:
/*
* This method calculates the sum of two numbers.
* It takes two integer parameters and returns their sum.
*/
public int add(int a, int b) {
return a + b;
}
5
1.6 Java Program Structure
Suggested
Documentation section
Optional
Package statement
Optional
Import statements
Optional
Interface statements
3. Import Statements(Optional)
Used to include predefined classes from other packages.
Helps to reuse existing functionality.
Example:
import [Link]; // Imports the Scanner class for input
4. Interface Statement(Optional)
Interface is similar to a class. It contains only method declarations.
It is an optional section in a program.
It is used when we want to implement multiple inheritance in Java.
6
// Fields and methods go here
}
Example Program
}
}
Source code
Java Compiler
Byte code
The Java compiler is a program that converts Java source code (saved with .java extension)
into bytecode.
It checks the program for syntax errors and reports them to the programmer.
The compiler does not execute the program; it only translates code.
After successful compilation, it creates a .class file containing the bytecode.
Bytecode
8
The virtual machine code is not machine specific. The machine specific code (known as machine
code) is generated by the Java interpreter by acting as an intermediary between the virtual
machine and the real machine as shown in Fig
9
Chapter 2
Constants , Variables and Datatypes
2.1 Constants
In Java, constants are fixed values that do not change during program execution.
They are also known as literals.
2. Numeric Constant
1. Numeric Constants : Numeric constants represent numbers.
A. Integer Constants (int type):
These constants represent whole numbers without a decimal point.
They represent numeric values and can be written in different number systems.
Java supports four types of integer constants based on number system:
2. Character Constants: These constants represent characters enclosed in single or double quotes.
10
They are of two types:
A. Character Constants (char) : These are single characters enclosed in single quotes.
Must contain exactly one character
Enclosed in single quotes ' '
Example: ‘5’ , ‘;’ , ‘ ’, ‘a’
B. String Constants (String) : These represent a sequence of characters enclosed in double quotes.
Can contain 0 or more characters
Enclosed in double quotes " "
Example: “Java class” ,”1900”, ”3+8”, “v”
}
}
Output:
2. Floating-Point Types:
[Link](weight);
3. Character Type:
The char data type is used to store a single character.
Characters are stored using Unicode, so it can store letters, digits, symbols, etc.
Size: 2 bytes.
Example:
4. Boolean Type:
The boolean data type in Java is used to store true/false values.
It represents logical values and is commonly used in conditions, loops, and decision-making
statements
Java boolean does not have a fixed size (depends on JVM implementation)
boolean: Holds true or false.
Example: boolean flag = true;
boolean isValid = false;
12
2.2.2 Non-Primitive Data Types:
class Student {
int age;
void display() {
[Link]("Student age: " + age);
}}
5. Interfaces
An interface is a collection of abstract methods (methods without body).
It is used to achieve 100% abstraction and multiple inheritance in Java.
Example:
interface Animal {
void eat(); // abstract method
}
2.3 Variables
A variable is a name given to a memory location that stores data.
13
You can also declare multiple variables of the same type:
Syntax: dataType variable1, variable2, variable3……..;
Example: int x, y, z;
Values can be given to variables after it has been declared in two ways:
A. By Assignment Statement:
An assignment statement stores a value into a variable using = operator.
Syntax: variableName = value;
Example: age = 20;
marks = 85.5f;
grade = 'A';
name = "Navya";
It is also possible to declare and assign a variable in a single line:
Syntax: type variableName = value;
Example: int age = 20;
float salary = 25000.50f;
1. Reading an integer
int age;
age = [Link]();
2. Reading a float
float salary;
salary = [Link]();
3. Reading a character
char grade;
grade = [Link]().charAt(0);
4. Reading a string
String name;
name = [Link]();
14
Example:
import [Link];
class VariableExample {
public static void main(String[] args) {
String name;
age = [Link]();
marks = [Link]();
Characteristics
Example:
int a = 10;
double price = 99.5;
char grade = 'A';
15
2. Dynamic Initialization (Run-time Initialization)
Dynamic initialization means assigning a value during program execution, not at declaration time.
Characteristics
Value is decided at runtime
Usually depends on:
o user input
o method return value
o expressions and calculations
More flexible than static initialization
Example:
int sum = a + b; // variable sum value calculated at runtime
Example:
public class ImplicitConversion {
public static void main(String[] args) {
16
2.5.2 Explicit Type Conversion (Narrowing)
Explicit type conversion in Java is the process of manually converting a larger data type into a smaller
data type using a cast operator.
It is called narrowing because the destination type has a smaller range than the source type.
Example:
float b = 10.5;
int a = (int)b; // a becomes 10 (data loss)
Example:
public class ExplicitConversion {
public static void main(String[] args) {
17
Chapter 3:
Operators in Java
}
Output:
Arithmetic Operators:
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
18
2. Relational operators
Relational operators in Java are used to compare two values or expressions. They always return a
boolean result: true or false.
These operators check relationships such as equality, inequality, greater than, or less than. They are
mainly used in conditional statements (if, loops).
}
}
Output:
Relational Operators:
a == b: false
a != b: true
a > b: false
a < b: true
a >= b: false
a <= b: true
3. Logical operators
Logical operators in Java are used to combine multiple boolean expressions or conditions and return a
boolean result.
They are mainly used in decision-making (if, else-if), loops, and complex condition checks. These
operators work only on boolean values.
19
Operator Description Explanation
&& Logical AND Returns true only if both conditions are true.
|| Logical OR Returns true if any one of the condition is true.
! Logical NOT Reverses the boolean value (true → false, false →
true).
Example:
class LogicalDemo {
// AND (&&)
[Link]("(a > 5) && (b > 15): " + ((a > 5) && (b > 15)));
// OR (||)
[Link]("(a > 15) || (b > 15): " + ((a > 15) || (b > 15)));
// NOT (!)
[Link]("!(a == b): " + !(a == b));
}
}
Output:
Logical Operators:
(a > 5) && (b > 15): true
(a > 15) || (b > 15): true
[Link] operators
Assignment operators in Java are used to assign values to variables. They can also combine assignment
with arithmetic operations.
The basic assignment operator (=) sets the variable value. Compound assignment operators reduce the
writing of long expressions like a = a + b.
20
5. Increment and Decrement operators
Syntax:
condition ? value_if_true : value_if_false;
Example:
class TernaryDemo {
Result: b is greater
7. Bitwise operator
21
Returns true if both values are equal; otherwise false.
Used in conditions, loops, and comparisons.
Example:
8. Special operators
These include two commonly used special operators:
A. instanceof Operator
The instanceof 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. Checks whether an object belongs to a specific class.
Example:
public class InstanceExample{
Output: true
true
false
B. Dot Operator .
The dot operator is used to access members of a class or an object. It allows us to:
2. Access fields (variables) of a class or an object.
3. Invoke methods of a class or an object.
4. Access inner classes and interfaces.
Example:
class Student {
int age = 20;
void display() {
22
}
class DotOperatorDemo {
public static void main(String[] args) {
// Creating object
Student s = new Student();
// Using dot operator to access variable and method
23
Chapter 4
Control Structures in Java
Control structures are statements in Java that control the flow of execution based on conditions or
[Link] help the program decide, repeat, or choose actions.
3.1. If Statement
There is another way of putting if`s together when multipath decisions are involved. A multipath
decision is a chain of `if`s in which the statement associated with each `else is an if. It takes the
following general form:
if (condition1){
statement-1;
else if (condition2){
statement-2;
25
else if (condition3){
statement-3;
. . .}
statement-n;
else{
default-statement;
statement-x;
This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the rest of the ladder). When
all if conditions become false, then the final else containing the default-statement will be executed.
[Link]("Grade A");
[Link]("Grade B");
[Link]("Grade C");
} else {
[Link]("Fail");
Output: Grade B
26
3.1.4 Nesting of If...Else Statements
When a series of decisions are involved, we may have to use more than one if...else statement in
nested form as follows.
if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the
second test. If the condition-2 is true, the statement-1 will be executed, otherwise the statement-2
will be evaluated and then the control is transferred to the statement-x.
if (a > b) {
if (a > c) {
} else {
} else {
if (b > c) {
} else {
27
}
Example: Program to display the day of the week based on number (1–7)
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:[Link]("Sunday");
break;
case 2:[Link]("Monday");
break;
case 3:[Link]("Tuesday");
break;
case 4:[Link]("Wednesday");
break;
28
case 5:[Link]("Thursday");
break;
case 6: [Link]("Friday");
break;
case 7: [Link]("Saturday");
break;
default: [Link]("Invalid day number");
}
}
}
Output: Tuesday
3.3 Ternary Operator
The ternary operator is a shortened form of the if–else statement.
It evaluates a condition and returns one of two values:
One value if the condition is true. Another value if the condition is false
It is mainly used to write simple decisions in a compact form.
Syntax:
condition ? value_if_true : value_if_false;
Example:
public class TernaryExample {
public static void main(String[] args) {
int score = 75;
String result;
result = (score >= 50) ? "Pass" : "Fail";
[Link]("The result is: " + result);
}
}
In this example:
We have a variable score set to 75.
The ternary operator checks if score is greater than or equal to 50.
If it is true, result is assigned "Pass".
If it is false, result is assigned "Fail".
The program then prints the result, which will be "Pass" in this case.
This concise form helps reduce the need for multiple lines of code and makes simple
conditional assignments more readable.
29
Chapter 5
Looping Structures
In Java, looping allows you to execute a block of code repeatedly based on a condition. The Java
language provides three constructs for performing loop operations.
while loop
do while loop
for loop
The program then continues with the next statement after the loop.
Braces { } are needed only if there are two or more statements in the body.
30
5.2 The Do While loop
The do…while loop is used when the body of the loop must be executed at least once.
Unlike the while loop, the condition is tested after the body is executed.
On reaching the do statement, the loop body is executed first.
After execution, the test condition is checked.
If the condition is true, the loop body runs again.
This process repeats until the condition becomes false.
Since the condition is checked at the end, it is called an exit-controlled loop.
Therefore, the body of a do…while loop is always executed at least once.
Syntax:
do
{
body of the loop
} while (test condition);
int i = 10;
do {
i--;
}
Output: 10 9 8 7 6
The for loop is another entry-controlled loop that provides a more concise loop control structure.
The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment.
The general form of the for loop is:
for (initialization ; test condition ; increment)
{
body of the loop
}
31
[Link](i + " ");
}
}
}
Output: 2 4 6 8 10
Syntax: break;
Example:
public class BreakExample {
public static void main(String[] args) {
}
}
Output:
i=1
i=2
i=3
i=4
5. Continue statement
During the loop operations, it may be necessary to skip a part of the body of the
loop under certain conditions. Like the break statement, Java supports another
similar statement called the continue statement. However, unlike the break which
causes the loop to be terminated, the continue, as the name implies, causes the loop
to be continued with the next iteration after skipping any statements in between. The
continue statement tells the compiler, "SKIP THE FOLLOWING STATEMENTS
AND CONTINUE WITH THE NEXT ITERATION".
Syntax: continue;
32
Example:
public class ContinueExample {
public static void main(String[] args) {
33
Question Bank
34
What is automatic (implicit) type conversion? Give example
28.
What is the purpose of [Link] ().Give an example.
29.
Write the syntax of simple if statement with example.
30.
Give the syntax of declaring a symbolic constant with example.
35