0% found this document useful (0 votes)
39 views43 pages

Ashish Sain Its Final Java Report (1) Roll No 10

This Industrial Training Report on Java Core was submitted by Ashish Sain in partial fulfillment of a Bachelor of Technology degree in Computer Science & Engineering. The report covers the history, features, and programming fundamentals of Java, emphasizing its platform independence, object-oriented nature, and robust security. It also includes acknowledgments, an abstract, and a detailed table of contents outlining various chapters related to Java programming concepts.
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)
39 views43 pages

Ashish Sain Its Final Java Report (1) Roll No 10

This Industrial Training Report on Java Core was submitted by Ashish Sain in partial fulfillment of a Bachelor of Technology degree in Computer Science & Engineering. The report covers the history, features, and programming fundamentals of Java, emphasizing its platform independence, object-oriented nature, and robust security. It also includes acknowledgments, an abstract, and a detailed table of contents outlining various chapters related to Java programming concepts.
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/ 43

An

Industrial Training Report


on
Java core
Submitted in partial fulfillment for the award of degree of
Bachelor of Technology

In

Computer Science & Engineering

Submitted to: Submitted By:


Dr. Pradeep Jha Name : Ashish Sain
HOD-CSE/IT/AI&DS Dept. 23EGJAD010

Department of Computer Science & Engineering


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

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

Ashish Sain
23EGJAD010
B. Tech III semester, II Year, AI & DS

ii
Abstract

Java is a high-level, object-oriented, platform-independent programming language designed for


simplicity, versatility, and reliability. It was developed by Sun Microsystems in 1995 and is now
maintained by Oracle Corporation. Java's key feature is its "Write Once, Run Anywhere" (WORA)
philosophy, enabled by the Java Virtual Machine (JVM), which allows Java programs to run on any
platform without modification.

Key features of Java include:

• Object-Oriented: Java uses concepts like classes, objects, inheritance, encapsulation, and
polymorphism to model real-world problems effectively.

• Platform Independence: Java bytecode, generated after compilation, can run on any device
with a JVM.

• Robust and Secure: Built-in memory management, exception handling, and runtime checks
ensure robust and secure applications.

• Multi-threaded and Concurrent: Java supports multithreading for efficient resource


utilization.

• Rich API: A comprehensive standard library simplifies development for tasks like
networking, database access, GUI design, and more.

Java is widely used in developing web, mobile, and desktop applications, as well as in enterprise
systems, scientific computing, and IoT devices. Its simplicity, scalability, and extensive community
support make it a preferred language for developers across diverse domains.

iii
Table Of Content
Certificate .................................................................................................................................... i
Acknowledgement ...................................................................................................................... ii
Abstract………………………………………………………………………………………...iii
Table of Content .............................................................................................................................. iv

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

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

Chapter 1 - INTRODUCTION AND OBJECTIVE 1


1.1 History of Java ........................................................................................................................................... 1
1.2 An Introduction to Programming in Java.................................................................................................... 2
1.3 Why Use Java?........................................................................................................................................... 2
1.4 The goal of programming in Java ............................................................................................................... 2
1.4.1 Stage Freedom ................................................................................................................ 3
1.4.2 Security ........................................................................................................................... 3
1.4.3 Object-Arranged Programming ....................................................................................... 3
1.4.4 Performance.................................................................................................................... 3
1.4.5 Broad Libraries ................................................................................................................ 3
1.4.6 Multithreading ................................................................................................................ 3
1.4.7 Community Assistance .................................................................................................... 3
1.5 Features of Java ....................................................................................................................................... 4
1.6 Primary/Main Features of Java ................................................................................................................ 4
1.7 Some important terms in Java ................................................................................................................. 7
1.8 How to download the Java ?.................................................................................................................... 7
1.9 Install Java................................................................................................................................................ 8
1.10 Class Path ................................................................................................................................................ 8
1.11 Java Syntax .............................................................................................................................................. 9
1.12 Pascal case examples ............................................................................................................................... 9
1.13 Camel case examples............................................................................................................................. 10

Chapter 2 - Fundamentals of Java Programming 11


2.1 First Program of the Java ........................................................................................................................ 11
2.2 Variables................................................................................................................................................. 11
2.3 Parameter used in first java program ...................................................................................................... 11
2.4 Data Type ............................................................................................................................................... 12
2.5 Following are the size of the data type.................................................................................................... 13
2.6 Keyword ................................................................................................................................................. 13
2.7 Operator.................................................................................................................................................. 14

