Java Report2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

GURU TEGH BAHADUR 4TH CENTENARY ENGINEERING COLLEGE

TRAINING REPORT
JAVA

Bachelor of Technology
in
Computer Science & Engineering
2022 - 2026
G-8 AREA, RAJOURI GARDEN, NEW DELHI-110064

Under the Guidance of:


S. Pardeep Singh
HOD (CSE)

Submitted by:- Ansh Garg


Name:- Ansh Garg
Enrolment No.:- 03123802722
Batch:- CSE-1
Training name :- JAVA
Organisation name:- Dynamic Future Teach pvt. Ltd.
Abstract
This report provides an in-depth overview of a Java Basics Training Program
developed to build foundational knowledge and skills in Java programming. Java is a
prominent language in software development due to its platform independence,
security features, and adaptability across various domains, from web applications to
enterprise systems and mobile apps. The training program was designed to cater to
both beginners and individuals with minimal prior experience in coding, aiming to
introduce them to the core principles of Java and programming fundamentals.
The curriculum encompassed essential topics, beginning with Java installation, setting
up the development environment, and an introduction to Integrated Development
Environments (IDEs). From there, participants were introduced to Java syntax, data
types, variables, operators, and control structures such as loops and conditionals. A
significant portion of the training was dedicated to Object-Oriented Programming
(OOP) concepts, including classes, objects, inheritance, polymorphism, and
encapsulation, which form the backbone of Java’s architecture. Additional modules
addressed error handling through exceptions, basic data structures (like arrays and
lists), and input/output operations to manage data flow within Java applications.
Practical exercises and projects played a central role in the program, allowing
participants to apply theoretical knowledge in real-world coding tasks. By working
through example projects and coding challenges, trainees learned to write, debug, and
optimize Java code effectively. Each module concluded with assessments to measure
understanding, and interactive sessions were included to resolve common queries and
reinforce learning.
The program’s outcomes were evaluated based on participant performance in these
assessments, feedback collected, and the final project deliverables. The report
analyzes the effectiveness of the program, highlighting areas of strength, such as
improved proficiency in Java fundamentals and the ability to understand and
implement core programming structures. It also provides recommendations for
enhancing future iterations of the training, including additional resources for
continued learning and advanced topics to bridge the gap to professional software
development.
Overall, the Java Basics Training Program successfully equipped participants with the
skills necessary to pursue further studies in Java, laying a strong foundation for
advanced programming courses and career opportunities in software development.
Acknowledgment
I would like to express my sincere gratitude to Dynamic Future Tech
Pvt. Ltd. for the invaluable training experience. Special thanks to
Summit Sir for his expert guidance, support, and insights, which
greatly enriched my understanding and skills. His mentorship was
instrumental in helping me grasp the complexities of the training
and develop practical knowledge.

I would also like to extend my appreciation to Mr. Pradeep Singh,


Head of the Computer Science Department, and to Guru Tegh
Bahadur 4th Centenary Engineering College for their
encouragement and continuous support. The institution and its
dedicated faculty have provided an invaluable foundation, enabling
me to make the most of this training experience and further my
academic and professional growth.
Thank you all for contributing to this rewarding learning journey
Introduction

Java is a general purpose, high-level programming language developed by Sun


Microsystems. The Java programming language was developed by a small team of
engineers, known as the Green Team, who initiated the language in 1991.

The Java language was originally called OAK, and at the time it was designed for
handheld devices and set-top boxes. Oak was unsuccessful and in 1995 Sun changed the
name to Java and modified the language to take advantage of the burgeoning WorldWide
Web.

Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of
two key Sun software assets: Java and Solaris.

Today the Java platform is a commonly used foundation for developing and delivering
content on the web. According to Oracle, there are more than 9 million Java developers
worldwide and more than 3 billion mobile phones run Java.

In 2014 one of the most significant changes to the Java language was launched with Java
SE 8. Changes included additional functional programming features, parallel processing
using streams and improved integration with JavaScript. The 20th anniversary of
commercial Java was celebrated in 2015.

Java is defined as an object-oriented language similar to C++, but simplified to


eliminate language features that cause common programming errors. The source
code files (files with a .java extension) are compiled into a format called bytecode
(files with a .class extension), which can then be executed by a Java interpreter.
Compiled Java code can run on most computers because Java interpreters and
runtime environments, known as Java Virtual Machines (VMs), exist for most
operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can
also be converted directly into machine language instructions by a just-in-time
compiler (JIT). In 2007, most Java technologies were released under the GNU General
Public License.

1. Object oriented
2. Simple
3. Secured
4. Platform independent
5. Robust
6. Portable
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High performance
11. Multithreading
12. Distributed

1. Developing
2. Desktop application
3. Web application
4. Mobile software
5. Smart card
6. Robotic games
7. Many different ways we can use java coding.
JAVA LANGUAGE- 1995

( .Java ) ( .Class )

