Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Unit 1 - Basics of Programming in Java

Uploaded by

sudin khanal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Unit 1 - Basics of Programming in Java

Uploaded by

sudin khanal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Advanced Programming with Java

rd
BE (IT) III Semester

Unit 1: Basics of Programming in Java


o Java Architecture, Class Paths, Sample Program
o Classes, Objects, Constructors
o Packages and Data Types
o Conditional Statements
o Access Modifiers
o Exception Handling
o Java Collections

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.

Fig. 1.1: Java Architecture

Compiled By: Er. Shirish Raj Sharma 1


Advanced Programming with Java
rd
BE (IT) III Semester

The key components of Java architecture include the following.


 Java Virtual Machine (JVM)
The Java Virtual Machine is a crucial part of Java's architecture. It abstracts the underlying
hardware and provides a runtime environment for Java applications. The JVM is responsible for
interpreting or compiling Java bytecode into machine code that can be executed by the host
machine. It enables Java's platform independence, allowing Java applications to run on any device
with a compatible JVM.
 Java Runtime Environment (JRE)
The JRE is a package of software components that includes the JVM, Java class libraries, and
supporting files. It provides the runtime environment needed for executing Java applications and
applets. Users must have the JRE installed on their machines to run Java programs.
 Java Development Kit (JDK)
The JDK is a full-fledged software development kit that includes the JRE and additional tools for
Java development. Developers use the JDK to write, compile, and debug Java applications. It
contains the javac compiler, debugger, documentation generator (javadoc), and other utilities
essential for software development.
 Java Class Library
The Java Class Library, also known as the Java Standard Edition (SE) library, is a collection of pre-
built classes and packages that provide a wide range of functionality. These classes cover areas
such as I/O, networking, utilities, data structures, and more. The Java Class Library simplifies
application development by offering reusable components and standardizing common
programming tasks.
 Java Application Programming Interface (API)
The Java API is a set of rules and tools for building software applications. It includes packages,
classes, interfaces, and methods that developers use to create Java applications. The API defines
the standard way Java components should interact, providing a consistent and predictable
development environment.
 Java Compiler
The Java compiler (javac) translates Java source code into bytecode. Java source files have a .java
extension, and the compiler generates corresponding bytecode files with a .class extension.

Compiled By: Er. Shirish Raj Sharma 2


Advanced Programming with Java
rd
BE (IT) III Semester

Bytecode is an intermediate representation that is platform-independent and can be executed on


any device with a compatible JVM.
 Security Architecture
Java has a robust security model designed to protect users from malicious code. The security
architecture includes features such as the Java Security Manager, which defines the access
permissions for Java applications, and the ability to run Java applets in a restricted sandbox
environment.
 Garbage Collector
Java includes an automatic memory management system known as the Garbage Collector. It is
responsible for reclaiming memory occupied by objects that are no longer in use, preventing
memory leaks and improving the efficiency of memory utilization.
 Java Language
The Java programming language itself is a fundamental part of Java architecture. It is designed to
be simple, object-oriented, and familiar to many programmers. Java's syntax and semantics are
carefully defined to ensure consistency and ease of use.
 Java EE (Enterprise Edition) and Java ME (Micro Edition)
In addition to Java SE (Standard Edition), there are two other editions of Java: Java EE for
developing enterprise-level applications and Java ME for mobile and embedded systems. Each
edition builds upon the core Java architecture but includes additional libraries and features
tailored to specific application domains.

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.

Compiled By: Er. Shirish Raj Sharma 3


Advanced Programming with Java
rd
BE (IT) III Semester

Class Path in Java


In Java, the classpath is a parameter that tells the Java Virtual Machine (JVM) where to look for user-
defined classes and packages. It specifies the locations in the file system or in JAR files where Java should
search for compiled bytecode (.class files) corresponding to the classes used in a Java application.
The classpath is crucial for the JVM to locate and load classes when they are referenced during the
execution of a Java program. The following are the key aspects of the classpath in Java.

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.

2. Setting the Classpath


The classpath can be set in several ways:
 Command Line: We can specify the classpath using the -cp or -classpath option when running a
Java program from the command line.
java -cp /path/to/classes MyClass

 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

Compiled By: Er. Shirish Raj Sharma 4


Advanced Programming with Java
rd
BE (IT) III Semester

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.

6. Order of Classpath Entries


The order of classpath entries matters. If a class is found in multiple locations, Java will use the first
occurrence it finds. This can lead to unexpected behavior, so it's essential to manage the classpath
carefully.

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.

Compiled By: Er. Shirish Raj Sharma 5


Advanced Programming with Java
rd
BE (IT) III Semester

Class, Objects & Constructor


In Java, classes, objects, and constructors are fundamental concepts in object-oriented programming
(OOP). These are explain with examples as follows.

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,

