0% found this document useful (0 votes)
15 views

Report 126

Uploaded by

pawanjhuriya89
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)
15 views

Report 126

Uploaded by

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

An

Industrial Training Report


on
Java Programming Language
Submitted in partial fulfillment for the award of degree of
Bachelor of Technology
In
Computer Science and Engineering

Submitted to: Submitted By:


Dr. Pradeep Jha Mahi Kansal
HOD-CSE/IT/AI&DS/IOT/CYBER SECURITY
23EGJCS126

Department of Computer Science & Engineering


Global Institute of Technology
Jaipur (Rajasthan)-302022
Session: 2024-25

i
JAVA/CSE

Certificate

i
Session 2024-25
JAVA/CSE

Acknowledgement

I take this opportunity to express my deep sense of gratitude to my ITS coordinator Mr.
Hemant Mittal Assistant Professor and Ms. Kritika Assistant Professor Department of
Computer Science and Engineering, Global Institute of Technology, Jaipur, for his valuable
guidance and cooperation throughout the Practical Training work. She provided constant
encouragement and unceasing enthusiasm at every stage of the Practical Training work.
I am grateful to our respected Dr. I. C. Sharma, Principal GIT for guiding me during
Industrial Training period
I express my indebtedness to Dr. Pradeep Jha, Head of Department of Computer Science
and Engineering, Global Institute of Technology, Jaipur for providing me ample support
during my Industrial Training period.
Without their support and timely guidance, the completion of our Industrial Training would
have seemed a farfetched dream. In this respect we find ourselves lucky to have mentors of
such a great potential.

Place: GIT, Jaipur

Mahi Kansal
23EGJCS126
B.Tech. III Semester, II Year, IT

ii
Session 2024-25
JAVA/CSE

Abstract

This report provides a comprehensive overview of the Java programming language,


exploring its history, key features, and essential programming concepts. Starting with an
introduction to Java’s origins and its rise in the software industry, the report highlights
Java's platform independence, object-oriented principles, robustness, and versatility, which
make it a preferred choice for building secure, scalable, and efficient applications across
diverse domains.

The core of the report delves into Java’s fundamental syntax, keywords, and data handling
mechanisms. It explains how Java structures its programs, manages variables, and controls
execution flow through loops and conditionals, offering illustrative examples for clarity.
Additionally, the object-oriented nature of Java is discussed, emphasizing concepts such as
inheritance, polymorphism, abstraction, and encapsulation.

Further chapters focus on practical aspects of Java development, such as exception handling
and file input/output (I/O), with real-world examples to demonstrate how developers
manage errors and interact with external data. The report concludes with two detailed Java
projects: a Guess The Number Game and a Hungama Game. These projects highlight the
application of key concepts in real-world scenarios, reinforcing the importance of
mastering Java’s robust features.

Overall, the report offers a holistic guide to understanding and implementing Java, from
basic syntax to more advanced features, making it an ideal resource for both beginners

iii
Session 2024-25
JAVA/CSE

Table of Contents

Certificate ......................................................................................................................................................ii

Acknowledgement .....................................................................................................................................iii

Abstract ......................................................................................................................................................... iv

Table of Content .......................................................................................................................................... v

List of Figures ..................................................................................................................... vi

List of Tables ..................................................................................................................... vii

List of Symbols .................................................................................................................viii

Chapter 1. Introduction ................................................................................................ 1


1.1 What is Java…………………………………………………………………....1
1.2 Brief history and development of Java……………………………………...…1
1.3 Importance in the software industry…………………………………………...3
1.4 Overview of key features………………………………………………………5
Chapter 2. Java Syntax and Fundamentals .............................................................. ...7
2.1 Basic Syntax…………………………………………………….…….…….....7
2.2 Java Keyword………………………………………………………….………8
2.3 Data Type and Variable……………………………………………….…….…9
2.4 Operators……………………………………………………………………...10
2.5 Control Flow Statements………………………………………………...……11
2.6 Array………………………………………………………………………….13
2.7 Methods………………………………………………………………………13
2.8 Comments………………………………………………………………….…14
2.9 Input and Output………………………………………………………….…..14
Chapter 3. Object-Oriented Programming(OOP) in Java ....................................... 15
3.1 Class and Objects………………………………………………………….….15
3.2 .Encapsulasion……………………………………….……..………….….….16
3.3 Inheritance……………………………………………..….……….…....…....17
3.4 Polymorphism……………………………………..……………...……….…18
3.5 Abstraction………………………………………...………...…..…..…...…..19
3.6 Constructor………………………………………………………..……….…20