JAVA SOURCE CODE------>COMPILER-------->BYTE CODE >DIFFERENT PLATFORM.


//platform independent

It is not user readable nor machine readable. It is platform


independent but JVM isplatform dependent.

JVM is an engine that provides runtime environment to drive the Java Code or
applications . It converts Java bytecode into machines language. JVM is a part of
JRE(Java Run Environment). It stands for Java Virtual Machine.
 In other programming languages, the compiler produces machine code for
a particular system. However, Java compiler produces code for a Virtual
Machine known as Java Virtual Machine.
 First, Java code is compiled into bytecode. This bytecode gets interpreted
on different machines
 Between host system and Java source, Bytecode is an intermediary
language.
 JVM is responsible for allocating memory space.
Let's understand the Architecture of JVM. It contains class loader, memory area,
execution engine etc.

In order to write and execute a software program, you need the following

1. Editor – To type your program into, a notepad could be used for this
2. Compiler – To convert your high language program into native machine code
3. Linker – To combine different program files reference in your main program
together.
4. Loader – To load the files from your secondary storage device like Hard Disk,
Flash Drive, CD into RAM for execution. The loading is automatically done
when you execute your code.
5. Execution – Actual execution of the code which is handled by your OS &
processor.
Variables - They are used to store information. It is a piece of memory that contains data
value. A variable has a different data type. It is basically the name of the memory chunk in
which we store our data.

1. Local Variable
2. Instance Variable
3. Static Variable

It is a variable which is declared inside the method and we can only access this variable
in that particular method.

It is a variable which is declared at a class level with a static keyword is known as a static
variable. It gets memory once in its whole life cycle.

A variable which is declared at class level and which is non static is known as instance
variable.

class Example{
static int c; // Static variable
int a = 0; // Instance variable
void fun(){
int a,b; // Local variable
}
When a single condition is there and we have to check for that condition then we use the if-
else condition.

public class Main


{
public static void main(String[] args) {
int x=20, y=10;
if(x>y){
System.out.println("X is greater");
}
else{
System.out.println("Y is greater");
}
}
}

Output –
When multi-condition is there. According to our logic or code according to the condition
satisfied the particular block of that code will be executed. If no conditions are satisfied
then the else part will be executed.

public class Main


{
public static void main(String[] args) {
int x=20, y=10;
if(x>y){
System.out.println("X is greater");
}
else if(y>x){
System.out.println("Y is greater");
}
else{
System.out.println("Both are equal");
}
}
}

Output-
In this we also have multiple situations. In this we handle these situations using cases.
There is a default case also. We have to apply a break statement after every case so that
we can stop execution of another case. No need to apply a break after the default
statement.

public class Main


{
public static void main(String[] args) {
int ch =1;
switch(ch){
case 1:
System.out.println("First month is january");
break;
case 2:
System.out.println("Second month is febuary");
break;
case 3:
System.out.println("Third month is march");
break;
default:
System.out.println("Not a valid month");
}
}
}

Output –
When we want to execute a particular code for some time/until a condition is true we
use loops.

There are three types of loops in java

1. For
2. Do-while
3. While

For loop is used to iterate a part of the program several times. Number of iterations is
fixed, it is recommended to use for loop.

class Main{
public static void main(String[] args){
for (int i=1; i<=5; i++){
System.out.println(i);
}

Output -

While loop is an entry-controlled loop. Conditions will be checked at entry level.


class Main{
public static void main(String[] args){
int i = 0;
while(i<5){
System.out.println("Hello");
i++;
}
}
}

Output

It is an exit control loop. Conditions will be checked at exit level. Loop will be executed
at least one time.

class Main{
public static void main(String[] args){
int i = 0;
do{
System.out.println("Hello");
i++;
}while(i<5);
}
}

Output
In this concept everything is represented as an object is known as OOP’s concept but we
can say that Java isn’t truly object-oriented programming language because Java is not
fully focused on object.

Visual basic is fully object oriented.

It is a real-world entity which contains two things: state & behaviour. It is the instance
of class (part of class). It contains the state and behaviour of class.

It is a collection of similar types of objects. It is the blueprint from which the object is
created.

Object contains three things --> State, Behaviour and Identity.

It represents the internal state of an object it's belong data (value.).

It shows the functionality of an object.

Object identity is typically implemented via a unique I.D. The value of ID is not visible to
the external user but it is used internally by the JVM to identify each object uniquely.
pg. 27
One object acquiring all properties and behaviour of a parent class is known as
inheritance. Basically, it provides code reusability. It is used for achieving run-time
polymorphism. It is also known as is-a-relationship (parent-child relationship).

Inheritance types

In java multiple and hybrid inheritance is supported through interface only.

There are following Advantage of inheritance:

1. Method Overriding (which is achieved by runtime polymorphism)


2. Code Reusability
class a{
void commonProperty(){
System.out.println("4 legs (Parent class)");
}
}

class b extends a{
void cat(){
System.out.println("Cat -> Properties ...... (Child class)");
}
}

public class Main


{
public static void main(String[] args) {
b obj = new b();
obj.commonProperty();
obj.cat();
}
}

Output

Why can’t we implement multiple inheritance directly?


class a{
}
class b{
}
class c extends a,b{
}
Now if a and b contain the same method then there will be confusion in class c.
Constructor is a special type of method. That is used to initialize the object. In every
program in java constructor invoked at a time of object creation. It constructs the value
(data) for the object that is why it is called a constructor.

There is certain rule of constructor

1. Constructor must have the same name as the class name.


2. Constructor doesn't have any return type.

There are three type constructors in java

1. Defaulter constructor
2. No argument constructor
3. Parameterized constructor

This is a defaulter constructor. If programmers don't initialize a constructor then JVM


automatically creates this constructor.

class example{
{
System.out.println("Hello! I am defaulter constructor.");
}
}
pg. 35
public class Main
{
public static void main(String[] args) {
example obj = new example();
}
}

Output

Hello! I am defaulter constructor.

Constructor which doesn't have any argument called no argument constructor.

class example{
example(){
System.out.println("Hello! I am non parameterized constructor.");
}
}

public class Main


{
public static void main(String[] args) {
example obj = new example();
}
}

pg. 36
Output -
Hello! I am non parameterized constructor.

Constructors which have arguments are called parameterized constructor.

class example{
int a,b;
example(int x, int y){
a=x; b=y;
}
void printInfo(){
System.out.println("Value of a is " + a + " and value of b is " + b);
}
}

public class Main


{
public static void main(String[] args) {
example obj = new example(10, 20);
obj.printInfo();
}
}

pg. 37
Output Note: It is called constructor because it constructs
the values at the time of object creation. It is not
Value of a is 10 and value of b is 20 necessary to write a constructor for a class. It is
because the Java compiler creates a default
constructor if your class doesn’t have any.

1. An interface cannot have the constructor.


2. Constructor cannot be private.
3. A constructor cannot be abstract, static, final, native, strictfp, or synchronized.
4. A constructor can be overloaded.
5. Constructors cannot return a value.
6. Constructors do not have a return type: not even void.
7. An abstract class can have the constructor.
8. Constructor name must be similar to that of the class name inside which it resides.
9. Constructors are automatically called when an object is created.

pg. 38
Used to copy properties of one object to another object. In Java we don’t have any
constructor.

Remember there is no copy constructor concept in java. We only use constructor for
copy.
class Director{
String name;
int age;
Director(String name, int age){
this.name = name;
this.age = age;
}
void director_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition ->
Director\nSalary->100000");
}
}

class Trainer{
String name;
int age;
Trainer(Director obj){
name = obj.name;
age = obj.age;
}

void trainer_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition -> trainer\nSalary-
>50000");
pg. 39
}
}

class Developer{
String name;
int age;
Developer(Director obj){
name = obj.name;
age = obj.age;
}
void developer_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition ->
Developer\nSalary->80000");
}
}

