0% found this document useful (0 votes)
83 views41 pages

Training Report

The document describes a training report submitted by Aryaan Pegu, a student of Chandigarh School of Business Jhanjeri, for a summer training program undertaken at NOVEM Controls Pvt. Ltd. where the student worked on developing a Snake game. The report includes an introduction to the Snake game project, details of the company NOVEM Controls, and chapters covering concepts learned during the training.

Uploaded by

Geass
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views41 pages

Training Report

The document describes a training report submitted by Aryaan Pegu, a student of Chandigarh School of Business Jhanjeri, for a summer training program undertaken at NOVEM Controls Pvt. Ltd. where the student worked on developing a Snake game. The report includes an introduction to the Snake game project, details of the company NOVEM Controls, and chapters covering concepts learned during the training.

Uploaded by

Geass
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

CHANDIGARH SCHOOL OF BUSINESS JHANJERI

MOHALI-140307
DEPARTMENT OF COMPUTER APPLICATIONS

TRAINING
REPORT
OF
SUMMER TRAINING
UNDERTAKEN
AT
NOVEM CONTROLS PVT. LTD. ( MOHALI )
ON SNAKE GAME
SUBMITTED IN PARTIAL FULFILLMENT
OF THE DEGREE
OF
BACHELOR OF COMPUTER
APPLICATIONS
Submitted By:
NAME:- ARYAAN PEGU
Roll No. :-2133040
DEPARTMENT OF COMPUTER APPLICATIONS
CGC JHANJHERI
MOHALI-140307
CANDIDATE’S DECLARATION
I ARYAAN PEGU hereby declare that I have undertaken Summer training at

NOVEM CONTROLS PVT. LTD. (MOHALI) during period from 15 June 2023 to

30 July 2023 in partial fulfillment of requirements for the award of the degree

of BCA (Computer Applications) at Chandigarh groups of collage, Jhanjheri.

The work which is being presented in the training report submitted to Department of
Computer Applications) at Chandigarh groups of collage, Jhanjheri is an authentic
record of training work.

Candidate’s Signature
The summer training Viva- Voce Examination of _____________________________________
has been held on _______________________________and accepted.
Signature of Examiner
COMPANY PROFILE
NOVEM is a leading system engineering and integration company in India, offering

application design, development, testing services and asset-based solutions in niche

segments through turnkey projects for mission critical systems. NOVEM has also been

expanding its service presence in international markets offering off shoring

advantages and delivering value through service level-based and project scope-based

deliveries. Since its inception on March 2004, 2004, NOVEM has been a frontrunner in

providing IT solutions and services.

NOVEM continues to bring the benefits of IT to improve the productivity of its

customers globally and enhance the quality of its products and services by combining

its wide range of service offerings with its deep vertical experience in multiple

industries. NOVEM mission is to deliver turnkey solutions to solve complex business

and societal problems using technology & innovation.

Today, NOVEM CONTROLS, an ISO 9001:2000 certified organization, is positioned as

a premier IT solutions provider in the fast growing and competitive IT market. It

executes large and complex turnkey projects, and has built, managed and

supported its customer's IT systems across the value chain of infrastructure,

applications and business processes.

NOVEM Controls a software company is managed by a team of dedicated, committed

and highly qualified software & hardware professional in the fields of Software,

Hardware and Web Technologies.

One of the areas of our specializations is Project study, analysis, development and its live

implementation. Our Engineers has hands-on experience in software development and has

a proven track record in training and guiding the students.


ABSTRACT
This project aims to brings the fun and simplicity of snake game with some feature .It
will include computer controlled intelligent other whose aims will be to challenge the
human players. It is single player game .It is interesting game for all the players .It is
oldest game but most famous game in our childhood.

This project explore a new dimension in the tradition snake game to make it more
interesting and challenging. The simplicity of this game makes it an idea candidate for a
minor project as we can focus on simple topics like simple functionality and
implementation of computer controlled intelligent opponent.

ACKNOWLEDGEMENT
Acknowledgement is an endless ocean and one requires the satisfying, supporting,

guiding, inspiring and constructively criticizing several specialists in order to drive out

a handful pearls from its depth. As this comes wordlessly it can’t be acknowledged in

words. I am greatly obliged to NOVEM CONTROLS PVT. LTD. institute for providing me

this opportunity to take up this project as long as platform to learn and enhance my

professional skill. I would like to express my deep sense of gratitude to MR. CHURAMANI

SHARMA, my corporate guide, for his kind help and support and valuable guidance

throughout the project. I am thankful to him for providing me with necessary insights

