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

Anshul Java

Uploaded by

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

Anshul Java

Uploaded by

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

Training Report

In the partial fulfillment of the requirements for the four weeks Summer Institutional
Training of Bachelor of Technology in Computer Science & Engineering

By

Name: Anshul Pratap Singh


University roll no: 23100010015
Submitted to:
CSE Department

UNIVERSITY SCHOOL OF ENGINEERING & TECHNOLOGY

1
Table of Contents

S.no Content Page no.


1. Introduction 3
2. Data Types: Variables and Literals 4
3. Set java Environment 5
4. Operators and Expressions 6
5. String class and Printing 7
6. Strimg Class and Printing 9
7. Conditional Statements 10
8. Loops 11
9. Arrays 12
10. Methods 13
11. Object-Oriented Programming 14
12. Inheritance 16
13. Abstract Classes 18
14. Interfaces 19
15. Inner classes 20
16. Static and Final 21
17. Packages 22
18. Exception Handling 23
19. Multithreading 24
20. Java.lang Package 26
21. Annotations and JavaDoc 26
22. Lambda Expressions 26
23. Java IO Streams 27
24. Java Generics 28
25. Collection Framework 28
26. Date and Time API 29
27. Network Programming 30
28. JDBC using SQL Lite 30
29. AWT Abstract Window Toolkit 31
30. Java Swing 35
31. Practical Programs 37
32. Completion Certificate 47
33. Acknowledgement 48

2
CHAPTERS
1. INTRODUCTION:

o Introduction to Java : Java is a high-level, object-oriented programming language developed


by Sun Microsystems, which is now owned by Oracle Corporation. It was designed to have as
few implementation dependencies as possible, making it a versatile language used in a wide
variety of applications.
1.1. Features of Java :
 Object-oriented: Objects model real-world entities for reusable, modular code.
 Platform independent (WORA): Code runs on any platform with a JVM.
 Simple and Secure: Easy to learn with a focus on security features.
 Robust and Rich API: Reliable with a vast library of pre-written functions.
 Multithreaded, High-performance, Scalable: Handles multiple tasks, performs
well, and adapts to growing needs.
 Interpreted and Dynamic: Flexible for integrating code from other languages.

1.2. How to install JDK on Windows:


 Download the JDK installer from https://www.oracle.com/java/technologies/downloads/.
Choose the correct version (usually Windows x64).
 Run the installer and follow the on-screen instructions (usually accept defaults).
 (Optional) Configure environment variables if you encounter issues running Java commands
from the command prompt.
 Verify the installation by running java -version and javac -version in a command prompt.

1.1.1To check the version :

fig 1.1

To Print “Hello World” in Java :

Fig1.2

3
To Run program :

Fig 1.3

Scanner class in java:

Method Description

nextBoolean() Used for reading Boolean value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value

nextLine() Used for reading Line value

nextLong() Used for reading Long value

4
2. DATA TYPES-VARIABLES AND LITERALS

2.1. Variable: it is act like a container where we store value.


2.2. Literals: It is raw value that are stored in a variable or constant.

2.1.1. Primitive Data Types:


 Numeric:
o byte: Smallest integer (1 byte)
o short: Integer (2 bytes)
o int: Integer (4 bytes)
o long: Large integer (8 bytes)
o float: Single-precision floating-point (4 bytes)
o double: Double-precision floating-point (8 bytes)
 Character: char (2 bytes)
 Boolean: boolean (1 bit)
2. Reference Data Types:
 Classes : Blueprints for creating objects
 Interfaces : Contracts for classes to implement
 Arrays : Ordered collections of elements of the same type

 Program:
class data
{ public static void main(String arg[])
{
int n=100;
float f=3.1f;
char c='A';
String s="Hi";
double d=5.1232;
System.out.println(n+" "+f+" "+c+" "+s+" "+d);
}

Output:

5
3. SET JAVA ENVIRONMENT

3.1. How to Install NetBeans Java IDE on Windows?


NetBeans IDE is a Free open-Source, Cross-plate form Integrated Development Environment (IDE) with
built-in support for the JAVA Programming Language.
To install NetBeans follow following steps:
(i) Visit the official website of NetBeans i.e NetBeans.com , download the latest version and install
it.
(ii) Start NetBeans and go to tools to search plugins and sactivate Java SE plugin.
(iii)

Fig 3.1

(iv) To start new project go to file and select new project


(v) Select java with Ant and then Java applications.
(vi)

Fig 3.2
(vii) Give the file name and start work.
(viii) First program on NetBeans:

Fig 3.3

6
4. FEATURES AND ARCHITECTURE
Platform Independence in Java
Java's platform independence means that a Java program compiled on one system can run on any
other system with a Java Virtual Machine (JVM) installed. This is achieved through:
 Bytecode: Java code is compiled into platform-neutral bytecode, not machine-specific code.
 JVM: This virtual machine translates the bytecode into machine-specific code at runtime,
enabling cross-platform compatibility.
Key benefits:
 Portability: Code can be reused across different operating systems.
 Efficiency: Developers write code once and deploy it on multiple platforms.
In essence, Java's "Write Once, Run Anywhere" (WORA) principle is made possible by the
combination of bytecode and the JVM

4.1. JVM Architecture: JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides runtime environment in which java bytecode can be executed.

Fig 4.1