public class Main


{
public static void main(String[] args) {
Director obj = new Director("Sumit", 29);
Trainer obj1 = new Trainer(obj);
Developer obj2 = new Developer(obj);
obj.director_info();
obj1.trainer_info();
obj2.developer_info();
}
}

Output
This is a reference variable in java. It’s used to reference the current object.

class Director{
String name;
int age;
Director(String name, int age){
this.name = name;
this.age = age;
}
void director_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition ->
Director\nSalary->100000");
}
}

class Trainer{
String name;
int age;
Trainer(Director obj){
name = obj.name;
age = obj.age;
}

void trainer_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition -> trainer\nSalary-
>50000");
}
pg. 44
}

class Developer{
String name;
int age;
Developer(Director obj){
name = obj.name;
age = obj.age;
}
void developer_info(){
System.out.println("Name is "+name+" age is "+age+"\nPosition ->
Developer\nSalary->80000");
}
}

public class Main


{
public static void main(String[] args) {
Director obj = new Director("Sumit", 29);
Trainer obj1 = new Trainer(obj);
Developer obj2 = new Developer(obj);
obj.director_info();
obj1.trainer_info();
obj2.developer_info();
}
}

Output

pg. 45
public class Main
{
int age; String b_place;
Main(){
this(20, "Muzaffarnagar");
System.out.println("I am Abhishek");
}
Main(int age, String b_place){
this.age = age;
this.b_place = b_place;
System.out.println("Age is "+age+" and birth place is "+b_place);
}
public static void main(String[] args) {
// System.out.println("Hello World");
Main obj = new Main();
pg. 46
}
}

Output

public class Main


{
int age; String b_place;
Main(){
System.out.println("I am Abhishek");
}
Main(int age, String b_place){
this();
this.age = age;
this.b_place = b_place;
System.out.println("Age is "+age+" and birth place is "+b_place);
}
public static void main(String[] args) {
// System.out.println("Hello World");
Main obj = new Main(20, "Muzaffarnagar");
}
}
P
Output

public class Main


{
int a=10,b=20;
void fun1(){
int ans = a-b;
System.out.print(" and sum is "+ans);
}
void fun2(){
int ans = a+b;
System.out.println("Subtraction is "+ans);
this.fun1();
}
public static void main(String[] args) {
// System.out.println("Hello World");
Main obj = new Main();
obj.fun2();
}
}

Output
Access modifiers will define the accessibility of a class. Means how the class will be
accessible like it will be inherited or not.

Can be accessed within or outside the package.

Can be within package and outside package but in only the child class.

We can access only within the class.

We can access only within the package.


Data hiding is a software development technique specifically used in object-oriented
programming (OOP) to hide internal object details (data members). Data hiding ensures
exclusive data access to class members and protects object integrity by preventing
unintended or intended changes.

Outside person can’t access our internal data directly or our internal data should not go
out directly. This OOP feature is nothing but data hiding. After validation or
authentication, an outside person can access our internal data.

When we talk about data hiding that simply mean with private keyword. For hiding
something we keep that thing private.

class Example {
private int x;
}

Hiding internal implementation and just highlighting the set of services that we are
offering, is the concept of abstraction. For example, through bank ATM GUI screen
banks highlight a set of services that the bank offers without highlighting internal
implementation.

Simply, Abstraction means hiding implementation from the user.