and helping me out at every single step.

MUKESH KUMAR

BCA (BACHELER OF COMPUTER APPLICATIONS)


ROLL NO: 2133116

TABLE OF CONTENTS
Contents

Chapter 1: Introduction
Java Intro

Java Features

Java Syntax

Java Output

Java User Input

Java Comments

Java Variables

Java Data Types

Java Type Casting

Java Operators

Java Strings

Java Math & Java Booleans

Java Conditional Statements

Java Switch Statement

Java Loops

Java Break/Continue

Java Arrays

Java Methods

Java Method Parameters

Java Method Overloading

Java Scope

Java OOP

Java Classes/Objects

Java Class Methods


Java Constructors

Java Encapsulation

Java Inheritance

Java Polymorphism

Java Abstraction

Chapter 2: Training Work Undertaken


2.1 Introduction to Project: Snake Game

2.2 Game Concept

2.3 Key Features

2,4 source code of game

Chapter 3: Results and Discussions


3 Results
3 Discussion about the
Game

Conclusion
References

CHAPTER 1
INTRODUCTION

1. Java Intro -Java is a programming language created by James Gosling from Sun
Microsystems (Sun) in 1991. The target of Java is to write a program once and

then run this program on multiple operating systems. The first publically

available
version of Java (Java 1.0) was released in 1995. Sun Microsystems was acquired

by the Oracle Corporation in 2010. Oracle has now the stearmanship of Java.

More than billion devices run Java. Java is defined by a specification and

consists of programming language, a compiler, core libraries and runtime (Java

virtual machine). The Java runtime allows software developers to write

program code in other languages than the Java programming language which

still runs on the Java virtual machine. The Java platform is usually associated

with the Java virtual machine and the Java core libraries.

1.2 JAVA FEATURES:

Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)

It is one of the most popular programming language in the world

It has a large demand in the current job market

It is easy to learn and simple to use

It is open-source and free

It is secure, fast and powerful

It has a huge community support (tens of millions of developers)

Java is an object oriented language which gives a clear structure to programs and

allows code to be reused, lowering development costs

As Java is close to C and C#, it makes it easy for programmers to switch to Java.

1.3 JAVA SYNTAX:


1.3 JAVA SYNTAX:

Main.java
public class Main{
public static void main(String[] args) {
System.out.println("Hello World")
}
}
In the above example, we created a lava file called Main.java, and we used the
above code to print "Hello World" to the screen.
Example explained
Every line of code that runs in Javu must be inside a class. In our example, we
named theclass Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning

The name of the java file must match the class name. When saving the file, save it
using the class name and add "java" to the end of the filename. The output
should be: Hello World

The main Method


The main() method is required and you will see it in every Java program. Any code

inside the main() method will be executed.

System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen

Note: The curly braces {} marks the beginning and the end of a block of code.

System is a built-in Java class that contains useful members, such as out, which is short
for "output". The println() method, short for "print line", is used to print a value to the

screen (or a file).

1.4 JAVA OUTPUT/PRINT:


Print Text
We can use the println() method to output values or print text in Java:

System.out.println(“Hello World”);
We can add as many println() methods as you want. It will add new line for each method.

Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "".If

you forget the double quotes, an error occurs:


System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);

The Print() Method


There is also a print() method, which is similar to println(). The only difference is that it

does not insert a new line at the end of the output.

Print Numbers
You can also use the println() method to print numbers. However, unlike text, we

don't put numbers inside double quotes:


System.out.println(3);

You can also perform mathematical calculations inside the println() method:
System.out.println(3+3);

1.4 JAVA USER INPUT: The Scanner class is used to get user input, and it is
found in the java.util package. To use the Scanner class, create an object of the

class and use any of the available methods found in the Scanner class

documentation. In our example, we will use the nextLine() method, which is

used to read Strings:

Example: Import Java.Util.Scanner; //Import Scanner Class