iv
Session 2024-25
JAVA/CSE

3.7 ‘this’ keyword…………………………………………………………..…....22

Chapter 4. Exeption Handaling and File I/O ............................................................. 23


4.1 Introduction to Exception……………………………………………...……..23
4.2 Try, Catch, and Finally Blocks………………………………………..……..23
4.3 Throwing Exceptions…………………………………………………...……25
4.4 Creating Custom Exceptions………………………………………..….….....25
4.5 File Input and Output………………………………………………..….……26
4.6 Reading from a File……………………………………………….…….……27
4.7 Writing to a File…………………………………………………………...…28
4.8 Ussing Scanner for File Input…………………………………….……..……29
4.9 Handaling File Exeptions………………………………………….…………30

Chapter 5. …………………………………………………………………………….31
5.1 Conclusion………………………………………………………….………..31
5.2 Reference…………………………………………………………..…....…..32

v
Session 2024-25
JAVA/CSE

List of Figures

Fig 1.1 History of Jana …………………………………………………………………..3


Fig 2.1 Syntax of Java……………………………………………………….…..…..…...8
Fig 2.2 Control Flow in Computer Program…………………………………………....14
Fig 3.1 OOP Concept…………………………………………………………………...17
Fig 4.1 Source code 1…………………………………………………………….…..…27
Fig 4.2 Output 1………………………………………………………………………...28
Fig 4.3 Source code 2………………………………………………………….……......29
Fig 4.4 Output 2…………………………………………………………………….…..30

vi
Session 2024-25
JAVA/CSE

List of Table

Table.1 Keywords In Java ...................................................................................................................... 10


Table.2 Data Types ................................................................................................................................... 11
Table.3 Difference between PP and OOP .......................................................................................... 26

vii
Session 2024-25
JAVA/CSE

Chapter 1
Introduction

1.1 What is Java?

Java is a high-level, object-oriented programming language developed by Sun


Microsystems in the mid-1990s.

It is designed to be platform-independent, allowing developers to write code that can run


on any device equipped with a Java Virtual Machine (JVM).

1.2 Brief history and development of Java

1. Origins (1991)

Java was conceived by James Gosling and his team at Sun Microsystems. Originally named
Oak, it was designed for interactive television but was soon recognized for broader
applications.

2. First Public Release (1995)

Oak was renamed Java and officially released as Java 1.0. The slogan “Write Once, Run
Anywhere” (WORA) emphasized its platform independence through the use of the Java
Virtual Machine (JVM).

3. Java 2 (1998)

Introduced significant enhancements, including the Swing GUI toolkit and the Collections
Framework. Java 2 was aimed at enterprise applications and further established Java’s
capabilities.

4. Java 5 (2004)

A major update that added features like generics, metadata annotations, and the enhanced
for loop. This version marked a shift towards more powerful programming constructs.

1
Session 2024 - 25
JAVA/CSE

5. Java SE 6 (2006)

Focused on performance improvements, scripting support through JavaScript, and


enhancements to the Java Platform API.

6. Java SE 7 (2011)

Introduced features like the try-with-resources statement, the diamond operator for type
inference, and improved support for file I/O (NIO.2).

7. Java SE 8 (2014)

A landmark release that introduced lambda expressions, the Stream API, and the new Date
and Time API. This version significantly improved functional programming capabilities in
Java.

8. Java SE 9 (2017)

Introduced the module system (Project Jigsaw), allowing developers to modularize


applications for better maintainability.

9. Java SE 10 and Beyond (2018–Present)