 Java can be considered both a compiled and interpreted language because its source code is first
compiled into binary-byte code. This byte code runs on the JVM, which is usually a software-
based interpreted.

7
5. OPERATORS AND EXPRESSIONS

5.1. Operators are symbols that perform specific operations on operands (values or variables).
5.2. Expressions are combinations of operators, operands, and parentheses that evaluate to a
value.
5.1.1. Arithmetic Operators
 Addition: +
 Subtraction: -
 Multiplication: *
 Division: /
 Modulo: % (returns the remainder of division)
5.1.2. Relational Operators
 Equal to: ==
 Not equal to: !=
 Greater than: >
 Less than: <
 Greater than or equal to: >=
 Less than or equal to: <=
5.1.3. Logical Operators
 Logical AND: && (returns true if both operands are true)
 Logical OR: || (returns true if at least one operand is true)
 Logical NOT: ! (reverses the logical value of an operand)
5.1.4. Assignment Operators
 Simple assignment: =
 Compound assignment: +=, -=, *=, /=
Increment/Decrement Operators
 Increment: ++ (increases the value by 1)
 Decrement: -- (decreases the value by 1)

 Program:
public class data
{
public static void main(String[] args) {
int a = 100;
int b = 5;
boolean x = true;
boolean y = false;
int s = a + b; //arithematic operators
int remainder = a % b;
boolean bol = (a == b); //Relational Operators
boolean and = x && y; //Logical Operators

8
boolean or = x || y;
int And = a & b; // Bitwise Operators
int Or = a | b;
System.out.println("a + b = " + s);
System.out.println("a == b: " + bol);
System.out.println("x && y: " + and);
System.out.println("x || y: " + or);
System.out.println("a & b: " + And);
System.out.println("a | b: " + Or);
}
}

Output:

9
6. STRING CLASS AND PRINTING

6.1. String Class:


 Immutable: Once created, a String object cannot be modified.
 Object: A String object represents a sequence of characters.
 Methods: Provides numerous methods for manipulating and comparing strings.
6.2. Printing Strings:
 System.out.println(string): Prints the string to the console followed by a newline.
 System.out.print(string): Prints the string to the console without a newline.
 System.out.printf(format, args): Prints formatted output using placeholders and arguments.

6.3. Regular expressions: Regular expressions simply known as RegEx in java is a sequence of characters that
forms a search pattern. When you search for data in a text, you can use this search pattern to describe what
you are searching for.
Program :
class RegEx
{
public static void main(String arg[])
{
String str="aabbcc";
String pattern="[abc].*";
System.out.println(str.matches(pattern));
}
}

Output:

10
7. CONDITIONAL STATEMENETS

7.1. Conditional Statements : Conditional statements allow you to execute different code blocks based on
specific conditions. Conditional statements:
8.1.1 if Statement
The if statement is the most basic form of conditional control. It executes a block of code if a specified
condition evaluates to true.
8.1.2. if-else Statement
The if-else statement provides an alternative block of code to execute when the condition is false.
8.1.3. if-else if-else Statement
When you need to check multiple conditions, you can use if-else if-else statements.

8.1.4. Switch Statement


The switch statement allows you to execute one block of code among many based on the value of an
expression. It is a cleaner alternative to multiple if-else statements when dealing with multiple discrete values.

 Write a program to check whether a number is odd or even.


import java.util.*;
class css
{
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter any number : ");
int n=s.nextInt();
if(n%2==0)
System.out.println("Even");
else
System.out.println("Odd");
}
}

Output:
Fig 8.1

11
8. LOOPS

8.1. Loops : Loops allow us to repeatedly execute a block of code until a certain condition is met.Example of
loops are:
8.1.1. for Loop
The for loop is commonly used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment/decrement.
8.1.2. Enhanced for Loop (for-each Loop)
The enhanced for loop is used to iterate over arrays or collections. It simplifies the syntax for iterating through
elements.

 Write a program to find the factorial of a number.


import java.util.*;
class calci
{
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a number : ");
int num=s.nextInt();
int fact=1;
for(int i=1;i<=num;i++)
{
fact=fact*i;
}
System.out.print("Factorial of number is : "+fact);
}
}

Output
Fig 9.1

12
9. ARRAYS

9.1. Arrays : Arrays are ordered collections of elements of the same data type.
 Write a program to add elements in array.
import java.util.ArrayList;

public class arr


{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println("ArrayList: " + list);
}
}
Output:
Fig 10.1

 Write a program to insert an element in an array.


class arr
{
public static void main(String arg[])
{
int a[] = {1,2,3,4,5,6};
for(int i=4;i>=3;i--)
{
a[i+1]=a[i];
}
a[3]=15;
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+",");
}
}
}

Output:
Fig 10.2

13
10. METHODS

11.1. Methods : Methods are blocks of code that perform specific tasks. They are essential for
organizing your code, making it reusable, and improving readability.

 Write a program for methods.


import java.util.ArrayList;
class arr
{
void show()
{
System.out.println("Hello...");
}
public static void main(String[] args)
{
arr a=new arr();
a.show();
a.show();
}
}

Output:
Fig 11.1