class Main{

public static void main(String[] args){

Scanner myObj= new Scanner(System.in); //Create Scanner object

System.out.println(“Enter username: “);

String username=myObj.nextline(); //Read user input

System.out.println(“Username is “+username); //output user input

1.6 JAVA COMMENTS: Comments can be used to explain Java code, and to make it
more readable. It can also be used to prevent execution when testing alternative code.

Single-line Comments: Single-line comments start with two forward slashes


(//).Any text between // and the end of the line is ignored by Java (will not be

executed).

Java Multi-line Comments: Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

1.7 JAVA VARIABLES: Variables are containers for storing data values. In Java,
there are different types of variables, for example:

String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes

boolean - stores values with two states: true or false

Declaring (Creating) Variables: To create a variable, you must specify the type and assign

it a value:

Syntax: type variableName=value;

Where type is one of Java's types (such as int or String), and variableName is the name of the

variable (such as x or name). The equal sign(=) is used to assign values to the variable.

Example:
Int myNum;

myNum=15;

System.out.println(myNum);

Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword
(this will declare the variable as "final" or "constant", which means
unchangeable and readonly).

Example: final int myNum=12;

myNum=15; //will generate error as we declare variable name with final keyword

Other Types: A demonstration of how to declare variables of other types:

Int myNum=5;

Float myFloatNum=5.99f;

Char myLetter=’D’;

Boolean myBool=true;

String myText=”Hello”;

Display Variables: The println() method is often used to display variables. To combine
both text and a variable, use the + character:

Example: String name=”Kashish”;

System.out.println(name+” Sharma”);

For numeric values, the + character works as a mathematical operator (notice

that we use int (integer) variables here):

Example: int x=9, y=10;

System.out.println(x+y); //Print value of x+y

One Value to Multiple Variables: You can also assign the same value to
multiple variables in one line:

Example: int x, y, z;

x=y=z=50;

System.out.println(x+y+z);

Identifiers: All Java variables must be identified with unique names. These
unique names are called identifiers. Identifiers can be short names (like x and y)

or more descriptive names (age, sum, totalVolume).


Note: It is recommended to use descriptive names in order to create understandable

and maintainable code:

Example: int minutesPerHour=60; //Good

int m=60; //it is Ok, but it is not easy to understand what “m” actually means
The general rules for naming variables are:

• Names can contain letters, digits, underscores, and dollar signs.


• Names must begin with a letter.
• Names should start with a lowercase letter and it cannot contain whitespace.
• Names can also begin with $ and _
• Names are case sensitive ("myVar" and "myvar" are different variables).
• Reserved words (like Java keywords, such as int or boolean) cannot be used as
names.

1.8 JAVA DATA TYPES: Data types are divided into two groups:
• Primitive data types - includes byte, short, int, long, float, double, boolean and
char
• Non-primitive data types - such as String, Arrays and Classes.
Numbers: Primitive number types are divided into two groups: Integer types stores whole
numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte,

short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or

more decimals. There are two types: float and double.

Integer Types
Byte: The byte data type can store whole numbers from -128 to 127. This can be used

instead of int or other integer types to save memory when you are certain that the value

will be within -128 and 127.

Short: The short data type can store whole numbers from -32768 to 32767.

Int: The int data type can store whole numbers from -2147483648 to 2147483647.

In general, and in our tutorial, the int data type is the preferred data type when we

create variables with a numeric value.

Long: The long data type can store whole numbers from -9223372036854775808 to

9223372036854775807. This is used when int is not large enough to store the value.

Note that you should end the value with an "L".

Floating Point Types


You should use a floating point type whenever you need a number with a decimal, such

as 9.99 or 3.14515. The float and double data types can store fractional numbers. Note

that you should end the value with an "f" for floats and "d" for doubles.

Scientific Numbers:
Boolean Types: Very often in programming, you will need a data type that can only

have one of two values, like:

• YES / NO
• ON / OFF
• TRUE / FALSE

For this, Java has a boolean data type, which can only take the values true or false.

Characters: The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c'

Strings: The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes.

Non-Primitive Data Types: Non-primitive data types are called reference


types because they refer to objects. The main difference between primitive and
nonprimitive data types are:

• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java .
• Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts
with an uppercase letter.

Examples of non-primitive types are Strings, Arrays, Interfaces, etc.

1.9 JAVA TYPE CASTING: Type casting is when you assign a value of one primitive
data type to another type. In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size


type double -> float -> long -> int -> char -> short -> byte

1.10 JAVA OPERATORS: Operators are used to perform operations on variables and
values. In the example below, we use the + operator to add together two values:

Example: int x=100+50;


Java divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
1. Arithmetic Operators: Arithmetic operators are used to perform common
mathematical operations. Example: +, -, *, /, %, ++, --
2. Assignment Operators: Assignment operators are used to assign values to variables.
Example: =, +=, - =, *=, /=, %=, &=, |=, >>=, <<=
3. Comparison Operators: Comparison operators are used to compare two values (or
variables). This is important in programming, because it helps us to find answers and
make decisions. The return value of a comparison is either true or false. These values
are known as Boolean values. Example: ==, !=, >, <, >=, <=
4. Logical Operators: You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values.
Example: &&, ||, !

1.11 JAVA STRINGS: Strings are used for storing text. A String variable contains a
collection of characters surrounded by double quotes.

Example: String greeting=”Hello”;

String Length: A String in Java is actually an object, which contain methods that can
perform certain operations on strings. For example, the length of a string can be found

with the length() method.

Example: String txt=”Good Morning”;

System.out.println(“The length of text String is: “+ txt.length());

More String Methods: There are many string methods available, for example

toUpperCase() and toLowerCase()

Finding a Character in a String: The indexof() method returns the index (the
position) of the first occurrence of a specified text in a string (including whitespace).

String Concatenation: The + operator can be used between strings to combine them.
This is called concatenation. You can also use the concat() method to concatenate two

strings

1.12 JAVA MATH & BOOLEANS: The Java Math class has many methods that
allows you to perform mathematical tasks on numbers.

Math.max(x,y): The Math.max(x,y) method can be used to find the highest

value of x and y:
Example: Math.max(5,10);

Math.min(x,y): The Math.min(x,y) method can be used to find the lowest value of x and y:

Example: Math.min(5,10);

Math.sqrt(x): The Math.sqrt(x) method returns the square root of x:

Example: Math.sqrt(25);

Java Booleans: Very often, in programming, you will need a data type that can only
have one of two values, like:

• YES / NO
• ON / OFF
• TRUE / FALSE

For this, Java has a boolean data type, which can store true or false values.

Boolean Values: A boolean type is declared with the boolean keyword and can only
take the

values true or false:

Boolean Expression: A Boolean expression returns a boolean value: true or false.

This is useful to build logic, and find answers. For example, you can use a

comparison operator, such as the greater than (>) operator, to find out if an

expression (or a variable) is true or false. Example: int x=10, y=9;

System.out.println(x>y);

1.13 JAVA CONDITIONAL STATEMENTS: Java has the following


conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed.

The if Statement: Use the if statement to specify a block of Java code to be

executed if a condition is true.

Syntax: if(condition) { Example: if(20>18){

// block of code to execute System.out.println(“20 is greater than 18”)

}}

The else Statement: Use the else statement to specify a block of code to be executed if

the condition is false.


Syntax: if(condition){ Example: int time=20;

//block of code if(time<18){

} else{ //block of code System.out.println(“Good Day”);

} else{

} System.out.println(“Good Evening”); }

The else if Statement: Use the else if statement to specify a new condition if the first

condition is false.

Syntax: if(condition 1){ Example: int time=30;

//block of code if(time<10){

} else if(condition 2){ System.out.println(“Good Morning);

// block of code else if(time<20){

} else{ System.out.println(“Good Afternoon);

//block of code else{

} System.out.println(“Good evening”); }