 We can achieve security because we are not highlighting our internal


implementation
 Without affecting outside people, we are able to perform any type of changes
in our internal system and hence enhancement will become easy.
 It improves maintainability of the application.
 It improves the ease of use of our system.

Process of binding data and corresponding methods into a single unit is nothing but
encapsulation. Basically, class means encapsulation.
If any component follows data hiding and abstraction such type of component is said to
be an encapsulated component.

Encapsulation = data hiding + abstraction.

A class is said to be tightly encapsulated if and only if each and every variable declared
as private whether class contains corresponding getter and setter method or not and
whether these methods declared public or not these things we are not required to
check.

If a class has an entity reference, it is known as Aggregation. Aggregation represents


HAS- A relationship.

Basically, when we create our own custom data type variable using class and
implement/use those data types that is called aggregation.
Static keyword can be used with class, variable, method and block. Static members
belong to the class instead of a specific instance, this means if you make a member static,
you can access it without an object.

In java it is a variable which belongs to class and initialized only once at the start of the
execution. It will retain its value.
 A single copy to be shared by all instances of the class.
 A static variable can be accessed directly by the class name and doesn’t need
any object.

Static method in java is a method which belongs to a class and not to the object. Static
method can access only static data.

 A static method can call only other static methods and cannot call a non-static
method from it.
 A static method can be accessed directly by the class name and doesn’t need any
object.
 A static method cannot refer to “this” or “super” keywords in any way.

Syntax: <class name>.<method name>

It makes your program memory efficient (i.e.: saves memory).

Static means, when something is declared as static that means now that variable or
function now belongs to a class not to an object. It will be common for all objects. It will
be called using the class name.
Code
import java.util.Scanner;

class Election{
static String cm = "AAP";

static void fun(){


cm = "BJP";
}
}

public class Main


{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name : ");
String name = sc.next();

System.out.print("Are you from Delhi (0/1) : ");


int ch = sc.nextInt();

if(ch==0){
return;
}

System.out.print("Are you greater than 18 (0/1) : ");


int ch1 = sc.nextInt();

if(ch==0){
return;
}

System.out.print("Yo want to know cm before 2022 or after 2022 (0/1) : ");


int ch2 = sc.nextInt();
if(ch2==0){
System.out.println(Election.cm);
}

else{
Election.fun();
System.out.println(Election.cm);
}
}
}

Output
Static blocks help to initialize the static data members just like constructor initialize
instance variables. It is like a constructor and used to initialize static variables at run time.

import java.util.Scanner;

public class Main