Java adopted a new release cadence with feature releases every six months. Subsequent
versions introduced features like local-variable type inference (var), improvements in
garbage collection, and new APIs.

10. Current State

Java remains one of the most popular programming languages, widely used in web
applications, enterprise software, mobile applications (Android), and more. Its strong
community support and extensive ecosystem of libraries and frameworks continue to drive
its development

2
Session 2024 - 25
JAVA/CSE

Fig 1.1 History of Java

1.3 Importance in the software industry

1. Widespread Adoption and Versatility

Java is a general-purpose language that can be used across various domains—web


applications, mobile apps (especially Android), enterprise software, desktop applications,
scientific computing, big data processing, and more.

It is the primary language for Android development, which has a dominant share in the
mobile OS market.

2. Enterprise Solutions

Java is a go-to language for building enterprise-level applications. Many large companies
rely on Java because of its scalability, reliability, and robust ecosystem of frameworks like
Spring, Hibernate, and Java EE.

The financial services sector, including banks and insurance companies, use Java
extensively for transaction processing systems.

3
Session 2024 - 25
JAVA/CSE

3. Platform Independence

Java’s ability to run on any platform with a JVM (Java Virtual Machine) makes it highly
adaptable in the industry. This feature, "Write Once, Run Anywhere" (WORA), has
contributed to its longevity and adoption in varied environments.

4. Mature Ecosystem

Java has a rich set of APIs, libraries, and frameworks that speed up the development
process, enabling developers to build complex systems efficiently.

The Java ecosystem includes robust tools like Eclipse, IntelliJ IDEA, Maven, and Gradle,
which aid in development, debugging, and deployment.

5. Community Support and Regular Updates

Java has one of the largest developer communities in the world, ensuring active support,
documentation, and forums for learning and problem-solving.

The language continues to evolve with regular updates, introducing features that keep it
modern and competitive with newer languages.

6. Security

Java's built-in security features—like bytecode verification, secure class loading, and
garbage collection—make it a strong choice for building secure applications, particularly
in industries like banking, healthcare, and e-commerce.

7. Job Market Demand

Due to its extensive use in enterprises, Java developers are consistently in high demand.
Knowledge of Java is often a requirement for a variety of software development roles,
especially in backend systems and full-stack development.

4
Session 2024 - 25
JAVA/CSE

1.4 Overview of key features (platform independence, object-


oriented nature)

1. Object-Oriented Programming (OOP)

Java is a fully object-oriented language, which promotes concepts like inheritance,


encapsulation, polymorphism, and abstraction. Everything in Java revolves around objects
and classes, making it modular, flexible, and easier to maintain.

2. Platform Independence

Java follows the principle of "Write Once, Run Anywhere" (WORA). Programs written in
Java are compiled into bytecode, which can be run on any device equipped with a Java
Virtual Machine (JVM), regardless of the underlying platform (Windows, Mac, Linux,
etc.).

3. Robust and Secure

Java is designed with security features such as bytecode verification, secure class loading,
and runtime exception handling. It has automatic memory management through garbage
collection, which prevents memory leaks and other common issues found in lower-level
languages.

4. Simple and Familiar Syntax

Java’s syntax is similar to C++ but with simpler memory management and fewer complex
features, making it easy for developers, especially those with a C/C++ background, to learn
quickly.

5. Multithreading

Java supports multithreading, which allows multiple threads to execute concurrently. This
feature is essential for building high-performance applications, especially for tasks like
processing large datasets, handling multiple network requests, or performing background
tasks.

5
Session 2024 - 25
JAVA/CSE

6. High Performance

Java's performance is enhanced through Just-In-Time (JIT) compilation. The JIT compiler
converts Java bytecode into machine code at runtime, speeding up execution by allowing
frequently used parts of the code to be optimized for performance.

7. Distributed Computing

Java has built-in support for developing distributed applications. Technologies like Remote
Method Invocation (RMI) and CORBA (Common Object Request Broker Architecture)
make it easier to build applications that can run across multiple machines connected by a
network.