iv
CHAPTER 3 - Decision Making 16
3.1 Decision Making is Further Divided into two parts : .............................................................................. 16
3.2 Loop Statement....................................................................................................................................... 21
3.2.1 JAVA FOR-EACH LOOP.............................................................................................. 22
3.2.2 Java while loop.............................................................................................................. 23
3.2.3 Java do-while loop ........................................................................................................ 25

3.3 The flow chart of the do-while loop is given below : .............................................................................. 26
3.4 Jump Statements..................................................................................................................................... 26
3.4.1 Break Statement ......................................................................................................... 26
3.4.2 Continue Statement ..................................................................................................... 27
3.5 Java Comments ..................................................................................................................................... 28
3.6 For what reason do we involve Comments in a code? ........................................................................... 28
3.7 Array ..................................................................................................................................................... 28

CHAPTER 4 - OOPS CONCEPT IN JAVA 30


4.1 What are Strings in Java?....................................................................................................................... 30
4.2 Inheritance ............................................................................................................................................. 30
4.3 Polymorphism........................................................................................................................................ 30
4.4 Packages ................................................................................................................................................ 31
4.5 Math class .............................................................................................................................................. 31
4.6 Mini Project (Guess The Number ) ........................................................................................................ 31
4.7 Hangman Mini Project........................................................................................................................... 32

CHAPTER 5
* Conclusion .................................................................................................................... 35
* References ..................................................................................................................... 37

v
List of figures
Figure 1:- Features of Java ............................................................................................................................... 4
Figure 2 :-class path ......................................................................................................................................... 9
Figure 3 :-java syntax ....................................................................................................................................... 9
Figure 4 :-Data Type Diagram ........................................................................................................................ 12
Figure 5 :-Types OF Java Control Statements ................................................................................................ 15
Figure 6 :-For loop in Java \ ........................................................................................................................... 22
Figure 7 :-Java While Loop ............................................................................................................................ 25
Figure 8 :-Java do -while loop ........................................................................................................................ 26

vi
List of tables
Table 1 Size of data type ........................................................................................................ 13
Table 2 Keywords ................................................................................................................... 13
Table 3 operators ..................................................................................................................... 14

vii
Java Core / AI&DS

Chapter 1
INTRODUCTION AND OBJECTIVE
1.1 History of Java [1]
Java’s history is very interesting. It is a programming language createdin 1991. James
Gosling,Mike Sheridan, and Patrick Naughton,a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms. In 1997, Sun Microsystems approached the ISO standards body
and later formalized Java, but it soon withdrew from the process. At one time, Sun made
most of its Java implementations available without charge, despite their proprietary software
status. Sun generated revenue from Java through the selling of licenses for specialized
products such as the Java Enterprise System .

On November 13, 2006, Sun released much of its Java virtual machine as free, opensource
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.

The principles for creating java were simple, robust, secured, high-performance, portable,
multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by James Gosling
who is known as the Father of Java. Currently, Java is used in mobile devices, internet
programming, games, e-business, etc.

Session 2024 – 25 1
Java Core / AI&DS

1.2 An Introduction to Programming in Java [5]


Java is a generally utilized, flexible, and vigorous programming language that plays had a
critical impact in forming the cutting edge programming improvement scene. Java was
created in the middle of the 1990s by James Gosling and his team at Sun Microsystems,
which is now owned by Oracle Corporation. Its primary objective was to be platform-
independent and to provide a secure, efficient, and simple-to-maintain programming
environment. Throughout the long term, it has turned into a foundation of the product
business, controlling everything from portable applications and web administrations to big
business level applications and implanted frameworks.

The "Write Once, Run Anywhere" mantra of Java means that code written in Java can run on
any platform with a compatible Java Virtual Machine (JVM). This is why Java is so popular.
Java is widely used to create crossplatform applications that run seamlessly on a variety of
operating systems thanks to its platform independence. Additionally, Java is a preferred
language for developing software solutions that are scalable and easy to maintain thanks to its
emphasis on robust typing, automatic memory management, and extensive library and
framework support.

1.3 Why Use Java? [ 4]

Java is easy to learn for programmers. Most people pick Java as their first programming
language. Moreover, the popularity of Java still persists in the industry. Most of the
government, healthcare, defence, and education sector websites, and applications are still
using Java technologies. So, it is worth learning and using Java. If you see Java as a career
option then also it can take you to various career paths. Almost everything you can do using Java.