Short Hand If...Else: There is also a short-hand if else, which is known as the ternary

operator because it consists of three operands. It can be used to replace multiple lines of code

with a single line, and is most often used to replace simple if else statements:

Syntax: variable=(condition) ? expressionTrue : expressionFalse;

Example: int time=20;

String result=(time<18) ? “Good morning” : “Good evening” ;

System.out.println(result);

1.14 JAVA SWITCH STATEMENTS: Instead of writing many if else statements,


you can use the switch statement. The switch statement selects one of many code

blocks to be executed:

Syntax: switch (expression) {

case x:

//code block

break;

case y:

//code block
break;

default:

//code block

This is how it works:

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each
case.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional.
Example:

int day = 4;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");
break;

The default Keyword: The default keyword specifies some code to run if there is no
case match

1.15 JAVA LOOPS: Loops can execute a block of code as long as a specified condition
is reached. Loops are handy because they save time, reduce errors, and they make code

more readable.

Java While Loop: The while loop loops through a block of code as long as a

specified condition is true.

Syntax: while (condition) {

// code block

Example: int i=0;

while (i<5) {

System.out.println(i);

i++; }

Java For Loop: When you know exactly how many times you want to loop through a

block of code, use the for loop instead of a while loop.

Syntax: for (statement 1,; statement 2; statement 3) {

// code block

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

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

System.out.println(i);

Nested Loops: It is also possible to place a loop inside another loop. This is called a nested

loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

For-Each Loop: There is also a "for-each" loop, which is used exclusively to loop

through elements in an array


Syntax: for (type variable_name: array_name) {

// code block

Example: String[] cars= {“Volvo”, “Audi”, “Ford”};

for (String i: cars) {

System.out.println(i);

1.16 JAVA BREAK/CONTINUE:


Java Break: The break statement is used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

Example: for(int i=0; i<10; i++) {

if (i==4) {

break;

System.out.println(i);

Java Continue: The continue statement breaks one iteration (in the loop), if a

specified condition occurs, and continues with the next iteration in the loop.

Example: for (int i=0; i<10; i++)

if (i==4) {

continue;

System.out.println(i);

1.17 JAVA ARRAYS: Arrays are used to store multiple values in a single variable,

instead of declaring separate variables for each value. To declare an array, define the

variable type with square brackets.

To create an array of integers, you could write:

int[] myNum= {10, 20, 30, 40};

To create an array of strings:

String[] cars={“Volvo”, “Audi”, “Swift”};


Access the Elements of an Array: You can access an array element by referring to

the index number. This statement accesses the value of the first element in cars.

Example: String[] cars={“Volvo”, “Audi”, “Swift”};

System.out.println(cars[0]);

Change an Array Element: To change the value of a specific element, refer to the

index number.

Example: String[] cars={“Volvo”, “Audi”, “Swift”};

cars[0]=”Swift”;

System.out.println(cars[0]);

Array Length: To find out how many elements an array has, use the length property.

Example: String[] cars={“Volvo”, “Audi”, “Swift”};

System.out.println(cars.length);

Loop Through an Array: You can loop through the array elements with the for loop,

and use the length property to specify how many times the loop should run.

Example: String[] cars={“Volvo”, “Audi”, “Swift”};

for(int i=0; i<cars.length; i++) {

System.out.println(cars.length);

Loop Through an Array with For-Each: There is also a "for-each" loop, which is

used exclusively to loop through elements in arrays.

Example: String[] cars={“Volvo”, “Audi”, “Swift”};

for(String i: cars) {

System.out.println(i);

Multidimensional Arrays: A multidimensional array is an array of arrays.

Multidimensional arrays are useful when you want to store data as a tabular form,

like a table with rows and columns. To create a two-dimensional array, add each array

within its own set of curly braces.

Example: int[][] myNumbers={{1,2,3,4},{5,6,7,8}};

Access Elements: To access the elements of the myNumbers array, specify two indexes: one

for the array, and one for the element inside that array.
Example: int[][] myNumbers={{1,2,3,4},{5,6,7,8}};

System.out.println(myNumbers[1][2]);

Change Element Values: You can also change the value of an element.

Example: int[][] myNumbers={{1,2,3,4},{5,6,7,8}};

myNumbers[1][2]=9;

System.out.println(myNumbers[1][2]);

Loop Through a Multi-Dimensional Array: We can also use a for loop inside another for

loop to get the elements of a two-dimensional array (we still have to point to the

two indexes)

Example: public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

for(int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

1.18 JAVA METHODS: A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method: A method must be declared within a class. It is defined with the name of the

method, followed by parentheses (). Java provides some pre-defined methods, such as

System.out.println(), but you can also create your own methods to perform certain actions

Example: public class Main {

static void myMethod() {

// code to be executed

}
Call a Method: To call a method in Java, write the method's name followed by two

parentheses () and a semicolon;

1.19 METHOD PARAMETERS:

Parameters and Arguments: Information can be passed to methods as parameter.

Parameters act as variables inside the method. Parameters are specified after the

method name, inside the parentheses. You can add as many parameters as you want,

just separate them with a comma.

The following example has a method that takes a String called fname as parameter.

When the method is called, we pass along a first name, which is used inside the method

to print the full name:

public class Main {

static void myMethod(String fname)

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

NOTE: When a parameter is passed to the method, it is called an argument. So, from the

example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters: You can have as many parameters.

Note: when you are working with multiple parameters, the method call must have the

same number of arguments as there are parameters, and the arguments must be passed

in the same order.

Return Values: The void keyword, used in the examples above, indicates that the

method should not return a value. If you want the method to return a value, you can

use a primitive data type (such as int, char, etc.) instead of void, and use the return

keyword inside the method

Example: public class Main {


static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

System.out.println(myMethod(5, 3));

} // Outputs 8 (5 + 3)

1.20 JAVA METHOD OVERLOADING: With method overloading, multiple


methods can have the same name with different parameters.

Example: static int plusMethod(int x, int y) {

return x + y;

static double plusMethod(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

1.21 JAVA SCOPE: In Java, variables are only accessible inside the region they are
created. This is called scope.

Method Scope: Variables declared directly inside a method are available anywhere in the

method

Block Scope: A block of code refers to all of the code between curly braces {}. Variables

declared inside blocks of code are only accessible by the code between the curly braces,

which follows the line in which the variable was declared.

1.22 JAVA OOP: OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or methods that perform operations on
the data, while object-oriented programming is about creating objects that contain both

data and methods. Object-oriented programming has several advantages over

procedural programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and
shorter development time

1.23 JAVA CLASSES/OBJECTS: Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes

and methods. For example: in real life, a car is an object. The car has attributes, such

as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class: To create a class, use the keyword class:

Example: public class Main {

int x = 5;

Create an Object
In Java, an object is created from a class. We have already created the class named

Main, so now we can use this to create objects. To create an object of Main, specify the

class name, followed by the object name, and use the keyword new:

Example: public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Java Class Attributes: In the previous example, we used the term "variable" for x in
the example (as shown below). It is actually an attribute of the class. Or you could say

that class attributes are variables within a class:


Example: public class Main {

int x = 5;

int y = 3;

NOTE: Another term for class attributes is fields.

Accessing Attributes: You can access attributes by creating an object of the class,

and by using the dot syntax (.)

Modify Attributes: You can also modify attribute values or override the existing values:

Example: Set the value of x to 40:

public class Main {

int x=10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

1.24 JAVA CLASS METHODS: Methods are declared within a class, and that they

are used to perform certain actions.

Example: public class Main {

static void myMethod() {

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

} public static void main(String[]


args) { myMethod(); }

Static vs.
Public :You will often see Java programs that have either static or public attributes and

methods. In the example above, we created a static method, which means that it can be

accessed without creating an object of the class, unlike public, which can only be

accessed by objects.
1.25 JAVA CONSTRUCTORS: A constructor in Java is a special method that is used to

initialize objects. The constructor is called when an object of a class is created. It can be

used to set initial values for object attributes.

Example: public class Main { //Create Main class

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main

//(This will call the constructor)

System.out.println(myObj.x); // Print the value of x

} // Outputs 5

Note: Constructor name must match the class name, and it cannot have a return type

(like void). Also note that the constructor is called when the object is created. All classes

have constructors by default: if you do not create a class constructor yourself, Java

creates one for you. However, then you are not able to set initial values for object

attributes.

Constructor Parameters: Constructors can also take parameters, which is used to

initialize attributes. The following example adds an int y parameter to the

constructor. Inside the constructor we set x to y (x=y). When we call the constructor,

we pass a parameter to the constructor (5), which will set the value of x to 5:

Example: public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);


System.out.println(myObj.x);

} // Outputs 5

1.26 JAVA ENCAPSULATION: The meaning of Encapsulation , is to make sure

that "sensitive" data is hidden from users. To achieve this, you must:

• declare class variables/attributes as private


• provide public get and set methods to access and update the value
of a private variable

Get and Set: private variables can only be accessed within the same class (an outside class

has no access to it). However, it is possible to access them if we provide

public get and set methods. The get method returns the variable value, and the set method

sets the value. Syntax for both is that they start with either get or set, followed by the

name of the variable, with the first letter in upper case.

Why Encapsulation ?

• Better control of class attributes and methods


• Class attributes can be made read-only (if you only use the get method), or
writeonly (if you only use the set method)
• Flexible: the programmer can change one part of the code without affecting
other parts
• Increased security of data

1.27 JAVA INHERITANCE: In Java, it is possible to inherit attributes and methods


from one class to another. We group the "inheritance concept" into two categories:

• subclass (child) - the class that inherits from another


class
• superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword. In the example below, the Car

class (subclass) inherits the attributes and methods from the Vehicle class

(superclass) Why And When To Use "Inheritance"?

It is useful for code reusability: reuse attributes and methods of an existing class
when you

create a new class.

Example: class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method


System.out.println("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

Car myCar = new Car(); // Create a myCar object

// Call the honk() method (from the Vehicle class) on the myCar

object myCar.honk();

/* Display the value of the brand attribute (from the Vehicleclass) and the value of the

modelName from the Car class*/

System.out.println(myCar.brand + " " + myCar.modelName);

The final Keyword: If you don't want other classes to inherit from a class,

use the final keyword.

1.28 JAVA POLYMORPHISM: Polymorphism means "many forms", and it occurs


when we have many classes that are related to each other by inheritance. Like we

specified in the previous topic; Inheritance lets us inherit attributes and methods from

another class. Polymorphism uses those methods to perform different tasks. This allows

us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound().

Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own

implementation of an animal sound (the pig oinks, and the cat meows, etc.)

Example: class Animal {

public void animalSound() {

System.out.println("The animal makes a sound");

class Pig extends Animal {


public void animalSound() {

System.out.println("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {

System.out.println("The dog says: bow wow");

}}

class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

Why And When To Use "Inheritance" and "Polymorphism"?

It is useful for code reusability: reuse attributes and methods of an existing class
when you

create a new class.

JAVA ABSTRACTION: Data abstraction is the process of hiding certain details


and showing only essential information to the user.

Abstraction can be achieved with either abstract classes or interfaces

The abstract keyword is a non-access modifier, used for classes and methods:

• Abstract class: is a restricted class that cannot be used to create objects (to access it,
• it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

Example: abstract class Animal { // Abstract class


// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

CHAPTER 2
TRAINING WORK UNDERTAKEN
INTRODUCTION TO PROJECT:SNAKE GAME
The history of the snake game goes back to the 1970s when the game took that we will be
using. It was sold under numerous names and many platforms but probably gained widespread
recognition when it was shipped as standard on Nokia mobile phones in the 1990s.

GAME
CONCEPT :The game involve controlling a single block or snakehead by turning only left
,right, up and down you manage to eat enemy .When you get the enemy ,the snake grows
an extra block or body segment.

If ,or rather when , the snake bumps into the edge of the screen or accidentally eats
himself the game is over .the more enemys the snake eats the higher the score.
KEY FEATURES:

• Use the left, right , up and down keys to give direction to the
snake.
• The current score and lengths are displayed .
• If the snake hits its own body, it dies.
• Food is placed at random positions every time.

Sources code of snake game


package snakegame;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.Random;

import javax.swing.ImageIcon;

import javax.swing.JPanel;

import javax.swing.Timer;

public class GamePanel extends JPanel implements ActionListener, KeyListener{

private int[] snakexlength=new int[750];

private int[] snakeylength=new int[750];

private int lengthOFSnake=3;

privateint[]xPos={25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,4
75,50 0,525,550,575,600,625,650,675,700,725,750,775,800,825,850};

privateint[]yPos={75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,50
0,525, 550,575,600,625};
private Random random=new Random();

private int enemyX,enemyY;

private boolean left=false;

private boolean right=true;

private boolean up=false;

private boolean down=false;

private int moves=0;

private int score=0;

private boolean gameOver=false;

private ImageIcon snaketitle=new

ImageIcon(getClass().getResource("snaketitle.jpg")); private ImageIcon

leftmouth=new ImageIcon(getClass().getResource("leftmouth.png")); private

ImageIcon rightmouth=new ImageIcon(getClass().getResource("rightmouth.png"));

private ImageIcon upmouth=new ImageIcon(getClass().getResource("upmouth.png"));

private ImageIcon downmouth=new

ImageIcon(getClass().getResource("downmouth.png")); private ImageIcon

snakeimage=new ImageIcon(getClass().getResource("snakeimage.png")); private

ImageIcon
private enemy=new
Timer timer; ImageIcon(getClass().getResource("enemy.png"));

private int delay=100;

GamePanel(){

addKeyListener(this);

setFocusable(true);

setFocusTraversalKeysEnabled(true);

timer=new Timer(delay,this);

timer.start();
newEnemy();

@Override

public void paint(Graphics g) {

super.paint(g); // Generated from


nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/OverriddenMethodBody

g.setColor(Color.WHITE);

g.drawRect(24, 10,851 , 55);

g.drawRect(24, 74, 851, 576);

snaketitle.paintIcon(this,g,25,11);

g.setColor(Color.BLACK);

g.fillRect(25, 75, 850, 575);

if (moves==0){

snakexlength[0]=100;

snakexlength[1]=75;

snakexlength[2]=50;

snakeylength[0]=100;

snakeylength[1]=100;

snakeylength[2]=100;

if(left){

leftmouth.paintIcon(this,g,snakexlength[0],snakeylength[0]);

if(right){

rightmouth.paintIcon(this,g,snakexlength[0],snakeylength[0]);

if(up){
upmouth.paintIcon(this,g,snakexlength[0],snakeylength[0]);

if(down){

downmouth.paintIcon(this,g,snakexlength[0],snakeylength[0]);

for(int i=1;i<lengthOFSnake;i++){

snakeimage.paintIcon(this, g,snakexlength[i],snakeylength[i] );

enemy.paintIcon(this, g, enemyX, enemyY);

if(gameOver){

g.setColor(Color.WHITE);

g.setFont(new Font("Arial",Font.BOLD,50));

g.drawString("Game Over",300, 300);

g.setFont(new Font("Arial",Font.PLAIN,20));

g.drawString("Press SPACE to Restart",320, 350);

g.setColor(Color.WHITE);

g.setFont(new Font("Arial",Font.PLAIN,14));

g.drawString("Score:"+score,750, 30);

g.drawString("Length :"+lengthOFSnake, 750, 50);

g.dispose();

@Override

public void actionPerformed(ActionEvent e) {

for(int i=lengthOFSnake-1;i>0;i--){

snakexlength[i]=snakexlength[i-1];

snakeylength[i]=snakeylength[i-1];

}
if(left){

snakexlength[0]=snakexlength[0]-25;

if(right){

snakexlength[0]=snakexlength[0]+25;

if(up){

snakeylength[0]=snakeylength[0]-25;

if(down){

snakeylength[0]=snakeylength[0]+25;

if(snakexlength[0]>850)snakexlength[0]=25;

if(snakexlength[0]<25)snakexlength[0]=850;

if(snakeylength[0]>625)snakeylength[0]=75;

if(snakeylength[0]<75)snakeylength[0]=625;

collidesWithEnemy();

collidesWithBody();

repaint();

@Override

public void keyPressed(KeyEvent e) {

if(e.getKeyCode()==KeyEvent.VK_SPACE){
restart();

if(e.getKeyCode()==KeyEvent.VK_LEFT && (!right)){

left=true;

right=false;

up=false;

down=false;

moves++;

if(e.getKeyCode()==KeyEvent.VK_RIGHT && (!left)){

left=false;

right=true;

up=false;

down=false;

moves++;

if(e.getKeyCode()==KeyEvent.VK_UP && (!down)){

left=false;

right=false;

up=true;

down=false;

moves++;

if(e.getKeyCode()==KeyEvent.VK_DOWN && (!up)){

left=false;

right=false;

up=false;

down=true;

moves++;

}
if(e.getKeyCode()==KeyEvent.VK_LEFT){

left=true;

right=false;

up=false;

down=false;

moves++;

@Override

public void keyReleased(KeyEvent e) {

@Override

public void keyTyped(KeyEvent e) {

private void newEnemy() {

enemyX=xPos[random.nextInt(34)];

enemyY=yPos[random.nextInt(23)];

for(int i=lengthOFSnake-1;i>=0;i--){

if(snakexlength[i]==enemyX && snakeylength[i]==enemyY){

newEnemy();

private void collidesWithEnemy(){

if(snakexlength[0]==enemyX && snakeylength[0]==enemyY){

newEnemy();
lengthOFSnake++;

score++;

private void collidesWithBody(){

for(int i=lengthOFSnake-1;i>0;i--){

if(snakexlength[i]==snakexlength[0] && snakeylength[i]==snakeylength[0]){

timer.stop();

gameOver=true;

private void restart(){

gameOver=false;

moves=0;

score=0;

lengthOFSnake=3;

left=false;

right=true;

up=false;

down=false;

timer.start();

repaint();

Output

CHAPTER 3
RESULTS AND DISCCUSSIONS
RESULTS:
Snapshots of result of Game application:
Fig1
Fig2

DISCUSSIONS: The snake game is a timeless classic that holds a special place in the
hearts of gamers. Its straightforward gameplay and simple controls make it easy to
pick up and play, appealing to players of all ages and skill levels. The objective of
enemy to eats the snake grows the extra length and score one by one and if hit snake
body the game over.

One of the game's strengths lies in its strategic elements. Players must carefully

position the enemy and eats enemy to maximize the number of lengths and

score. The use of Java as the development platform allows the game to be highly

accessible, running on various devices without compatibility issues. Java's

graphical capabilities and event handling ensure a smooth and immersive

gaming experience.
CONCLUSION
The snake game in Java showcases the versatility of Java's core features in creating an engaging

and entertaining gaming experience. Its simple yet addictive gameplay, combined with dynamic

graphics, provides an immersive experience for players. The game's potential for strategic

decision-making and increasing difficulty keeps players challenged and motivated. With some

additional enhancements and features, the snake game has the potential to become an even

more captivating and popular gaming choice among players. It offers an enjoyable blend of

simplicity, nostalgia, and strategic gameplay. Its timeless appeal, combined with Java's

capabilities, makes it a fun and accessible option for players seeking a classic arcade adventure.

With its potential for enhancements, the snake game can continue to captivate players and

provide hours of entertainment and satisfaction.

REFERENCES:

https://www.w3schools.com/

https://www.javatpoint.com/

https://youtube.videos.com/

Book: Head First Java by Kathy Sierra & Bert Bates

You might also like