14
11. Object-Oriented Programming
11.1. Classes and Objects: In Java, classes and objects are basic concepts of Object Oriented
Programming (OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior.

11.2 . Abstraction: Data abstraction is the process of hiding certain details and showing only
essential information to the user.

11.3 . Constructors: In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created.

 Write a program to calculate grades of a student using classes and objects.


class Student
{ String name;
private int roll_no;
String Student_class;
int m1,m2,m3;
public int total()
{
return m1+m2+m3;
}
public double percentage()
{ int totalMarks=total();
return totalMarks/3;
}
public void grade()
{ double per=percentage();
if(per>85)
System.out.print("Grade A");
else if(per>70)
System.out.print("Grade B");
else if(per>50)
System.out.print("Grade C");
else
System.out.print("Fail");
}
public int getroll_no()
{
return roll_no;
}
public void setroll_no(int roll_no)
{
this.roll_no=roll_no;
}
public static void main(String arg[])
{
Student s=new Student();
s.name="Eilish";
s.setroll_no(7);
s.Student_class="Six";
s.m1=98;
s.m2=99;
s.m3=15;

15
System.out.println("Name : "+s.name);
System.out.println("Roll no. : "+s.getroll_no());
System.out.println("Class : "+s.Student_class);
System.out.println("Total marks : "+s.total());
System.out.println("Percentage : "+s.percentage());
System.out.print("Grade : ");
s.grade();
}
}
Output:

Fig 12.1

16
12 INHERITANCE

12.1. Inheritance: In Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the


mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class.
 Program:
class Animal
{
String name;
Animal(String name)
{
this.name=name;
}
void speak()
{
System.out.println("Animal Speak...");
}
}
class Dog extends Animal
{
Dog(String name)
{
super(name);
}
void speak()
{
System.out.println(name+" says Woof Woof...");
}
}
class Cat extends Animal
{
Cat(String name)
{
super(name);
}
void speak()
{
System.out.println(name+" says Meow Meow...");
}
}
class ann
{
public static void main(String arg[])
{
Dog d=new Dog("Jacky");
Cat c=new Cat("Leo");
d.speak();
c.speak();
}
}

Output:
Fig 12.1

12.2 Polymorphism:The word polymorphism means having many forms. In simple words, we can define Java
Polymorphism as the ability of a message to be displayed in more than one form.

12.2.1 Types of polymorphism:

17
12.2.1.1 Method overloading:Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input parameters or type of input
parameters, or a mixture of both.
 Program :
class test
{
public int max(int a,int b)
{
return a>b?a:b;
}
public int max(int a,int b,int c)
{
if(a>b && a>c) return a;
else if (b>a &&b>c) return b;
return c;
}
}
class overloading
{
public static void main(String arg[])
{
test t=new test();
int m=t.max(15,20);
int n=t.max(10,12,16);
System.out.println("Maximum number : "+m);
System.out.println("Maximum number : "+n);
}
}
Output:

Fig 13.2

12.2.1.2 Method Overriding: If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
 Program:
class Super
{
public void display()
{
System.out.println(" Super display");
}
}
class Sub extends Super
{
public void display()
{
System.out.println(" Sub display");
}
}
class overriding
{
public static void main(String arg[])
{
Super s=new Sub(); //Dynamic method dispatch
s.display();
}
}
Output:
Fig 13.3

18
13 ABSTRACT CLASSES

13.1. Abstract classes: Abstract class is declared with the abstract keyword. It may have both abstract and non-
abstract methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in
Java but not for variables.
 Program:
abstract class Shape
{
public int num1;
public int num2;
abstract void area();
}

class Circle extends Shape


{
Circle(int radius)
{
this.num1=radius;
}
void area()
{
double a=Math.PI*num1*num1;
System.out.println("Area of Circle : "+a);
}
}
class Main
{
public static void main(String arg[])
{
Circle c=new Circle(10);
c.area();
}
}
Output:
Fig 13.1

19
14 INTERFACES
14.1. Interfaces:The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface could
only have abstract methods (methods without a body) and public, static, and final variables by default. The
abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and
must be implemented.

 Program:
interface Animal
{
void makesound();
}
class Cat implements Animal
{
public void makesound()
{
System.out.println("Meow Meow ....");
}
}
class sound
{
public static void main(String arg[])
{
Cat c=new Cat();
c.makesound();
}
}

Output:
Fig 14.1

20
15 INNER CLASSES

15.1. Inner classes are classes defined within another class. They provide a way to logically group related
classes together and can enhance code organization and encapsulation.

15.2. Local class: Local classes are classes defined within a method or initializer block. They can only
be accessed within the scope where they are defined.

15.3. Anonymous class: These are special type local inner classes that are defined and instantiated in
single expression and created during object creation.They are often used with interfaces or abstract
classes.
 Program:
public class Out
{
class Inn
{
void print() {
System.out.println("Hello...");
}
}
public static void main(String args[])
{
Out o = new Out();
Inn i= o.new Inn();
i.print();
}
}
Output:
Fig 15.1

21
16 STATIC AND FINAL
16.1. Static keyword: The static keyword is primarily used to define class-level variables and methods
that belong to the class rather than instances (objects) of the class.

16.2. Final keyword: The final keyword is used to restrict access and modification.

16.3. Singleton class: It is a class that allows only one instance of itself to be created during the entire
lifetime of the program. This is useful when you need a single point of access for certain functionalities,
like managing a database connection, configuration settings, or logging.

 Program for static and final variable:


public class exp
{
static int s = 10;
final int f;
public exp(int value)
{
f= value;
}
public static void print()
{
System.out.println("Static Variable: " + s);
}
public void show()
{
System.out.println("Final Variable: " + f);
}
public static void main(String[] args)
{
exp.print();
exp e = new exp(25);
e.show();
}
}
Output:

Quiz:

Fig 16.1

22
17 Packages

17.1. Packages: Packages are used to group related classes, interfaces, and sub-packages together, helping
to organize code and avoid name conflicts. Packages are essentially folders or directories that contain Java
classes and interfaces.
17.2. Access Specifiers : Access specifiers in Java control the visibility of classes, methods, and variables.
They help define how accessible different parts of your code are from other classes and packages.

17.2.1. Public : When a member (class, method, or variable) is declared public, it can be accessed from
any other class in any package. This is the most permissive access level.

17.2.2. Private : A private member is accessible only within the class it is declared in. It cannot be accessed
from outside the class, not even by subclasses or classes in the same package. This is the most restrictive
access level.

17.2.3. Protected : A protected member can be accessed within its own package and by subclasses (even
if they are in different packages). This provides a balance between public and private access.

17.2.4. Default : If no access specifier is declared, it is considered default (also known as package-private).
A default member is accessible only within classes in the same package. It cannot be accessed from classes
in different packages.

Example:
package package1;
public class Class1 {
public void method1() {
System.out.println("From Class1");
} }
package package2;
import package1.Class1;
public class Class2 {
public void method2() {
Class1 obj = new Class1();
obj.method1();
} }

Output:

23
18 EXCEPTION HANDLING
18.1. Exception Handling : Exception handling is a mechanism in Java that allows you to manage and
recover from unexpected errors that occur during program execution. These errors, known as exceptions,
can disrupt the normal flow of a program. By using exception handling, you can prevent your program
from crashing and provide informative error messages to the user.

(i) Try Block : The try block is used to wrap the code that might throw an exception. If an exception
occurs within this block, the control is transferred to the corresponding catch block.

(ii) Catch block : The catch block is used to handle the exception thrown by the try block. You
can have multiple catch blocks to handle different types of exceptions.

(iii) Finally block : The finally block is optional and is used to execute important code such as
cleanup operations. This block will execute regardless of whether an exception occurred or not,
making it a good place to close resources like files or database connections.
 Write a program for exception handling using try and catch block.
class Excep
{
public static void main(String arg[])
{
try
{
int result=10/0;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero is not possible");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
S..ystem.out.println("Executed. ... ");
}
}

Output:
Fig 18.1

Certificate:

24
19. MULTITHREADING

19.1. Multithreading: It is a process in which two or more parts of the same process run simultaneously.
This can improve the performance of applications, especially those that need to handle multiple tasks
simultaneously or perform I/O operations.

19.2. Synchronization: Synchronization is a process of handling resource accessibility by multiple thread


requests. The main purpose of synchronization is to avoid thread interference.

19.3. Life Cycle of thread:


 New: The thread is created but not yet started.
 Runnable: The thread is ready to run and waiting for CPU time.
 Running: The thread is actively executing.
 Blocked: The thread is waiting for a resource or condition to proceed.
 Waiting: The thread is waiting indefinitely for another thread to perform an action.
 Timed Waiting: The thread is waiting for a specified time period.
 Terminated: The thread has finished execution.

Fig 19.1

19.4. Program:
class data
{
synchronized public void display(String str)
{
for(int i=0;i<str.length();i++)
{
System.out.print(str.charAt(i));
try
{
Thread.sleep(100);
}
catch(Exception e){};
}
}
}
class thread extends Thread
{
data d;
public thread(data d)
{
this.d=d;
}
public void run()
{
d.display("Hello World");
}
}

25
class thread1 extends Thread
{
data d;
public thread1(data d)
{
this.d=d;
}
public void run()
{
d.display("Welcome All");
}
}
class thSyn
{
public static void main(String arg[])
{
data d=new data();
thread t1=new thread(d);
thread1 t2=new thread1(d);
t1.start();
t2.start();
}
}
Output:
Fig 19.2
Certificate:

26
20. JAVA.LANG PACKAGE

20.1. The object class is a fundamental class in Java that serves as the base class for all Java objects. It provides
a common interface for interacting with objects in the Java Virtual Machine (JVM).

20.2. Wrapper class: These are used to represent primitive data types as objects. They provide methods for
converting between primitive values and their corresponding object representations.

20.3. Enums: Enums or enumerations, are a special type of class in Java that provide a way to define a fixed
set of constants. They are often used to represent a group of related values that should be restricted to a
specific set.

20.4. Java.lang.reflect: The java.lang.reflect package in Java provides classes and interfaces that allow
you to examine and manipulate the structure and behavior of classes, methods, fields, and constructors
at runtime. This process is known as reflection.

Introduction to Java Reflection


Reflection in Java is a powerful mechanism that allows you to examine and manipulate the structure of a
class at runtime. It provides a way to inspect classes, interfaces, methods, and fields dynamically.

21. ANNOTATIONS AND JAVADOC

21.1. Annotations: Annotations are special tags that can be added to Java code elements such as classes,
methods, fields, and variables. They provide metadata about the code, which can be used by tools and
frameworks to generate documentation, perform code analysis, or enforce coding standards.

21.1.1. Built-in Annotations: Java provides several built-in annotations that are used for various
purposes, including documentation, compiler instructions, and runtime processing.

@Override: Indicates that a method overrides a method from a superclass.


@Deprecated: Marks a method, field, or class as deprecated, indicating that it should no longer be used.
@SuppressWarnings: Suppresses compiler warnings for specific types of issues.
@SafeVarargs: Indicates that a method or constructor is safe to use with varargs (variable arguments).
@FunctionalInterface:Marks an interface as a functional interface, which has exactly one abstract method.

22. LAMBDA EXPRESSION


22.1. Lambda Expressions: Lambda expressions are a concise way to represent anonymous functions in
Java. They were introduced in Java 8 and provide a more functional programming style.
Syntax: (parameters) -> expression

 Program:
Interface mylambda
{
public void display();
}
class lam
{ public static void main(String arg[])
{
mylambda l=()->
{
System.out.println("Hello World ... ");
};
l.display();
}
}

27
OutPut:
Fig 23.1

23. JAVA IO STREAMS


23.1. Java IO streams provide a mechanism for reading and writing data to various sources and destinations,
such as files, networks, and in-memory buffers. They are essential for input/output operations in Java
applications.
Types of Streams:
23.1.1. Byte Streams: Deal with individual bytes of data.
23.2. InputStream: Abstract base class for reading bytes from a source.
23.3. OutputStream: Abstract base class for writing bytes to a destination.
23.4. Common subclasses:
23.4.1. FileInputStream: Reads bytes from a file.
23.4.2. FileOutputStream: Writes bytes to a file.
23.4.3. ByteArrayInputStream: Reads bytes from an in-memory array.
23.4.4. ByteArrayOutputStream: Writes bytes to an in-memory array.
23.4.5. BufferedInputStream: Provides buffering for InputStreams.
23.4.6. BufferedOutputStream: Provides buffering for OutputStreams.
23.1.2. Character Streams: Deal with characters (16-bit Unicode code points).
23.2. Reader: Abstract base class for reading characters from a source.
23.3. Writer: Abstract base class for writing characters to a destination.
23.4. Common subclasses:
23.4.2. FileReader: Reads characters from a file.
23.4.3. FileWriter: Writes characters to a file.
23.4.4. BufferedReader: Provides buffering for Readers.
23.4.5. BufferedWriter: Provides buffering for Writers.
23.4.6. StringReader: Reads characters from a string.
23.4.7. StringWriter: Writes characters to a string.

Basic Example: Reading from a File


import java.io.FileReader;
import java.io.IOException;

public class ReadFromFile {


public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("myFile.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
}
}

Output

Certificate:

28
24. JAVA GENERICS

24.1. Generics: Generics are a feature in Java that allows you to write flexible and reusable code that can work
with any data type. Instead of writing the same code for different data types, you can write it once and use
it with different types.
 Program:
class data<T>
{
private T obj;
public void setdata(T val)
{
obj=val;
}
public T getdata() //retreiving the obj
{
return obj;
}
}
public class generics
{
public static void main(String arg[])
{
data<Integer> d=new data<Integer>();
d.setdata(new Integer(10));
System.out.println(d.getdata());
}
}
Output:
Fig 24.1

25. Collection Framework

25.1. The Java Collection Framework (JCF) is a set of interfaces and classes that provide mechanisms for storing,
retrieving, and manipulating collections of objects. It provides a rich and flexible API for various data
structures and operations.
Core Interfaces:
 Collection: The root interface for all collections.
 List: Represents an ordered collection of elements that allow duplicates.
 Set: Represents an unordered collection of elements that do not allow duplicates.
 Map: Represents a collection of key-value pairs.
Common Implementations:
 ArrayList: A resizable array list that provides efficient random access.
 LinkedList: A doubly-linked list that is efficient for insertions and deletions.

29
 HashSet: An implementation of a set based on a hash table.
 TreeSet: A sorted set implementation based on a red-black tree.
 HashMap: An implementation of a map based on a hash table.
 TreeMap: A sorted map implementation based on a red-black tree.

 Write a program to create a linked list.


import java.util.*;
class Arr
{
public static void main(String arg[])
{
LinkedList<Integer> l1=new LinkedList<Integer>();
LinkedList<Integer> l2=new LinkedList<Integer>(List.of(10,20,30,40,50));
l1.add(8);
l1.add(98);
l1.addAll(l2);
l1.forEach(n->System.out.print(n+" "));
}
}
Output:
Fig 25.1

Certificate:

26. Date and time API(Application Programming Interface)


 Write a program to print date and time.
import java.util.*;
class dateTime
{
public static void main(String arg[])
{
Date d=new Date();
System.out.println(d);
}
}

30
Output:
Fig 26.1
Java time classes:
(i) java.util.Date
(ii) java.util.Calendar

27. Network Programming


27.1. Network programming in Java involves creating applications that can communicate with other computers
over a network. It's essential for building distributed systems, client-server applications, and web services.
Reverse echo server: A reverse echo server is a network application that receives a message from a client,
reverses the characters in the message, and sends the reversed message back to the client.
UDP(User Datagram Protocol): UDP is a connectionless, unreliable protocol used for datagram
transmission over the Internet.
Datagram communication refers to a method of sending data over a network using datagrams, which are
independent packets of data that are sent without establishing a connection. This is commonly associated
with the User Datagram Protocol (UDP) in networking. UDP is one of the core protocols of the Internet
Protocol (IP) suite and is used for scenarios where speed is more critical than reliability.

How Datagram Communication Works


1. Sender: Constructs a datagram and sends it to a destination address.
2. Network: Handles routing and transmission of the datagram. The datagram might travel through various
routers and switches.
3. Receiver: Receives the datagram and processes it. The receiver does not send an acknowledgment.

28. JDBC using SQLite


28.1. SQL (Structured Query Language) is a powerful language used for managing and querying relational
databases. It allows users to create, read, update, and delete data from databases.
It includes various types of commands that can be categorized mainly into Data Definition Language (DDL)
and Data Manipulation Language (DML).

JDBC Drivers: JDBC (Java Database Connectivity) is a Java API that allows Java applications to interact
with relational databases. JDBC provides a standard interface for connecting to databases, executing SQL
queries, and processing the results.

DML: Using JDBC (Java Database Connectivity) to perform Data Manipulation Language (DML)
operations involves executing SQL commands like INSERT, UPDATE, DELETE, and SELECT through
Java code. Below, I'll demonstrate how to perform these DML operations using JDBC.

DDL: Data Definition Language (DDL) in SQL is used to define and manage database structures such as
tables, indexes, and schemas. DDL commands are responsible for creating, altering, and dropping these
structures. Unlike Data Manipulation Language (DML), which deals with data inside the structures, DDL
focuses on the schema itself.

Complete Example
import java.sql.*;
public class SQLiteExample {
public static void main(String[] args) {
Connection conn = null;
try {
String url = "jdbc:sqlite:mydatabase.db";
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS persons (id INTEGER PRIMARY KEY,
name TEXT)");
stmt.executeUpdate("INSERT INTO persons (name) VALUES ('Gandhi')");
stmt.executeUpdate("INSERT INTO persons (name) VALUES ('Khushi')");
ResultSet rs = stmt.executeQuery("SELECT * FROM persons");

31
while (rs.next()) {
System.out.println("id = " + rs.getInt("id"));
System.out.println("name = " + rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
}

Output:

29. AWT Abstract Window Toolkit


29.1. AWT(Abstract Window kit): AWT is used in Java GUI programming because it provides a basic set of
platform-independent components and event-handling mechanisms. It directly uses the native OS
components, making it simple and suitable for basic applications.

 Write a program to create buttons and labels.


import java.awt.*;
class Main
{
public static void main(String arg[]) throws Exception
{
Frame f=new Frame();
f.setLayout(new FlowLayout());
Label l=new Label("Click here...");
Button b=new Button("Click");
f.add(l);
f.add(b);
f.setVisible(true);
}
}

Output:
Fig 29.1
 Write a program to create Checkbox and Radiobutton.
import java.awt.*;
import java.awt.event.*;
class checkbox extends Frame
{
Checkbox c1, c2;
checkbox()
{
CheckboxGroup c = new CheckboxGroup();
c1 = new Checkbox("Kalix", false, c);
c2 = new Checkbox("Jack", false, c);
setLayout(new FlowLayout());
add(c1);
add(c2);

32
}
}
class frame
{
public static void main(String arg[])
{
checkbox cb=new checkbox();
cb.setSize(400,400);
cb.setVisible(true);
}
}

Output:
Fig 29.2

29.2. Event: An event is an action or occurrence detected by the program, typically triggered by user interactions.
Java handles these events using the event-handling mechanism.
29.3. Action Listener: It is an interface in Java that listens for specific events, particularly action events. When
a user performs an action like clicking a button or pressing Enter in a text field, an action event is generated.

 Write a program to create a Scrollbar and Adjustment Event.


import java.awt.*;
import java.awt.event.*;
class frame extends Frame implements AdjustmentListener
{
Scrollbar red,green,blue;
TextField t;
frame()
{
red=new Scrollbar(Scrollbar.HORIZONTAL,0,20,0,255);
green=new Scrollbar(Scrollbar.HORIZONTAL,0,20,0,255);
blue=new Scrollbar(Scrollbar.HORIZONTAL,0,20,0,255);
t=new TextField(20);
red.setBounds(50,150,800,30);
green.setBounds(50,250,800,30);
blue.setBounds(50,350,800,30);
t.setBounds(50,100,800,50);
setLayout(null);
add(t);
add(red);
add(green);
add(blue);
red.addAdjustmentListener(this);
green.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
t.setBackground(new Color(red.getValue(),green.getValue(),blue.getValue()));
}
}
class main
{
public static void main(String arg[])
{
frame f=new frame();
f.setVisible(true);
f.setSize(500,500);
}
}

33
Output:

Fig 29.3

Certificate:

 Write a java program that handles all keyevents and shows the event name at the window
when a mouse event is fired.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class frame extends Frame implements KeyListener
{
Label l1,l2,l3,l4;
frame()
{
l1=new Label(""); //for press
l2=new Label(""); //for release
l3=new Label("");; //for typed
l4=new Label(""); //for time
setLayout(null);
add(l1);
add(l2);
add(l3);
add(l4);
l1.setBounds(30,50,100,20);
l2.setBounds(30,100,100,20);
l3.setBounds(30,150,100,20);
l4.setBounds(30,200,200,20);
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
l1.setText("Key Pressed");
l2.setText("");

34
}
public void keyReleased(KeyEvent e)
{
l2.setText("Key Released");
l1.setText("");
l3.setText("");
l4.setText("");
}
public void keyTyped(KeyEvent e)
{
l3.setText("Key Typed");
l4.setText(new Date(e.getWhen())+"");
}
}
class main
{
public static void main(String arg[])
{
frame f=new frame();
f.setSize(50,50);
f.setVisible(true);
}
}
Output:

Fig 29.4

 Adapter Class: An adapter class is a special type of class that provides default implementations
for the methods in an event listener interface. Adapter classes are used when you want to handle
only a few of the events defined in an interface with multiple methods, without having to
implement all the methods.
 Write a program for paint.
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{ int x=0,y=0;
MyFrame()
{ super("Painting Demo");
addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
});

}
public void paint(Graphics g)
{g.setColor(Color.MAGENTA);
g.setFont(new Font("Luminari",Font.BOLD,30));
g.drawString("Hello", x, y);

35
}
}
class Paint
{ public static void main(String[] args) {
MyFrame f=new MyFrame();
f.setSize(500,500);
f.setVisible(true);
}

Output:

Fig 29.5

30. Java Swing


Swing is a graphical user interface (GUI) toolkit for Java that provides a set of lightweight components for
building user interfaces. Unlike AWT (Abstract Window Toolkit), which relies on native system
components, Swing provides its own implementation of GUI components, resulting in a more consistent
look and feel across different platforms.

AWT vs Swing :
S.NO AWT Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes and is
1.
applications . used to create various applications.

The components of Java AWT are heavy


2. The components of Java Swing are light weighted.
weighted.

Java AWT has comparatively less Java Swing has more functionality as compared to
3.
functionality as compared to Swing. AWT.

The execution time of AWT is more than


4. The execution time of Swing is less than AWT.
Swing.

The components of Java AWT are platform The components of Java Swing are platform
5.
dependent. independent.

6. MVC pattern is not supported by AWT. MVC pattern is supported by Swing.

AWT provides comparatively less powerful


7. Swing provides more powerful components.
components.

8 AWT components require java.awt package Swing components requires javax.swing package

AWT is a thin layer of code on top of the Swing is much larger swing also has very much richer
9
operating system. functionality.

36
S.NO AWT Swing

Swing is also called as JFC(java Foundation classes).


10 AWT stands for Abstract windows toolkit .
It is part of oracle’s JFC.

Using AWT , you have to implement a lot of


11 Swing has them built in.
things yourself .

31. Write a program to create label and button using swing.


import javax.swing.*;
import java.awt.*;
import javax.swing.*;
class frame extends JFrame
{
JLabel l;
JButton b;
frame()
{
l=new JLabel("Click here");
b=new JButton("Click");
setLayout(null);
l.setBounds(50, 50, 100, 30);
b.setBounds(50, 80, 100, 30);
add(b);
add(l);
}
}
class main
{
public static void main(String arg[])
{
frame f=new frame();
f.setVisible(true);
}
}

Output:
Fig 30.1

Practical Programs:
1. (a) Write a java program to find the Fibonacci series.

import java.util.*;
class Fbseries
{
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter terms to wanna print : ");
int n=s.nextInt();
System.out.print("Enter First term : ");
int a=s.nextInt();
System.out.print("Enter Second term : ");
int b=s.nextInt();
int c=a+b;
System.out.print("Fibonacci Series : ");

37
System.out.print(a+","+b+",");
for(int i=0;i<=n-2;i++)
{ c=a+b;
System.out.print(c+",");
a=b;
b=c;
}
}
}
Output:

(b) Write a java program to multiply two given matrices.

class arr
{
public static void main(String arg[])
{
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
int b[][]={{1,2,3},{4,5,6},{7,8,9}};
int c[][]=new int[3][3];
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
for(int k=0;k<a[0].length;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];

}
System.out.print(c[i][j]+" ");

}
System.out.println(" ");
}

}
}
Output:

2. (a) Write a java program for Method overloads and Constructor overloading.

class Circle
{
private double radius;
public Circle() // Default construcor
{
this.radius = 1.0;
}
public Circle(double radius) // constructor overloading
{
setRadius(radius);
}

38
public void setRadius(double radius)
{
if(radius >= 0)
this.radius = radius;
else
this.radius = 0;
}
public double getRadius()
{
return radius;
}
public double area()
{
return Math.PI * radius * radius;
}
public double area(double radius) // method overloading
{
return Math.PI * radius * radius;
}
}
class circle
{
public static void main(String agr[])
{
Circle c1 = new Circle(); //default consturctor
System.out.println("Radius: " + c1.getRadius());
System.out.println("Area: " + c1.area());

Circle c2 = new Circle(5.0); //paramertric constructor


System.out.println("Radius: " + c2.getRadius());
System.out.println("Area: " + c2.area());
}
}
Output:

(b) Write a Java program that checks whether a given string is a palindrome or not.

import java.util.*;
class rev
{
public static void main(String arg[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a word : ");
String c=s.nextLine();
String r="";
for(int i=c.length()-1;i>=0;i--)
{
r+=c.charAt(i);
}
System.out.println("Reverse : "+r);
}
}
Output:

39
3. a)Write a Java program to create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only the
method print Area () that prints the area of the given shape.

abstract class Shape


{
public int num1;
public int num2;
abstract void area();
}
class Rectangle extends Shape
{
Rectangle(int length,int breadth)
{
this.num1=length;
this.num2=breadth;
}
void area()
{
double a=num1*num2;
System.out.println("Area of Rectangle : "+a);
}
}
class Triangle extends Shape
{
Triangle(int height,int base)
{
this.num1=height;
this.num2=base;
}
void area()
{
double a=0.5*num1*num2;
System.out.println("Area of Triangle : "+a);
}
}
class Circle extends Shape
{
Circle(int radius)
{
this.num1=radius;
}
void area()
{
double a=Math.PI*num1*num1;
System.out.println("Area of Circle : "+a);
}
}
class Main
{
public static void main(String arg[])
{
Rectangle r=new Rectangle(12,12);
Triangle t=new Triangle(15,15);
Circle c=new Circle(10);
r.area();

40
t.area();
c.area();
}
}

Output:

b) Write a Java program to implement Inheritance.