public class Car {


// Fields
String make;
String model;
int year;

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

// Main method (entry point for the program)


public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Toyota", "Camry", 2022);
Car car2 = new Car("Honda", "Civic", 2021);

// Accessing methods of the Car class

Compiled By: Er. Shirish Raj Sharma 6


Advanced Programming with Java
rd
BE (IT) III Semester

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.

Car car1 = new Car("Toyota", "Camry", 2022);


Car car2 = new Car("Honda", "Civic", 2021);

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.

Compiled By: Er. Shirish Raj Sharma 7


Advanced Programming with Java
rd
BE (IT) III Semester

In the Car class, the constructor looks as follows.

public Car(String make, String model, int year) {


this.make = make;
this.model = model;
this.year = year;
}
 The this keyword refers to the current object being created.
 The constructor parameters (make, model, year) are used to set the values of the object's fields.
When an object is created using new Car("Toyota", "Camry", 2022), the constructor is called, and the
object's fields are initialized with the provided values.

In the main method, car1.displayInfo() and car2.displayInfo() invoke the displayInfo method for each car,
printing information about each object.

When the program is run, it will output as follows.

2022 Toyota Camry


2021 Honda Civic

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:

Compiled By: Er. Shirish Raj Sharma 8


Advanced Programming with Java
rd
BE (IT) III Semester

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;

public class MyClass {


// class members go here
}

Package Naming Conventions


Package names in Java follow a reverse domain naming convention. For example, if a company owns the
domain "example.com," it might use the package name com.example for its classes. This helps ensure
uniqueness and avoids naming conflicts.

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;

public class MyClass {


// You can now use classes from the java.util package, e.g., List
}

Compiled By: Er. Shirish Raj Sharma 9


Advanced Programming with Java
rd
BE (IT) III Semester

Data Types and Variables


In Java, data types and variables are fundamental concepts that allow you to work with data, store values,
and manipulate information within your programs. The different data types and variables used in Java are
explained below with example.

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.

Syntax for Variable Declaration


dataType variableName;
Example
int age; // Declares an integer variable named 'age'

Compiled By: Er. Shirish Raj Sharma 10


Advanced Programming with Java
rd
BE (IT) III Semester

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

Variable Naming Rules


 Variable names must start with a letter, underscore (_), or a dollar sign ($).
 After the first character, variable names can include letters, numbers, underscores, and dollar
signs.
 Variable names are case-sensitive (e.g., 'myVar' and 'myvar' are different variables).
 Java reserved words (e.g., 'int', 'float', 'class') cannot be used as variable names.

Examples
// Valid variable names
int numStudents;
double averageScore;
String firstName;

// Invalid variable names (syntax errors)


int 2ndPlace; // Starts with a number
char #symbol; // Contains a special character #
boolean class; // Reserved word 'class' is used

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'

Compiled By: Er. Shirish Raj Sharma 11


Advanced Programming with Java
rd
BE (IT) III Semester

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.");
}

II. if-else Statement


The if-else statement extends the if statement by allowing you to specify an alternative code block to
execute if the condition is false.
int age = 15;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}

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

Compiled By: Er. Shirish Raj Sharma 12


Advanced Programming with Java
rd
BE (IT) III Semester

System.out.println("C");
} else {
System.out.println("F");
}

IV. switch Statement


The switch statement allows selecting one of many code blocks to execute based on the value of a
variable or expression. It's particularly useful when we have a single value that can match multiple
cases.
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ...
default:
System.out.println("Invalid day");
}

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

Compiled By: Er. Shirish Raj Sharma 13


Advanced Programming with Java
rd
BE (IT) III Semester

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

II. While Loop


int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}

III. Do-While Loop


int num = 1;
do {
System.out.println(num);
num++;
} while (num <= 5);

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

Compiled By: Er. Shirish Raj Sharma 14


Advanced Programming with Java
rd
BE (IT) III Semester

II. Continue Statement


Skips the current iteration of a loop and continues with the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skip iteration when i is 5
}
System.out.println(i);
}

III. Return Statement


Exits the current method and optionally returns a value to the caller.
public int add(int a, int b) {
return a + b; // Return the sum of a and b
}

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

Compiled By: Er. Shirish Raj Sharma 15


Advanced Programming with Java
rd
BE (IT) III Semester

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

public class MyDerivedClass extends MyBaseClass {


public void myMethod() {
myProtectedVariable = 10; // Accessing protected variable
from the superclass
}
}

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,

Compiled By: Er. Shirish Raj Sharma 16


Advanced Programming with Java
rd
BE (IT) III Semester

public class MyClass {


private int myPrivateVariable;
private void myPrivateMethod() {
// Code here
}
}

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.

Compiled By: Er. Shirish Raj Sharma 17


Advanced Programming with Java
rd
BE (IT) III Semester

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

Example 1: Handling ArithmeticException


public class ExceptionExample1 {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This line may throw
ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block always executed.");
}
}

static int divide(int a, int b) {


return a / b;
}
}

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.

Compiled By: Er. Shirish Raj Sharma 18


Advanced Programming with Java
rd
BE (IT) III Semester

Example 2: Handling FileNotFoundException


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ExceptionExample2 {


public static void main(String[] args) {
try {
readFile("nonexistent_file.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} finally {
System.out.println("Finally block always executed.");
}
}

static void readFile(String fileName) throws FileNotFoundException


{
File file = new File(fileName);
Scanner scanner = new Scanner(file); // This line may throw
FileNotFoundException
// Code to read from the file
scanner.close();
}
}

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.

Compiled By: Er. Shirish Raj Sharma 19

You might also like