{
static String government_name;

static{
government_name = "AAP";
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int n = 5;

while(n!=0){
System.out.println("Placed after 2002 or before\nBefore ---> 1\nAfter ---> 2");
int ch = sc.nextInt();

if(ch==1){
System.out.println("Pension alotted to you by " + Main.government_name + "
government");
}

else{
System.out.println("No pension alotted to you by " + Main.government_name
+ " government");

pg. 77
}
n--;
}
}
}

Output
Polymorphism means performing a single action in different ways.
We called poly + morphism. Poly means many and morphism means form, so we can say
that polymorphism means many forms.

1. Run time
2. Compile time

Compile polymorphism is obtained through method overloading.

Overloading allows different methods to have the same name, but different
signatures where signature can differ by number of input parameters or type of input
parameters of both.

We also overload static methods and main function.

Method overloading increases the readability of the program.

import java.util.Scanner;

public class Main


{
static int area (int l, int b){
return l*b;
pg. 79
}

static float area(int r)


{ float area = r*r*3.14f;return area;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int r_area = Main.area(10,20);
float c_area = Main.area(3);
System.out.println("Area of rectangle with l = 10 and b = 20 is " + r_area);
System.out.println("Area of circle with radius 3 is " + c_area);
}
}

Output

Runtime polymorphism is obtained through method overriding.


We use this concept if parent and child classes have the same function and we want
different implementations in both the classes.

If public class provides the specific implementation of the method that has been
provided by one of its parents. It is called method overriding.

There are following use of method overriding

1. Method overriding is used to provide specific implementation of a method.


That is provided by its super class.
2. Method overriding is achieved by runtime polymorphism.

1. Method overriding has the same name as the parent class.


2. Method must have the same parameter in the parent class.
3. It is used in is-a-relationship (Inheritance).

import java.util.Scanner;

class Example{
int computation(int a, int b){
int ans = a+b;
return ans;
}
}
pg. 82
class Example_one extends Example{
int computation(int a, int b) {
int ans = b-a;
return ans;
}
}

public class Main


{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Example_one obj = new Example_one();
int ans = obj.computation(10, 20);
System.out.println("Substraction is " + ans);

}
}

Output
Super keyword refers to the immediate parent of the class.

This scenario occurs when a derived class and base class have the same data members.

This is used when we want to call the parent class method. So whenever a parent and
child class have the same named methods then to resolve ambiguity we use super
keyword.

Super keyword can also be used to access the parent class constructor. One more
important thing is that, ‘super’ can call both parametric as well as not parametric
constructors depending upon the situation.

Note
To access parent constructor using
super keyword via child constructor
then super () should be in the first line.

class ABC
{
int a;

ABC(){
System.out.println("Parent constructor");
}
void display(){
System.out.println("Parent display");
}
}

class XYZ extends ABC


{
int a;
XYZ(){
super(); // This should be in first line. // Use with constructor
System.out.println("Child constructor");
}

XYZ(int x, int y){


super.a = x;
a = y;
}

void display ()
{
System.out.println ("a variable from child class : " + a);
System.out.println ("a variable from parent class : " + super.a); // Use with variable
super.display(); // Use with methods
}
}

public class Main


{
public static void main (String[]args)
{
It is a block where it initialize the instance of data member. It run when the object is
created.
It initialize the data members at run time.

Suppose I have to perform some operations while assigning value to instance data
member e.g. A for loop to fill a complex array or error array or error handling etc.

class Example{
int a = 10;
{
a = 199;
System.out.println("This is initializer bock");
System.out.println("Value of a is " + a);
}
Example(){
System.out.println("This is constructor");
System.out.println("Value of a is " + a);
}
}

class Main{
public static void main(String[] args) {
Example obj = new Example();
}
}

Output –
Note
Initializer block will always run first when the
object created after that constructor execute.
class ExampleOne{
ExampleOne(){
System.out.println("This is parent class constructor");
}
}
class Example extends ExampleOne{
int a = 10;
{
a = 199;
System.out.println("This is initializer bock");
System.out.println("Value of a is " + a);
}
Example(){
super();
System.out.println("This is child class constructor");
System.out.println("Value of a is " + a);
}
}

class Main{
public static void main(String[] args) {
Example obj = new Example();
}
}

Note
First parent class initializer block executed then parent class constructor then
child class initializer block then child class constructor.

Output –

1. In this block we create instance of class


2. In this block we invoked after the parent class constructor is invoked
3. The instance initializer block comes in the order in which they appear.
The Final keyword in java is used to restrict the user. The java final keyword can be used in
many context.
If we declare a variable or method final then we cannot change it.
There are three ways to use final:
1. Variable
2. Method
3. Class

What it does:
1. Stop value changing (in term of variable)
2. Stop method overriding (in terms of method)
3. Stop inheritance (in terms of class)

class Main{
public static void main(String[] args) {
final int a = 10 ;
a = 20;
}
}

This will throw an error.

If we make any variable as final, you can’t change the value of final
variable (It will be constant).
Instance of will return true or false if the passed object is instance (part of) the class it will
return true else will return false

class Main {
public static void main(String[] args)

{
Main s = new Main();
System.out.println(s instanceof Main); // true
}
}

Output –

In Java, an instance is a concrete occurrence of any object created from a class. When you
create an instance, you allocate memory for a specific object and can access its attributes and
methods.
It is a process to showing personality and hiding the internal details and showing only
functionality to the user.

Method that are declared without any body within an abstract class are called abstract
method. The method body will be defined by its subclass. Abstract method can never
be final and static. Any class that extends an abstract class must implement all the
abstract method declared by the super class.

1. Always end the declaration with a semicolon (;).


2. It must be overridden. An abstract class must be extended and in a
same way abstract method must be overridden. .
3. A class has to be declared abstract to have abstract methods

Note
The class which is extending abstract class must override all the
abstract methods.

1. Through the abstraction class


2. Through the interface
abstract class summation{
abstract void sum(int a, int b);
}

abstract class substraction_and_summation extends summation{


abstract void sub(int a, int b);
}

class calculation extends substraction_and_summation{


void sum(int a, int b){
int ans = a+b;
System.out.println("Sum is " + ans);
}
void sub(int a, int b){
int ans = a-b;
System.out.println("Substraction is " + ans);
}
void multiplication(int a, int b){
int ans = a*b;
System.out.println("Multiplication is " + ans);
}
void division(int a, int b){
int ans = a/b;
System.out.println("Division is " + ans);
}
}

public class Main


{
public static void main(String[] args) {
calculation obj = new calculation();
obj.sum(10, 20);
obj.sub(20, 5);
obj.multiplication(2, 3);
obj.division(8, 2);
}
}

Output –

Note
We can have an abstract class without any abstract method. This allows us
to create classes that cannot be instantiated, but can only be inherited.

An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in java.

Java interface also represents IS-A relationship.


Multiple Inheritance is a feature of object oriented concept, where a class can inherit properties
of more than one parent class. The problem occurs when there exist methods with same signature
in both the super classes and subclass. On calling the method, the compiler cannot determine
which class method to be called and even on calling which class method gets the priority.

interface summation{
void sum(int a, int b);
}

interface substraction{
void sub(int a, int b);
}

class calculation implements substraction, summation{


public void sum(int a, int b){
int ans = a+b;
System.out.println("Sum is " + ans);
}
public void sub(int a, int b){
int ans = a-b;
System.out.println("Substraction is " + ans);
}
void multiplication(int a, int b){
int ans = a*b;
System.out.println("Multiplication is " + ans);
}
void division(int a, int b){
int ans = a/b;
System.out.println("Division is " + ans);
}
}

public class Main


{
public static void main(String[] args) {
calculation obj = new calculation();
obj.sum(10, 20);
obj.sub(20, 5);
obj.multiplication(2, 3);
obj.division(8, 2);
}
}

Output –
Abstract class Interface
1. An abstract class can extend An interface can extend any
only one class or one abstract number of interfaces at a
class at a time. time.
2. An abstract class can extend An interface can only extend
another concrete (Regular) another interface.
class or abstract class.
3. An abstract class can have An interface can have only
both abstract and concrete abstract methods.
methods.
4. In abstract keyword In an interface keyword
“abstract” is mandatory to “abstract” is
declare a method as an optional to declare a method
abstract. as an
abstract.
5. An abstract class can have An interface can have only
protected and public have public abstract methods.
abstract methods.
6. An abstract class can have Interface can only have public
static, final or static final static final (constant) variable.
variable with any access
specifier.
ARRAY

Normally, array is a collection of similar type of elements that have contiguous memory
location. Java array is an object that contains elements of similar data type. It is a data structure
where we store similar elements.

We can store only fixed set of elements in a java array. Array in java is index based, first
element of the array is stored at 0 index.
We can also pass array as a parameter to a function.

Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily. Random access: We can get any data located at any index position.

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
run time. To solve this problem, collection framework is used in java.

1. Single dimensional array


2. Multidimensional array
import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);


int n = scan.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = scan.nextInt();
}
scan.close();

// Prints each sequential element in array a


for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}

Output –

EXAMPLE OF 2D ARRAY
String is a sequence of characters. It is an immutable object which means it is constant
and can cannot be changed once it has been created.

There are two ways to create a String in Java.


1. String literal
2. Using new Keyword

//creating a string by java string literal


String a = “Abhishek”;

Char a [] = {‘a’, ‘b’, ‘h’, ‘I’};


//converting char array a[] to string s
String s = new String (a);

//creating another java string s by using new keyword


String s = new String (“Abhishek”);
Output –

Changes in string are temporary because strings are immutable.


Temporary means you change value at that moment only. But actual value of string is
not changed.

pg. 147
Exceptions: An exception is an unwanted of unexpected event, which occurs the execution of
a program I.e. At run time.

Exception handling ensures that the flow of the program doesn’t break when an
exception occurs.

Error: an error indicates serious problem that a reasonable application should not tryto
catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.

NullPointer Exception: When you try to use a reference that points to null.
Arithmetic Exception: When bad data is provided by user, for example, when you try
to divide a number by zero this exception occurs because dividing a number by zero
isundefined.

There are two types of exceptions in Java:


1. Checked exceptions
2. Unchecked exceptions

Checked: are the exceptions that are checked at compile time.


Unchecked: are the exceptions that are checked at run time.

Handling try block


The try block contains set of statements where an exception can occur.
Syntax of try block