1.4 The goal of programming in Java [5]


The essential target of Java writing computer programs is to empower engineers to make top
caliber, convenient, and productive programming arrangements that meet an extensive variety
of utilization needs. Java provides a number of important objectives and benefits for
accomplishing this goal.

1.4.1 Stage Freedom


Java expects to separate stage explicit obstructions by permitting engineers to compose code
once and run it anyplace. As long as a JVM that is compatible is available, Java applications
will be able to run on a variety of platforms, including Linux, Windows, macOS, and
Session 2024 – 25 2
Java Core / AI&DS

embedded systems.

1.4.2 Security
By providing features like bytecode verification and a robust security model, Java places
security first. Because of this, e-commerce platforms and online banking systems that require
a high level of security can rely on it.

1.4.3 Object-Arranged Programming


Object-oriented programming principles, which encourage modular and organized code
structures, are promoted by Java. Reusability, extensibility, and maintenance are all made
easier by this.

1.4.4 Performance
Java is intended to offer cutthroat execution using Without a moment to spare (JIT)
gathering, productive memory the board, and streamlining procedures. This guarantees that Java
applications can effectively perform a wide range of computational tasks.

1.4.5 Broad Libraries


Java makes it easier for developers to quickly build applications with a lot of features thanks
to its extensive standard library and numerous third-party libraries and frameworks.

1.4.6 Multithreading
Java permits concurrent and responsive applications thanks to its support for multithreading.
When creating applications that can handle multiple tasks at once, this is especially helpful.

1.4.7 Community Assistance


Because Java has a large and active developer community, developers have access to
numerous tutorials, forums, and resources to help them with their programming projects.

1.5 Features of Java [2]


The primary objective of java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple

Session 2024 – 25 3
Java Core / AI&DS

2. Object-Oriented
3.Portable
4.Platform Independent
5.Secured
6.Interpreted
7.High Performance
8.Multithreaded
9.Distributed 10.Dynamic
11.Architectural Neutral

Figure 1 Features of Java

1.6 Primary/Main Features of Java [4]


1. Platform Independent
Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa. Each operating system has a different JVM, but the output produced by all the OS
is the same after the execution of the bytecode. That is why we call java a platform-
independent language.

2. Object-Oriented Programming Language


Organizing the program in the terms of a collection of objects is a way of object-oriented
programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
Abstraction Encapsulation
Inheritance Polymorphism
Session 2024 – 25 4
Java Core / AI&DS

3. Simple
Java is one of the simple languages as it does not have complex features like pointers,
operator overloading, multiple inheritances, and Explicit memory allocation.

4. Robust

Java language is robust which means reliable. It is developed in such a way that it puts a lot
of effort into checking errors as early as possible, that is why the java compiler is able to
detect even those errors that are not easy to

detect by another programming language. The main features of java that make it robust are
garbage collection, Exception Handling, and memory allocation.

5. Secure
In java, we don’t have pointers, so we cannot access out of bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws
like stack corruption or buffer overflow are impossible to exploit in Java. Also, java programs
run in an environment that is independent of the os(operating system) environment which
makes java programs more secure.

6. Distributed

We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications in
java. The java programs can be easily distributed on one or more systems that are connected
to each other through an internet connection.

7. Multithreading

Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of the CPU.

8. Portable

As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable

9. High Performance

Session 2024 – 25 5
Java Core / AI&DS

Java architecture is defined in such a way that it reduces overhead during the runtime and at
some times java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basics where it only compiles those methods that are called making applications to
execute faster.
10. Dynamic flexibility

Java being completely object-oriented gives us the flexibility to add classes, new methods to
existing classes, and even create new classes through sub-classes. Java even supports
functions written in other languages such as C, C++ which are referred to as native methods.

11. Sandbox Execution

Java programs run in a separate space that allows user to execute their applications without
affecting the underlying system with help of a bytecode verifier. Bytecode verifier also
provides additional security as its role is to check the code for any violation of access.

12. Write Once Run Anywhere

As discussed above java application generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary

reason java is used in the enterprising IT industry globally worldwide .

1.7 Some important terms in Java [3]


JDK: Java Development Kit ( It’s a collection of tools used for running and developing
Java Programs).