8. Dynamic and Extensible

Java is designed to be dynamic, which means it can adapt to evolving environments. New
classes, methods, and libraries can be added without affecting existing applications. The
dynamic class loading mechanism and runtime information gathering further enhance this
flexibility.

9. Rich API

Java provides a comprehensive Application Programming Interface (API) that includes


libraries for input/output (I/O), networking, data structures, graphics, security, and much
more. This rich set of libraries simplifies the development of complex applications.

10. Memory Management (Automatic Garbage Collection)

Java uses an automatic garbage collection mechanism, which means developers don’t have
to manually manage memory allocation and deallocation. This reduces the risk of memory
leaks and makes Java applications more reliable.

6
Session 2024 - 25
JAVA/CSE

Chapter 2

Java Syntax and Fundamentals

2.1Basic Syntax

Fig 2.1 Syntax of Java

Structure of a Java Program: Explain the basic structure of a Java program, including the
placement of classes, methods, and the `main()` method.

Example:

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

Explanation:

`public class HelloWorld`: Every Java program must have at least one class.

7
Session 2024 - 25
JAVA/CSE

public static void main(String[] args)`: The `main` method is the entry point of the program.

`System.out.println()`: Used to print messages to the console.

Case Sensitivity: Java is case-sensitive, so `MyClass` and `myclass` would be treated as


two different classes.

Curly Braces `{}`: Used to define a block of code. Every method and class must use curly
braces.

Semicolon `;` Every statement in Java ends with a semicolon.

2.2 Java Keywords

Java has a set of reserved words, or keywords, that have predefined meanings in the
language. These cannot be used as identifiers (variable names, method names, etc.).

Common Keywords:

Access Modifiers: `public`, `private`, `protected`

Class Definition: `class`, `interface`

Control Flow Statements: `if`, `else`, `switch`, `case`, `while`, `do`, `for`, `break`,
`continue`

Object-Oriented Keywords: `this`, `super`, `extends`, `implements`

Others: `final`, `static`, `return`, `void`, `try`, `catch`, `finally`, `new`

Example:

public class Test {

private int number; // 'private' is a keyword

8
Session 2024 - 25
JAVA/CSE

Table.1 Key Words

2.3 Data Types and Variables

Java is a statically typed language, meaning all variables must be declared with a data type
before they can be used.

Primitive Data Types:

int: Integer values.

float, double: Floating-point numbers.

char: Single 16-bit Unicode character.

boolean: True or false values.

Example:

int age = 21;

float price = 19.99f;

boolean isJavaFun = true;

char grade = 'A';

Reference Data Types: Objects, arrays, and more complex structures are stored as
references to memory locations.

9
Session 2024 - 25
JAVA/CSE

Variable Declaration: Variables in Java must be declared with a type before use, and you
can optionally initialize them.

Example:

String name = "John";

int number;

number = 10; // Declaration followed by initialization

Table.2 Data types

2.4 Operators

Java provides a wide variety of operators for performing different operations.

Arithmetic Operators: `+`, `-`, `*`, `/`, `%`

Comparison Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`

Logical Operators: `&&`, `||`, `!`

Assignment Operators: `=`, `+=`, `-=`, `*=`, `/=`

Increment/Decrement Operators: `++`, `--`

10
Session 2024 - 25
JAVA/CSE

Example:

int x = 5;

int y = 10;

int z = x + y; // Arithmetic operation

boolean result = (x > y); // Comparison operation

2.5 Control Flow Statements

Java provides various control flow mechanisms to manage the execution of code.

Conditional Statements:

`if`, `else if`, `else`

Example:

if (x > 0) {

System.out.println("x is positive");

} else {

System.out.println("x is non-positive");

Switch Statement: Used to execute one out of several blocks of code.

Example:

int day = 3;

switch(day) {

case 1:

System.out.println("Sunday");

11
Session 2024 - 25
JAVA/CSE

break;

case 2:

System.out.println("Monday");

break;

default:

System.out.println("Other Day");

Loops:

`for`, `while`, `do-while`

Example (for loop):

for (int i = 0; i < 5; i++) {

System.out.println(i);

Fig 2.2 Control Flow in Computer Program

12
Session 2024 - 25
JAVA/CSE

2.6 Arrays

Arrays in Java are objects that store multiple values of the same type. The size of an array
is fixed once it is created.

Declaration and Initialization:

int[] numbers = new int[5]; // Declaration with size 5

numbers[0] = 10; // Initializing the first element

Iterating Over Arrays:

int[] arr = {1, 2, 3, 4, 5};

for (int num : arr) {

System.out.println(num);

2.7 Methods

Methods in Java are blocks of code that perform a specific task. Every Java program must
have at least one method, which is `main()`. Methods can accept parameters and return
values.

Method Declaration:

public int add(int a, int b) {

return a + b;

Method Invocation:

int sum = add(5, 10); // Calling the add method

13
Session 2024 - 25
JAVA/CSE

2.8 Comments

Java supports three types of comments:

Single-line comment: `// This is a single-line comment`

Multi-line comment: `/* This is a multi-line comment */`

Javadoc comment: `/** This is a Javadoc comment */`

Example:

// This is a single-line comment

int x = 5; /* This is an inline comment */

2.9 Input and Output

Java uses classes like `Scanner` to take user input and `System.out` for output.

Example of Input:

import java.util.Scanner;

public class InputExample {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = sc.nextLine();

System.out.println("Hello, " + name);

14
Session 2024 - 25
JAVA/CSE

Chapter 3

Object-Oriented Programming (OOP) in Java

Fig 3.1 OOP Concepts

3.1 Classes and Objects

Class Definition: Explain what a class is and how it serves as a blueprint for creating
objects.

Example

public class Car {

String brand;

int year;

public void startEngine() {

System.out.println("Engine started");

15
Session 2024 - 25
JAVA/CSE

Object Creation: Demonstrate how to create an object from a class and access its members.

Example:

Car myCar = new Car(); // Create an object of Car

myCar.brand = "Toyota";

myCar.startEngine(); // Call method

3.2 Encapsulation

Definition: Encapsulation is the practice of wrapping the data (variables) and code
(methods) together as a single unit and restricting direct access to some of an object’s
components.

Private Fields and Public Getters/Setters:

Example:

public class Student {

private String name;

private int age;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

16
Session 2024 - 25
JAVA/CSE

Benefits: Explain how encapsulation improves security and code maintenance.

3.3 Inheritance

Definition: Inheritance allows a class to inherit properties and behaviors from another class.

Single Inheritance Example:

Example:

public class Animal {

public void makeSound() {

System.out.println("Animal sound");

public class Dog extends Animal {

public void makeSound() {

System.out.println("Bark");

Super Keyword: Show how the `super` keyword is used to access members of the parent
class.

Example:

public class Dog extends Animal {

public void makeSound() {

super.makeSound(); // Calls the parent class method

17
Session 2024 - 25
JAVA/CSE

System.out.println("Bark");

Types of Inheritance: Briefly discuss types such as single inheritance, hierarchical


inheritance, and multiple inheritance (through interfaces).

3.4 Polymorphism

Definition: Polymorphism allows objects to be treated as instances of their parent class,


while behaving according to the object's actual type.

Method Overloading and Overriding:

Example (Overloading):

public class Calculator {

public int add(int a, int b) {

return a + b;

public double add(double a, double b) {

return a + b;

Example (Overriding):

public class Animal {

public void makeSound() {

System.out.println("Animal sound");

18
Session 2024 - 25
JAVA/CSE

public class Cat extends Animal {

@Override

public void makeSound() {

System.out.println("Meow");

Upcasting and Downcasting:

Example (Upcasting):

Animal myAnimal = new Dog(); // Upcasting

myAnimal.makeSound(); // Calls the Dog's makeSound method

3.5 Abstraction

Definition: Abstraction allows us to define the essential qualities of an object while hiding
the implementation details.

Abstract Classes: A class that cannot be instantiated and may contain abstract methods.

Example:

public abstract class Animal {

public abstract void sound(); // Abstract method

public class Dog extends Animal {

public void sound() {

19
Session 2024 - 25
JAVA/CSE

System.out.println("Bark");

Interfaces: Explain how interfaces achieve full abstraction by defining method signatures
that must be implemented by a class.

Example:

interface Animal {

void sound();

public class Dog implements Animal {

public void sound() {

System.out.println("Bark");

Difference Between Abstract Classes and Interfaces:

Abstract classes can have defined methods and instance variables, while interfaces cannot.

2.6 Constructors

Definition: A constructor is a special method that is called when an object is instantiated.

Parameterized and Default Constructors:

Example (Parameterized Constructor):

public class Car {

String brand;

20
Session 2024 - 25
JAVA/CSE

public Car(String brand) {

this.brand = brand;

Car myCar = new Car("Toyota"); // Parameterized constructor

Constructor Overloading: Show how multiple constructors can be created for flexibility.

Example:

public class Car {

String brand;

int year;

public Car(String brand) {

this.brand = brand;

public Car(String brand, int year) {

this.brand = brand;

this.year = year;

21
Session 2024 - 25
JAVA/CSE

3.7 'this' Keyword

Definition: The `this` keyword refers to the current object within an instance method or
constructor.

Example:

public class Student {

private String name;

public Student(String name) {

this.name = name; // 'this' refers to the current object

Table.3 Difference Between Procedural vs Object Oriented Programming

22
Session 2024 - 25
JAVA/CSE

Chapter 4
Exception Handling and File Input/Output (I/O)

4.1 Introduction to Exception Handling

What is an Exception?

Definition: An exception is an event that disrupts the normal flow of a program’s


instructions.

Types of exceptions in Java:

Checked Exceptions

Exceptions that are checked at compile-time (e.g., `IOException`, `SQLException`).

Unchecked Exceptions: Exceptions that occur at runtime (e.g., `ArithmeticException`,


`NullPointerException`).

The Need for Exception Handling

Explain why handling exceptions is critical to avoid program crashes and ensure graceful
failure in scenarios like file not found, invalid user input, etc.

4.2 Try, Catch, and Finally Blocks

Syntax: Introduce the structure of `try`, `catch`, and `finally` blocks.

Example:

public class ExceptionExample {

public static void main(String[] args) {

try {

int result = 10 / 0; // This will throw an ArithmeticException

23
Session 2024 - 25
JAVA/CSE

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero: " + e);

} finally {

System.out.println("This block always executes.");

Multiple Catch Blocks: Explain how multiple catch blocks can be used to handle different
types of exceptions.

Example:

try {

int[] arr = new int[3];

arr[5] = 10; // This will throw an ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

System.out.println("ArithmeticException caught.");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index is out of bounds.");

24
Session 2024 - 25
JAVA/CSE

4.3 Throwing Exceptions

Throw Keyword: Show how exceptions can be thrown manually using the `throw`
keyword.

Example:

public class ThrowExample {

static void validateAge(int age) {

if (age < 18) {

throw new IllegalArgumentException("Age must be 18 or above.");

} else {

System.out.println("Age is valid.");

public static void main(String[] args) {

validateAge(16);

4.4 Creating Custom Exceptions

Defining a Custom Exception: Explain how to create your own exceptions by extending
the `Exception` or `RuntimeException` class.

Example:

class CustomException extends Exception {

public CustomException(String message) {

25
Session 2024 - 25
JAVA/CSE

super(message);

public class TestCustomException {

public static void main(String[] args) {

try {

throw new CustomException("This is a custom exception.");

} catch (CustomException e) {

System.out.println("Caught: " + e.getMessage());

4.5 File Input and Output (I/O) in Java

Introduction: Explain why File I/O is essential for interacting with external files and data
sources.

File Class: Introduce the `java.io.File` class for working with file paths and checking file
properties.

Example:

import java.io.File;

public class FileExample {

public static void main(String[] args) {

File file = new File("example.txt");

26
Session 2024 - 25
JAVA/CSE

if (file.exists()) {

System.out.println("File exists: " + file.getName());

} else {

System.out.println("File does not exist.");

4.6 Reading from a File

Using `FileReader` and `BufferedReader`: Introduce the classes used to read text from files.

Example:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadFileExample {

public static void main(String[] args) {

try {

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

27
Session 2024 - 25
JAVA/CSE

reader.close();

} catch (IOException e) {

System.out.println("An error occurred while reading the file.");

4.7 Writing to a File

Using `FileWriter` and `BufferedWriter`: Show how to write text to a file.

Example:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

public class WriteFileExample {

public static void main(String[] args) {

try {

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

writer.write("This is a line of text.");

writer.close();

System.out.println("File written successfully.");

catch (IOException e) {

28
Session 2024 - 25
JAVA/CSE

System.out.println("An error occurred while writing to the file.");

4.8 Using `Scanner` for File Input

Reading Files with Scanner: `Scanner` can also be used for file input, often with simpler
syntax for basic needs.

Example:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class ScannerFileExample {

public static void main(String[] args) {

try {

File file = new File("input.txt");

Scanner sc = new Scanner(file);

while (sc.hasNextLine()) {

String data = sc.nextLine();

System.out.println(data);

sc.close();

} catch (FileNotFoundException e) {

29
Session 2024 - 25
JAVA/CSE

System.out.println("File not found.");

4.9 Handling File Exceptions

Common File I/O Exceptions:

FileNotFoundException: Thrown when the file being accessed is not found.

IOException: General input/output exception.

Example

try {

FileReader file = new FileReader("nonexistentfile.txt");

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

30
Session 2024 - 25
JAVA/CSE

Chapter 5

Conclusion

In conclusion, this report has explored the fundamental aspects of Java programming,
starting with a brief introduction to its importance and versatility. We delved into the basics,
laying a strong foundation in understanding Java syntax, data types, control structures, and
functions. Building on this, the Object-Oriented Programming (OOP) principles were
examined, highlighting the concepts of encapsulation, inheritance, polymorphism, and
abstraction, which are the cornerstones of Java's architecture.

The two projects included in this report served as practical implementations of these
concepts, demonstrating how theoretical knowledge can be applied to solve real-world
problems. Through these projects, we have seen how Java's robust features, including its
platform independence and extensive libraries, make it an excellent choice for developing
scalable and efficient software.

In summary, Java continues to be a powerful and versatile language in the programming


world. This report not only reflects the key concepts and applications of Java but also
emphasizes the importance of continuous learning and practice to master its full potential.

31
Session 2024 - 25
JAVA/CSE

Reference
General Java References:
Java: The Complete Reference" by Herbert Schildt
A comprehensive guide to Java, covering both the basics and advanced topics, including
OOP.
Head First Java" by Kathy Sierra & Bert Bates
This book explains Java concepts in a beginner-friendly manner, ideal for understanding
the fundamentals.
Basics of Java:
Oracle Java Documentation
Oracle provides official documentation for Java, covering everything from setup to
advanced programming.
Link: [https://docs.oracle.com/javase/tutorial/](https://docs.oracle.com/javase/tutorial/)
GeeksforGeeks Java Tutorials
A great online resource with explanations and examples for beginners in Java.
Link: [https://www.geeksforgeeks.org/java/](https://www.geeksforgeeks.org/java/)
bject-Oriented Programming (OOP):
Effective Java" by Joshua Bloch
Focuses on best practices in Java programming, including OOP principles.
Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma et al.
A must-read for understanding how OOP concepts can be applied in Java.
Projects:
Java SE Development Kit (JDK) Documentation
Official documentation on using the JDK to build and run Java projects.
Link: [https://docs.oracle.com/javase/8/docs/](https://docs.oracle.com/javase/8/docs/)

Additional Online Resources:


Stack Overflow Java
Provides solutions and discussions on various Java-related problems and projects.
Link:
[https://stackoverflow.com/questions/tagged/java](https://stackoverflow.com/questions/ta
gged/java)

32
Session 2024 - 25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy