Unit 1 - Basics of Programming in Java
Unit 1 - Basics of Programming in Java
rd
BE (IT) III Semester
Java Architecture
Java architecture is a comprehensive framework that includes various components and layers designed to
provide a platform-independent, secure, and robust environment for developing and running Java
applications. The below-mentioned points and diagram will simply illustrate Java architecture:
There is a compilation and interpretation process in Java.
After the JAVA code is written, the JAVA compiler comes into the picture that converts this code
into byte code that can be understood by the machine.
After the creation of bytecode JAVA virtual machine(JVM) converts it to the machine code, i.e.
(.class file)
And finally, the machine runs that machine code.
Java's architecture supports the principles of WORA (Write Once, Run Anywhere), allowing developers to
create platform-independent applications. The modular and layered structure of Java architecture
enhances maintainability, scalability, and the overall quality of Java applications.
1. Default Classpath
When we run a Java program, the JVM automatically uses the default classpath, which includes the
current directory (.). This means that Java will look for classes in the current working directory. However,
relying solely on the default classpath may not be sufficient for more complex projects.
Environment Variable: We can set the CLASSPATH environment variable, which will be used by
the JVM.
export CLASSPATH=/path/to/classes
Note: When using the environment variable, be cautious as it might override the default
classpath. It's often better to use the -cp option to avoid unintentional conflicts.
Manifest File in JAR: If the application is packaged in a JAR file, we can specify the classpath in the
JAR file's manifest.
Class-Path: /path/to/lib/library.jar /path/to/classes
3. Classpath Entries
Classpath entries can be directories containing .class files or JAR files containing compiled classes.
Multiple entries are separated by a platform-specific path separator (semicolon ; on Windows, colon : on
Unix-like systems).
java -cp /path/to/classes:/path/to/lib/library.jar MyClass
4. Wildcards (*)
We can use the wildcard * to include all JAR files in a directory.
java -cp /path/to/lib/*:/path/to/classes MyClass
This includes all JAR files in the /path/to/lib/ directory.
5. Classpath in IDEs
Integrated Development Environments (IDEs) like Eclipse, IntelliJ IDEA, and NetBeans manage the
classpath for you. They typically provide a project configuration where libraries can be added and
dependencies, and the IDE takes care of setting the classpath when running or debugging the application.
Understanding and correctly setting the classpath is crucial for successfully running Java applications,
especially as projects become more complex and involve external libraries or dependencies. Carefully
managing the classpath ensures that the JVM can locate and load the required classes during runtime.
Class in Java
In Java, a class is a blueprint or template that defines the structure and behavior of objects. It
encapsulates data (fields) and behavior (methods). For example,
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method
public void displayInfo() {
System.out.println(year + " " + make + " " + model);
}
car1.displayInfo();
car2.displayInfo();
}
}
In this example:
The Car class has fields (make, model, and year), a constructor, and a method (displayInfo).
The constructor (public Car(String make, String model, int year)) is called when an object is
created, initializing the object's fields.
The displayInfo method prints information about the car.
Objects in Java
Objects are instances of classes. They represent real-world entities and encapsulate data and behavior. In
the example above, car1 and car2 are objects of the Car class.
Here, new Car("Toyota", "Camry", 2022) creates an object of the Car class with specific values for its
fields.
Constructors in Java
A constructor is a special method used to initialize the object's state when it is created.
A constructors acquire the following properties.
Constructors must have the same name as the class within which it is defined it is not necessary
for the method in Java.
Constructors do not return any type while method(s) have the return type or void if does not
return any value.
Constructors are called only once at the time of Object creation while method(s) can be called
any number of times.
In the main method, car1.displayInfo() and car2.displayInfo() invoke the displayInfo method for each car,
printing information about each object.
This demonstrates the creation of objects, the use of constructors for initialization, and the invocation of
methods in Java.
Packages
In Java, a package is a way to organize and group related classes and interfaces. It provides a mechanism
for creating a hierarchical structure in which classes and interfaces can be organized and easily managed.
Packages help prevent naming conflicts, improve code organization, and enhance code reusability. Here
are key points about packages in Java:
Package Declaration
To place a class or interface in a package, you include a package declaration at the beginning of the
source file. The package declaration specifies the package name, and it must be the first non-comment
statement in the file.
package com.example.myapp;
Package Structure
Packages can be organized hierarchically. For instance, the package com.example.myapp is a subpackage
of com.example. The directory structure on the file system reflects the package hierarchy.
src
└── com
└── example
└── myapp
└── MyClass.java
Import Statements
To use classes or interfaces from other packages, you need to use import statements. Import statements
inform the compiler about the location of the classes or interfaces you want to use.
package com.example.myapp;
import java.util.List;
1. Data Types
Data types define the type of data a variable can hold. In Java, data types can be categorized into two
main groups: primitive data types and reference data types.
Primitive Data Types: These are basic data types used to store simple values like numbers and characters.
Java has eight primitive data types:
byte: 8-bit signed integer (values from -128 to 127)
short: 16-bit signed integer (values from -32,768 to 32,767)
int: 32-bit signed integer (values from -2^31 to 2^31-1)
long: 64-bit signed integer (values from -2^63 to 2^63-1)
float: 32-bit floating-point (decimal) number
double: 64-bit floating-point (decimal) number
char: 16-bit Unicode character
boolean: Represents true or false values
Reference Data Types: These data types are used to reference objects, which are instances of classes.
Examples of reference data types include classes, arrays, and interfaces. Unlike primitive types, reference
types don't store the actual data but store a reference (memory address) to where the data is stored.
2. Variables
Variables are named memory locations used to store data of a specific data type. They allow you to work
with and manipulate data within your program. In Java, you must declare a variable before you can use it.
A variable declaration includes its data type and name.
Initializing Variables
Variables can be initialized (assigned an initial value) at the time of declaration or at a later point in the
program.
Example
int count = 10;
// Declares & initializes an integer variable count with the value 10
Examples
// Valid variable names
int numStudents;
double averageScore;
String firstName;
Using Variables
Once a variable is declared and initialized, you can use it in expressions, assignments, and other
operations.
Example
int x = 5;
int y = 3;
int sum = x + y; // Adds the values of 'x' and 'y' and assigns the
result to 'sum'
Conditional Statements
Conditional statements in Java are used to execute different blocks of code based on specified conditions.
These statements allow you to make decisions within your program, which is essential for controlling the
flow of execution. Java provides several conditional statements, including the if, else if, else, and switch
statements. Here's an explanation of each:
I. if Statement
The if statement is the most basic conditional statement in Java. It allows you to execute a block of
code if a specified condition is true. If the condition is false, the code block is skipped.
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}
III.else if Statement
The else if statement is used when you have multiple conditions to test. It allows you to specify
additional conditions to check if the previous conditions are false. You can have multiple else if
blocks.
int score = 75;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 70) {
System.out.println("C");
} else {
System.out.println("F");
}
In the above examples, the code within the appropriate block is executed based on the evaluation of the
specified conditions. The else if and switch statements are used when you have multiple possible
conditions to evaluate. The following key points should be noted, when working with conditional
statements.
Conditions should evaluate to a boolean value (true or false).
You can nest conditional statements within each other to handle complex logic.
The default case in a switch statement is executed when none of the other cases match.
Conditional statements are essential for controlling the flow of your Java programs and making decisions
based on user input, data, or other factors.
Loops
Loops in Java allow you to execute a block of code repeatedly. Java provides several types of loops,
including for, while, and do-while loops.
I. For Loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Branching Statements
Java provides branching statements to control the flow of execution within loops & conditional
blocks.
I. Break Statement
It terminates the current loop or switch statement and transfers control to the statement
immediately following the loop or switch.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}
Control flow allows creating programs that make decisions, repeat actions, and respond to changing
conditions. By combining these control flow constructs, we can create complex and sophisticated Java
applications that perform a wide range of tasks.
Access Modifiers
In Java, access modifiers are keywords used to set the accessibility or visibility of classes, methods, and
variables. They control which other classes or components can access a particular class, method, or
variable. Java provides four types of access modifiers, which are explained as follows.
1. Public
The public modifier is the least restrictive.
Classes, methods, and variables marked as public are accessible from any other class.
For example.
public class MyClass {
public int myVariable;
public void myMethod() {
// Code here
}
}
2. Protected
The protected modifier allows access within the same package and by subclasses, even if they are
in a different package.
For example,
class MyBaseClass {
protected int myProtectedVariable;
}
3. Default (Package-Private):
If no access modifier is specified (default), it is also known as package-private.
Access is limited to the same package. Classes, methods, and variables with default access are not
accessible outside the package.
For example,
class MyPackagePrivateClass {
int myPackagePrivateVariable;
}
4. Private
The private modifier is the most restrictive.
Classes, methods, and variables marked as private are only accessible within the same class.
For example,
Things to be noted
Access modifiers can be applied to classes, interfaces, methods, and variables.
The choice of access modifier depends on the desired level of encapsulation and the design
principles of the program.
When no access modifier is specified for a class, it defaults to package-private.
Access modifiers are crucial for encapsulation and defining the visibility of components in object-
oriented programming. They help in controlling access and maintaining the integrity of the
codebase.
Exception Handling
Exception handling in Java is a mechanism that allows you to handle runtime errors (exceptions)
gracefully, preventing the abrupt termination of the program. In Java, exceptions are objects representing
abnormal conditions that can occur during the execution of a program. The core idea of exception
handling is to separate the normal program flow from error-handling code, making it easier to maintain
and understand. A basic overview of Java exception handling can be explained as follows.
1. Exception Classes:
Exceptions in Java are represented by classes that are subclasses of either Exception or
RuntimeException.
Checked exceptions (subclasses of Exception other than RuntimeException) must be declared
in the method signature or handled using a try-catch block.
Unchecked exceptions (subclasses of RuntimeException) do not require explicit handling.
2. Try-Catch Block:
The try block contains the code that might throw an exception.
The catch block handles the exception if it occurs, providing a block of code to execute when
a specific exception is caught.
3. Finally Block:
The finally block contains code that will be executed regardless of whether an exception is
thrown or not.
It is often used for cleanup activities, such as closing resources (e.g., files, database
connections).
In this example, the divide method throws an ArithmeticException when attempting to divide by zero.
The try block catches this exception, and the corresponding catch block is executed.
In this example, the readFile method may throw a FileNotFoundException if the specified file is not found.
The exception is caught in the try-catch block.
These examples illustrate the basic structure of exception handling in Java, including the use of try, catch,
and finally blocks. It's important to handle exceptions appropriately to improve the robustness and
reliability of your Java applications.