JRE: Java Runtime Environment (JRE helps in executing program developed in java).
JVM: Java Virtual Machine (A Java virtual machine (JVM) is a virtual machine that
enables a computer to run Java programs as well as programs written in other languages that
are also compiled to Java bytecode.

1.8 How to download the Java [8]

1.Determine Your Java Version Requirement: First, decide whether you want to download
Oracle JDK (Java Development Kit) or OpenJDK. OpenJDK is an open-source alternative to
Oracle JDK and is often recommended for most use cases.

Session 2024 – 25 6
Java Core / AI&DS

1. Visit the Official Java Website

For Oracle JDK: Visit the Oracle Java SE Downloads page at


https://www.oracle.com/java/technologies/javase-downloads.html

For OpenJDK: You can find the latest OpenJDK releases on the AdoptOpenJDK website

(https://adoptium.net/) or on the official OpenJDK website (https://openjdk.java.net/)

1. Accept the License Agreement (Oracle JDK Only): If you're downloading Oracle JDK,
you will need to accept the Oracle Technology Network License Agreement before
proceeding.

2. Select the Latest Version: Choose the latest Java version that you want to download.
Usually, you'll find a list of versions and platforms to select from.

3. Choose Your Platform: Select your operating system (e.g., Windows, macOS, Linux) and the
appropriate package (e.g., .exe for Windows, .dmg for macOS, .tar.gz for Linux).

4. Download the Installation File: Click on the download link for the selected version and
platform to start the download.

1.9 Install Java


For Oracle JDK: Run the downloaded installer and follow the on-screen instructions to install
Java on your system.

For OpenJDK: Extract the downloaded archive (if applicable) and set the JAVA_HOME
environment variable to point to the extracted directory. Additionally, you may need to add the
bin directory to your system's PATH variable to make Java commands accessible.

Verify Your Java Installation: After the installation is complete, open a command prompt or
terminal and run the following command to verify that Java is installed: java -version

This should display the installed Java version.

1. Set Environment Variables (Optional): Depending on your use case, you might need to set
additional environment variables, such as ‘PATH’ or ‘JAVA_HOME’, to ensure that Java is

Session 2024 – 25 7
Java Core / AI&DS

properly configured.

1.10 Class Path

The class path is the file path where the java runtime and Java compiler look for
.class files to load. By default, JDK provides many libraries. If you want to include
external libraries they should be added to the class path.

Figure 2 :class path

Java Syntax

Figure 3 java syntax

1.12 Pascal case examples


The below examples follow both camel case and Pascal case naming conventions:

1.OutOfMemoryException

2. DateFormat

3.DatabaseConnection

Session 2024 – 25 8
Java Core / AI&DS

4.LinkedList

5. EventHandler

Pascal case is always consistent with camel case rules. However, when a variable starts with
a lowercase letter, camel case is not consistent with Pascal case.

1.13 Camel case examples


The following camel case examples do not follow the Pascal case convention: 1.jenkinsServer
2. iterationCount
3.tomcatInstance

Session 2024 – 25 9
Java Core / AI&DS

Chapter 2
Fundamentals of Java Programming
2.1 First Program of the Java
Follwing is the Syntex of java which is commonly used :

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

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

Just like in grammer we have some rules in java programming also has some rules which is
known as Syntex.

2.2 Variables [3]

Variable is container that store a value . This value can be changed during the execution
of the program.
Example :

int number = 9;

Data type Variable name Value it Stores!

2.3 Parameter used in first java program [3]


let's see what is the meaning of class, public, static, void, main,
String[],System.out.println().
class keyword is used to declare a class in Java.
Public keyword is an access modifier that represents visibility. It means it is
visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The
core advantage of the static method is that there is no need to create an object to invoke the
static method. The main() method is executed by the JVM, so it doesn't require creating an
object to invoke the main() method. So, it saves memory.
Session 2024 – 25 10
Java Core / AI&DS

void is the return type of the method. It means it doesn't return any value.

main represents the starting point of the program.

String[] args or String args[] is used for command line argument. We will discuss it in
coming section. System.out.println() is used to print statement. Here, System is a class,
out is an object of the PrintStream class, println() is a method of the PrintStream class. We
will discuss the internal working of System.out.println() statement in the coming section.

2.4 Data Type [5]

Figure 4 Data Type Diagram

2.5 Following are the size of the data type

Session 2024 – 25 11
Java Core / AI&DS

2.6 Keyword [8]


Table 1 Size of data type
Java keyword are also known as reserved words .These are predefined words by java so they
cannot be used

as variable or object name or class name.

Table 2 Keywords

2.7 Operator [9]


The symbols that is used to perform some operations are called as Operators in java .

There are following some major operators which are as follows:-

Session 2024 – 25 12
Java Core / AI&DS

1.Unary Operator

2.Arithmetic Operator

3. Shift Operator

4. Relational Operator

5. Bitwise Operator

6. Logical Operator

7. Ternary Operator and


8.Assignment Operator

Table 3 operators

Session 2024 – 25 13
Java Core / AI&DS

Figure 5 Types OF Java Control Statements

Session 2024 – 25 14
Java Core / AI&DS

CHAPTER 3
Decision Making

3.1 Decision Making is Further Divided into two parts [1]


1. If Statements
2. Switch Statements

1. If Statements
SYNTEX

if(condition) { statement 1;
//executes when condition is true
}
(a) Simple If Statement

SYNTEX

if(condition) {

statement 1; //executes when condition is true


}
Example:
public class Students {
public static void main(String[] args) {
int x = 30; int y = 40; if(x+y
> 60) {
System.out.println("x + y is greater than 60");
}
}
Output : x+y is greater than 60

2. If-Else Statement
SYNTEX

if(condition) { statement 1;
//executes when condition is true
} else{ statement 2; //executes when
condition is false

Session 2024 – 25 15
Java Core / AI&DS

}
Example : public class Student {
public static void main(String[]
args)
{ int x = 50; int y = 30; if(x+y
< 10) {
System.out.println("x + y is less than 50");

} else {

System.out.println ( "x + y is greater than 60");

Output: x+y is greater then 60

3. If-Else-If Ladder [4]

SYNTEX

if(condition 1) { statement 1;
//executes when condition 1 is true
}
else if(condition 2) { statement 2;
//executes when condition 2 is true }
else { statement 2; //executes when all
the conditions are false }

Example public class Test { public


static void main(String args[]) {
int x = 30;

if( x == 10 ) {

System.out.print("Value of X is 10");

}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {

System.out.print("Value of X is 30");

Session 2024 – 25 16
Java Core / AI&DS

}else {

System.out.print("This is else statement");

Value of X is 30

4. Nested if-statement [4]


In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
Syntax of Nested if-statement is given below:- if(condition

1. { statement 1; //executes when condition 1


is true if(condition
2. { statement 2; //executes when condition 2 is
true
} else{

statement 2; //executes when condition 2 is false

Example:-
public class Country{

public static void main(String[] args) {

String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Karnataka")) {

System.out.println("Your city is Meerut");

}else if(address.contains("Noida")) {

System.out.println("Your city is Noida");

}else {

System.out.println(address.split(",")[0]);

}else {

System.out.println("You are not living in India");


}}

Session 2024 – 25 17
Java Core / AI&DS

Output: Delhi

5. Switch Statement[1]
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Points to be noted about switch statement:

1. The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of

2. Cases cannot be duplicate

3. Default statement is executed when any of the case doesn't match the value of expression.
It is optional.

4. Break statement terminates the switch block when the condition is satisfied.

5. It is optional, if not used, next case is executed.

6. While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The syntax to use the switch
statement is given below:-

SYNTEX switch
(expression){
case value1:
statement1;
break;
case valueN:
statementN;

break;
default:default
statement;
}
EXAMPLE
1. First, import the Scanner class (for user input), declare the class name, and declare the

main method:

2. Next, declare a Scanner variable and create the object. This object will retrieve user input

Session 2024 – 25 18
Java Core / AI&DS

later:

3. Declare a variable to store the user input:

4. Ask the user to enter a number:

5. Use the Scanner object to retrieve the user input. Note that the program will wait here until

the user type

value and presses Enter:

6. Create a switch statement that switches on the day Num variable:

7. Inside the switch statement, add cases for each day. For example, the value 1 will output

Monday:

Here are the other cases. Note that case 5 also outputs TGIF:

The last case is a default case. This case occurs when the dayNum value has a number outside
range 1-7:
import java.util.Scanner; public
class Days {
public static void main(String[] args)
{Scanner in = new Scanner(System.in);
int dayNum;
System.out.print("Enter a day number (1-7): ");
dayNum = in.nextInt(); switch(dayNum) {
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");
System.out.println("TGIF!");
break;
case 6:
Session 2024 – 25 19
Java Core / AI&DS

System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day number.");
break;
}
}
}

3.2 Loop Statement [1]


In programming, it may be necessary to continually run a block of code while a certain
condition is true. However, the set of instructions is carried out repeatedly using loop
statements. The fulfillment of the given set of instructions is contingent upon a certain
circumstance.
Three different loop types that execute similarly exist in Java. They differ in terms of syntax
condition checking time, though.
for loop
while loop

do-while loop

SYNTEX
for(initialization, condition, increment/decrement) {

//block of statements
}

The Flowchart of the “For Loop” are given below:-

Session 2024 – 25 20
Java Core / AI&DS

Calculation.java
Figure 6 For loop in Java \

1. public class Calculattion {

2. public static void main(String[] args) {

3. // TODO Auto-generated method stub

4. int sum = 0;

5. for(int j = 1; j<=10; j++) {

6. sum = sum + j;

7. }

8. System.out.println("The sum of first 10 natural numbers is " + sum);

9. }

10. }.

3.3.1 JAVA FOR-EACH LOOP

SYNTEX

for(data_type var : array_name/collection_name){ //statements


}
Calculation.java
1. public class Calculation {

Session 2024 – 25 21
Java Core / AI&DS

2. public static void main(String[] args) {


3. // TODO Auto-generated method stub

4. String[] names = {"Java","C","C++","Python","JavaScript"};

5. System.out.println("Printing the content of the array names:\n"); 6. for(String

name:names) {

3.3.2 Java while loop


Java While Loop is a control flow statement that allows repeated execution of code based on a
specific Boolean condition. A while loop can be thought of as a repeated if statement. The
while loop is used in Java when we need to execute a block of statements repeatedly. A while
loop is treated as a repeated if statement. If the number of iterations is not fixed, it is
recommended to use a while loop.
It starts with the for keyword, just like a normal for loop.

Instead of declaring and initializing a loop counter variable, declare a variable of the same type as
the followed by a colon and then the name of the array.

Within the loop body, you can use the loop variable you created instead of indexing the array
element.

It is typically used to iterate over Array or Collections classes (such as ArrayList).

SYNTEX: \
while(condition){

//STATEMENT
}
Session 2024 – 25 22
Java Core / AI&DS

1. Calculation .java

1. public class Calculation {

2. publicstatic void main(String[] args) {


3. // TODO Auto-generated method stub

4. int i = 0;

5. System.out.println("Printing the list of first 10 even numbers \n");

6. while(i<=10) {

7. System.out.println(i);

8.i = i + 2;

9.}

10.}

11. }

Output:

Printing the list of first


10 even numbers

0
2
4
6
8
10

The flow chart for the while


loop is given:-

Session 2024 – 25 23
Java Core / AI&DS

Figure 7 Java While Loop

3.3.3 Java do-while loop [3]


SYNTEX:-
do

//statements

} while (condition);

Calculation.java

public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

do {

System.out.println(i);

i = i + 2;

}while(i<=10);

Session 2024 – 25 24
Java Core / AI&DS

} 11.}

Output:

Printing the list of first 10


even numbers 0 2

The flow chart of the do-while loop is given below :-

3.5 Jump Statements

Session 2024 – 25 25
Java Core / AI&DS

Figure 8 Java do -while loop


To Transfer the control of execution of program from one part to another part of the program is
called the Jump Statements

3.5.1 Break Statement


Break Statement is a loop control statement that is used to terminate the loop.

SYNTEX:- break;

public class Calculation {


public static void
main(String[] args) { //
TODO Auto-generated method

stub a: for(int i =
0; i<= 10; i++) { b:
for(int j = 0; j<=15;j++) {
c: for (int k = 0; k<=20;
k++) {
System.out.println(k);
if(k==5) { break a;
} }
}
}
}
}
Output:
0 1 2 3 4 5

3.5.2 Continue Statement [2]


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the

specific part of the loop and jumps to the next iteration of the loop immediately.

SYNTEX:-

continue;

The continue statement interrupts an iteration (in a loop) when a specific condition occurs and
continues with the next iteration in the loop.
Session 2024 – 25 26
Java Core / AI&DS

In the example of following, the value 4 is

skipped: public class Main {

public static void main(String[] args) {


for (int i = 0; i < 10; i++) { if
(i == 4) { continue;
}
System.out.println(i); } } }

3.6 Java Comments [2]

The statements in a Java program that are not executed by the compiler and interpreter are
referred to as comments.

3.7 For what reason do we involve Comments in a code?

Remarks are utilized to make the program more discernible by adding the subtleties of the code
with java.

It makes it simple to maintain the code and locate errors.

You can provide information or an explanation about the variable, method, class, or any
statement in thea aacomments.

It can likewise be utilized to forestall the execution of program code while testing the elective
code learn.

3.8 Array[1]
Java array is an object which contains elements of a similar data type. Additionally, The

elements of an array are stored in a contiguous memory location. It is a data structure where we

store similar elements. We can store only a fixed set of elements in a Java array.

Let's see a simple example that adds two matrices


.
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};

Session 2024 – 25 27
Java Core / AI&DS

int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices 9.
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices

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

for(int j=0;j<3;j++){

c[i][j]=a[i][j]+b[i][j];

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

}
System.out.println();//new line
}}}

Output: 2 6 8 6 8 10

Session 2024 – 25 28
Java Core / AI&DS

CHAPTER 4
OOPS CONCEPT IN JAVA
4.1 What are Strings in Java? [1]
Strings are the type of objects that can store the character of values. A string acts the same as
an array characters in Java.

4.2 Inheritance
Inheritance in Java is a mechanism whereby an object inherits all the properties and behavior
of its pare object.

It is an important part of OOP (object-oriented programming system).

The idea behind inheritance in Java is that you can create new classes based on existing
classes. When you inherit from an existing class, you can reuse methods and fields from the
parent class. Additionally, you can add new methods and fields to the current class.
Inheritance represents an IS-A relationship, also known as a parent-child relationship.

4.3 Polymorphism [6]

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object. Any Java object that can pass more than one IS-A test is considered to be

polymorphic.

Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) va together as a single unit. In encapsulation, the variables of a class will
be hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.

4.4 Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc. A Package can be defined as a grouping of related types (classes, interfaces,
Session 2024 – 25 29
Java Core / AI&DS

enumerations and annotations) providing access protection and namespace management.

4.5 Math class [3]


Math is an important class in Java that is extensively used and has a lot of interesting
functions. Import – import java.lang.Math; Some functions include: Max

int a =
10; int
b = 20;
Math.max(a, b);

Min
int a
= 10;
int b
= 20;
Math.min(a,b);

4.6 Mini Project (Guess The Number ) [3]


Let’s create a project where we are trying to ask the user to guess a randomly generated
number. The number is in the range of 1 to 100. If the user guesses a number that is greater,
we print “The number is too large”. If the user guesses a number that is smaller, we print
“The number is too small”. If the user is able to correctly guess the number, then we print
“Correct Number!”.

At the end we will print the number that was generated by our Math library.package
com.Lucky;

import java.util.Scanner;
public class Main { public static void main(String[] args) {
//MINI PROJECT
Scanner sc = new
Scanner(System.in);
int myNumber =
(int)(Math.random()*100);
int userNumber = 0;
do {
Session 2024 – 25 30
Java Core / AI&DS

System.out.println("Guess my
number(1-100) : ");
userNumber = sc.nextInt();
if(userNumber == myNumber) {
System.out.println("WOOHOO .. CORRECT NUMBER!!!");
break;}
else if(userNumber > myNumber) {
System.out.println("your number is too large");
} else {
System.out.println("your number is too small");
}
} while(userNumber >= 0);
System.out.print("My number was : ");
System.out.println(myNumber);
} }

4.7 Hangman Mini Project [5]


import java.util.Scanner; import
java.util.Random; public class HangmanGame {
private static String[] words = {"programming", "computer", "java",
"hangman",
"openai"};
private static String wordToGuess;
private static StringBuilder
guessedWord;
private static int maxAttempts = 6;
private static int attemptsLeft;
public static void main(String[] args)
{
Scanner scanner = new
Scanner(System.in);

Random random = new Random();

// Select a random word from the array


wordToGuess =
words[random.nextInt(words.length)];

// Initialize variables

guessedWord=new
StringBuilder("_".repeat(wordToGuess.

Session 2024 – 25 31
Java Core / AI&DS

length()));

attemptsLeft = maxAttempts;

System.out.println("Welcome to Hangman!");

while (attemptsLeft > 0 && guessedWord.indexOf("_")!= -1)

{System.out.println("Word to guess: " + guessedWord);

System.out.println("Attempts left: " + attemptsLeft);

System.out.print("Guess a letter: ");

String guess = scanner.nextLine().toLowerCase();

if (guess.length() == 1 && Character.isLetter(guess.charAt(0)))


{

if (wordToGuess.contains(guess)) {

// Update guessedWord with correctly guessed letter

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

if(wordToGuess.charAt(i)==guess.charAt(0))

guessedWord.setCharAt(i, guess.charAt(0));

else {

System.out.println("Incorrect guess!");

attemptsLeft--;

} else {

System.out.println("Please enter a valid letter.");

} }

if (guessedWord.indexOf("_") == -1) {
System.out.println("Congratulations! You guessed the word: " +
wordToGuess);

} else {

System.out.println("You ran out of attempts. The word was: " +


wordToGuess);

scanner.close();

}}

Session 2024 – 25 32
Java Core / AI&DS

CHAPTER 5
Conclusion

In this report, we have explored the multifaceted world of Java, a versatile and robust
programming language that has had a profound impact on the software development
industry. Java's enduring popularity can be attributed to its platform independence,
extensive library support, and rich ecosystem of tools and frameworks.

Platform Independence: Java's "Write Once, Run Anywhere" mantra has made it a go-to
choice for cross-platform development. By compiling code into bytecode executed by the
Java Virtual Machine (JVM), Java programs can seamlessly run on various operating
systems, which is a critical feature in today's diverse computing landscape. .

Ecosystem and Community: The Java ecosystem is enriched by a strong and vibrant
community. It offers a wealth of documentation, forums, and tutorials, making it an
excellent choice for both beginners and experienced programmers. Furthermore, Oracle,
the steward of Java, regularly releases updates and new versions, ensuring that Java remains
relevant and secure.

Security and Reliability: Java's design principles prioritize security and reliability. Its
memory management, exception handling, and type safety features contribute to creating
more robust and secure applications. These qualities are of utmost importance in critical
industries like finance, healthcare, and aerospace, where Java is widely used.

Scalability: Java's scalability is evident in its use in a wide range of applications, from small
mobile apps to large-scale enterprise systems. The language's support for multithreading
and distributed computing allows developers to build software that can handle high loads
and demanding workloads.

In conclusion, Java is not just a programming language; it is an enduring platform that


empowers developers to create diverse and innovative solutions. Its adaptability to an ever-

evolving technological landscape, strong community support, and commitment to security


Session 2024 – 25 33
Java Core / AI&DS

and reliability make it a valuable asset for any software project. As we move forward in the
digital age, Java will undoubtedly continue to be a foundational technology in the world of
software development.

Java's journey is far from over. With the introduction of new features and evolving trends
in software development, Java remains poised to adapt and thrive. This report has provided
an overview of Java's significance, but the world of Java is vast and ever-expanding,
offering countless opportunities for exploration, innovation, and continued success.

This conclusion summarizes the key points of your report and highlights Java's strengths
and significance in the software development landscape. You can adjust and expand it
further based on the specific content and findings of your report.

In conclusion, Java is not just a programming language; it is an enduring platform that


empowers developers to create diverse and innovative solutions. Its adaptability to an ever-
evolving technological landscape, strong community support, and commitment to security
and reliability make it a valuable asset for any software project. As we move forward in the
digital age, Java will undoubtedly continue to be a foundational technology in the world of
software development.

Session 2024 – 25 34
Java Core / AI&DS

References

[1]. Basics to advance concepts of Java by javatpoint ,2021,(Available ):


https://www.javatpoint.com/java-tutorial[Accessed] 09-Sep-2023.

[2]. Article on the path and tools of Java (Available): https://dev.java/learn/getting-started}


[Accessed ] 10-Sep-2023.

[3]. Java (programming language) Available : https://en.wikipedia.org/wiki/Java


(programming_language) [Accessed] 10Sep-2023.

[4]. Java Tutorial by W3Schools is Powered by W3.CSS Available:


https://www.w3schools.com/java

[5]. Java Tutorial by W3Schools is Powered by W3.CSS Available: "Oracle Java SE Support
Roadmap". Oracle. September 13, 2021. Archived from the original on September 19, 2021.
Retrieved September 18, 2021.

[6]. Object-oriented Programming with Java: Essentials and Applications. Tata McGraw-Hill
Education. p. 34.

[7]. JDK 20: The new features in Java 20 Available :


https://www.infoworld.com/article/3676699/jdk-20-the-new-featur 20.html.

[8]. Java JDK 20 https://openjdk.org/projects/jdk/20/

[9]. Basics of Java Programming language from beginner to advanced topic by Herbert Schildt
of Oracle Publication .

Session 2024 – 25 35

You might also like