try {
//Statement that can cause an exception.}
A Catch block is where you handle the exceptions, this block must follow the try block.A
single try block can have several catch blocks associated with it. You can catch different
exceptions in different catch blocks. When an exception occurs in try block, the
corresponding catch block that handles that particular exception executes.

Syntax of try catch block

try {
//Statement that can cause an exception.
}
catch (exception(type) e(object)){
//Error handling code.
}

For now you just need to know that this block executes whether an exception occurs
ornot. You should place those statements in finally blocks, that must execute whether
exception occurs or not.

Syntax of finally block

try {

//Statements that may cause an exception.


}
catch {
//Exception handling code.
}
finally {
//Statement to be executed.
}
import java.util.Scanner;
public class Main{

public static void main(String[] args) throws Exception{


Scanner sc = new Scanner(System.in);
int arr[] = {1, 2, 3, 4, 5, 6};
System.out.print("Which index you want to access : ");
int in = sc.nextInt();
if(in>5){
throw new Exception("Array out of bound! You can't access that index value.");
}
else{
System.out.println(arr[in]);
}
}
}

Output –

1. Throws clause is used declare an exception. Which means it works similar to the
try-catch block. On the other hand throw keyword is used to throw an exception
explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class
and throws is followed by exception class names.

Throws keyword exception propagation using throws keyword


Multithreading in java is a process of executing multiple threads simultaneously. Java
Multithreading is mostly used in games, animation etc.

1. It doesn’t block the user because threads are independent and you can perform
multiple operations at same time.
2. You can perform many operations together so it saves time.
3. Threads are independent so it doesn’t affect other threads if exception occur in
a single thread.

Multitasking is a process of executing multiple tasks simultaneously. We


use multi tasking to utilize to CPU.

1. Process-based multitasking (Multiprocessing)


2. Thread-based Multitasking (Multithreading)

Thread can be in one to the face states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated, there is no
running state.
1. New: The thread is in new state if you create an instance of Thread class but
before the invocation of start () method.
2. Runnable: The thread is in runnable state after invocation of start () method, but
the thread scheduler has not selected it to be the running thread.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked) or waiting: This is the state when the thread is still alive,
but is currently not eligible to run.
5. Terminated: A thread is in terminated or dead state when its run () method exits.

1. Public void run (): Is used to perform action for a thread.


2. Public void start (): Starts the execution of the thread. JVM calls the run ()
method on the thread.
3. Public void sleep (long milliseconds): Causes the currently executing thread to
sleep(temporarily cease execution) for the specified number of milliseconds.

4. Public void join (): Waits for a thread to die.


5. Public void join (long milliseconds): Waits for a thread to die for the specified
milliseconds.

Multi-Tasking: Ability to execute more than one task at the same time is known as
multitasking.
Multithreading: It is a process of executing multiple threads simultaneously.
Multithreading is also known as Thread-based Multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one
CPUs are involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer
syste1.
1. getName(): It is used for obtaining a thread’s name.
2. getPriority(): Obtain a thread’s priority.
3. isAlive(): Determine if a thread is still running
4. join(): Wait for a thread to terminate
5. run(): Entry point for the thread
6. sleep(): suspend a thread for a period of time.
7. start(): start a thread by calling its run() method.

 Thread priorities are the integers which decide how one thread should betreated
with respect to the others.
 Thread priority decides when to switch from one running thread to another,process
is called context switching.
 A thread can voluntarily release control and the highest priority thread that isready
to run is given the CPU.

 A thread can be pre-empted by higher priority thread no matter what the lower
priority thread is doing. Whenever a higher priority thread wants to run it does.
 To set the priority of the thread setPriority () method is used which is a method
of the class Thread class.
 In place of defining the priority in integers, we can
 Use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

 Multithreading introduces asynchronous behavior to the programs. If a thread is


writing some data another thread may be reading the same data at that time,
this may cause bring inconsistency.
 When two or more threads need access to a shared resource there should be
someway that the resource will be used only by one resource at a time. The
process to achieve this is called synchronization.
Java permits an object of a sub class can be referred by its super class. It is done
automatically.

It is to be performed manually by the developers. Here explicit casting is to be done by


the super class.

Join method can be used to pause the current thread execution until unless the
specified thread is dead. There are there overloaded join functions.

wait
Object wait methods has three variance, one which waits indefinitely for any other
thread to call notify or notifyAll method on the object to wake up the current thread.
Other two variances puts the current thread in wait for specific amount of time before
they wake up.

notify
Notify method wakes up only one thread waiting on the object and that thread starts
execution. So if there are multiple threads waiting for an object, this method will wake
up only one of them. The choice of the thread to wake depends on the OS
implementation of thread management.

notifyAll

notifyAll method wakes up all the threads waiting on the object, although which one will
process first depends on the OS implementation.
Output –
// start second thread after waiting for 2 seconds or if it's dead
t1.join(2000);
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
// start third thread only when first thread is dead
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
// let all threads finish execution before finishing main thread
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block e.printStackTrace();
}

System.out.println("All threads are dead, exiting main thread.");


}
}
Package are used in Java, in-order to avoid name conflicts and to control access of
class, interface and enumeration etc. A package can be defined as a group of similar
types of classes ,interface, enumeration or sub-package. Using package it becomes easier
to locate the related classes and it also provides a good structure for projects with
hundreds of classes and other files.