class Animal {
String name;
Animal(String name {
this.name=name;
}
void speak() {
System.out.println("Animal Speak...");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
void speak() {
System.out.println(name+" says Woof Woof...");
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
void speak() {
System.out.println(name+" says Meow Meow...");
}
}
class ann {
public static void main(String arg[]) {
Dog d=new Dog("Jacky");

41
Cat c=new Cat("Leo");
d.speak();
c.speak();
}
}
4. Write a Java program to implement interfaces and packages.
package animal;
interface Animal
{
void makesound();
}
class Cat implements Animal
{
public void makesound()
{
System.out.println("Meow Meow ....");
}
}
class sound
{
public static void main(String arg[])
{
Cat c=new Cat();
c.makesound();
}
}
Output :

5. Write a program which will explain the concept of try, catch and throw.
class Excep
{
public static void main(String arg[])
{
try
{
int result=10/0;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero is not possible");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("Executed. ... ");
}
}

Output:

42
6. Write a java program that handles all mouse events and shows the event name at the center of
the window when a mouse event is fired
import java.awt.*;
import java.awt.event.*;
class frame extends Frame implements MouseListener, MouseMotionListener
{
Label l,l1;
frame()
{
l=new Label("");
l1=new Label("");
setLayout(null);
l.setBounds(20,40,100,25);
l1.setBounds(40,60,100,25);
add(l);
add(l1);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseDragged(MouseEvent e)
{
l.setText("Mouse Dragged");
}
public void mouseMoved(MouseEvent e)
{
l.setText("Mouse Moved");
l1.setText(" ( "+e.getX()+" , "+e.getY()+" ) ");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
}
class main
{
public static void main(String arg[])
{
frame f=new frame();
f.setVisible(true);
}
}
Output:

43
7. Showing concept of threads by importing thread class.
class data
{
synchronized public void display(String str)
{
for(int i=0;i<str.length();i++)
{
System.out.print(str.charAt(i));
try
{
Thread.sleep(100);
}
catch(Exception e){};
}
}
}
class thread extends Thread
{
data d;
public thread(data d)
{
this.d=d;
}
public void run()
{
d.display("Hello World");
}
}
class thread1 extends Thread
{
data d;
public thread1(data d)
{
this.d=d;
}
public void run()
{
d.display("Welcome All");
}
}
class thSyn
{
public static void main(String arg[])
{
data d=new data();
thread t1=new thread(d);
thread1 t2=new thread1(d);
t1.start();
t2.start();
}
}

44
Output:

8. a) Write an applet program that displays a simple message.


import javax.swing.JApplet;
import java.awt.Graphics;

public class msg extends JApplet


{ public void paint(Graphics g)
{
g.drawString("Hello World", 50, 50);
}
}

b) Write a program for passing parameters using Applet.


import java.applet.Applet;
import java.awt.Graphics;

public class ParamApplet extends Applet {


private String message;
public void init() {
message = getParameter("message");
if (message == null) {
message = "No message provided";
}
}
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}

9. Write a program to describe AWT Class, Frames, Panels and Drawing.


import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{
int x=0,y=0;

MyFrame()
{
super("Painting Demo");

addMouseMotionListener(new MouseAdapter(){

45
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
});

}
public void paint(Graphics g)
{
g.setColor(Color.MAGENTA);
g.setFont(new Font("Luminari",Font.BOLD,30));
g.drawString("Hello", x, y);
}
}
class Paint
{ public static void main(String[] args) {
MyFrame f=new MyFrame();
f.setSize(500,500);
f.setVisible(true);
}

Output:

10. Write a program to demonstrate JDBC and build an application.


import java.awt.*;
import java.util.*;
import java.awt.event.*;
class frame extends Frame implements ActionListener
{
TextArea t;
TextField tf;
Label l;
Button b;
frame()
{
super("Notepad");
t=new TextArea(30,80);
tf=new TextField(50);
l=new Label("Type Something ... ");
b=new Button("Click");
setLayout(new FlowLayout());
add(t);
add(tf);
add(l);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
t.insert(tf.getText(),t.getCaretPosition());
}
}
class np
{
public static void main(String arg[])
{

46
frame f=new frame();
f.setVisible(true);
f.setSize(500,500);
}
}

Out

47
48
ACKNOWLEDGEMENT

I would like to express my sincere thanks to Abdul Bari for his excellent teaching and guidance
throughout this online Java course on Udemy. His clear explanations and structured approach
have significantly enhanced my understanding of Java programming.
I also appreciate the platform Udemy for providing such a well-organized and user-friendly
learning environment.
Finally, I am grateful to my teachers and fellow learners for their support and encouragement
during this course.
Thank you all for your contributions to this successful learning journey.

Anshul
Pratap Singh
LTSU Punjab

49

You might also like