1. Built-in
2. User defined

Existing Java package for example java.lang, java.util etc.

Java packages created by user to categorize their project’s classes and interface.

pg. 221
Creating a package in java is quite easy. Simply include a package command followed
by name of the package as the first statement in java source file.
package mypack;

public class employee{


statement;
}

The above statement will create a package woth name mypack in the project
directory.
Java uses file system directories to store packages. For example the .java file for any
class you define to be part of mypack package must be stored in a directory called
mypack.

1. A package is always defined as a separate folder having the same name as the
package name.
2. Store all the classes in that package folder.
3. All classes of the package which we wish to access outside the package must be
declared public.
4. All classes within the package must have the package statement as its first line.
5. All classes of the package must be compiled before use (So that they are error
free)
Project 1
Tic tac toe
Code:
Project 2
Restaurant menu
Code:
Summary
This report outlines the Java Basics Training Program, designed to introduce
participants to core programming concepts in Java, a widely-used language valued
for its cross-platform capabilities, object-oriented principles, and robustness. The
program targeted beginners and individuals with limited programming experience,
with the goal of providing a comprehensive foundation in Java.
The topics covered included:
1. Introduction to Java and Setup: Java installation, configuration of the
development environment, and an overview of Integrated Development
Environments (IDEs).
2. Java Syntax and Basic Constructs: Fundamental language components like data
types, variables, operators, and control structures (conditionals, loops) to build
logic within code.
3. Object-Oriented Programming (OOP): Core OOP principles, including classes and
objects, inheritance, polymorphism, encapsulation, and abstraction—essential
for designing modular, reusable code.
4. Error Handling and Exceptions: Techniques for managing runtime errors using
try-catch blocks and custom exceptions to ensure program stability and
reliability.
5. Data Structures: Basic structures such as arrays and lists for data management
and organization within Java applications.
6. Input and Output Operations: File handling and input/output methods to
facilitate data storage, retrieval, and manipulation.
The program employed practical coding exercises, mini-projects, and assessments
to solidify learning, with each topic reinforced through hands-on applications and
coding challenges. These activities enabled participants to apply their learning to
real-world programming tasks, from simple applications to more complex problem-
solving scenarios.
Evaluations of the program indicated that participants gained significant proficiency
in Java fundamentals, laying the groundwork for advanced study and practical
application in software development roles. This report highlights the program
structure, learning outcomes, participant feedback, and recommendations for
expanding future iterations to further support foundational skill-building in Java.
Results
The Java Basics Training Program effectively introduced participants to foundational
Java programming concepts, enhancing their readiness for more advanced
programming courses and real-world application development. Based on
assessments, project submissions, and participant feedback, the following key
results were observed:
1. Improved Understanding of Core Java Concepts: Participants demonstrated
proficiency in Java syntax, control structures, and basic programming
constructs. Post-training assessments showed significant improvement in the
ability to write clear, logical code for common tasks.
2. Strong Grasp of Object-Oriented Programming (OOP): The majority of
participants successfully grasped essential OOP concepts, including classes,
objects, inheritance, polymorphism, and encapsulation. Participants were able
to apply these principles to create structured, reusable code in hands-on
projects.
3. Error Handling and Debugging Skills: By the end of the training, participants had
developed essential debugging skills, with a clear understanding of how to
handle errors using Java’s exception handling mechanisms. They could identify
and resolve common runtime errors, improving program stability.
4. Basic Data Structures Proficiency: Participants effectively applied basic data
structures like arrays and lists to organize and manipulate data within
applications, which was evident in coding exercises and final projects.
5. Practical Coding and Project Development: Practical exercises and final projects
allowed participants to apply theoretical concepts to real-world scenarios.
Projects revealed improved problem-solving abilities, and many participants
produced well-structured, functional code.
6. Positive Participant Feedback: Feedback collected through post-training surveys
indicated high satisfaction with the curriculum structure, practical focus, and
instructor support. Many participants expressed confidence in applying their
newly acquired Java skills in future programming tasks.
Overall, the training program successfully achieved its goals, equipping participants
with a solid foundation in Java. These results reflect the program’s effectiveness in
preparing participants for further learning and practical application in software
development roles.
References
1. JavaTpoint. (n.d.). Java Tutorial. Retrieved from
https://www.javatpoint.com/java-tutorial
2. OpenAI. (2024). ChatGPT: An AI Language Model for Programming Assistance
and Learning Support. Retrieved from https://www.openai.com
3. Oracle. (n.d.). The Java™ Tutorials. Oracle Documentation. Retrieved from
https://docs.oracle.com/javase/tutorial/
4. GeeksforGeeks. (n.d.). Java Programming Language – Basics and Advanced
Concepts. Retrieved from https://www.geeksforgeeks.org/java/
5. W3Schools. (n.d.). Java Tutorial. Retrieved from
https://www.w3schools.com/java/

You might also like