Sunteți pe pagina 1din 44

CERTIFICATE

This is to certify that the industrial training seminar report on “CORE

JAVA” at “ Bodacious IT Hub. Pvt. Ltd.” from period of training is submitted

by “ Khushboo Verma ( 17EAYCS046 )” in partial fulfillment for the award

of degree of Bachelor of Technology in Computer Science has been found

satisfactory and is approved for submission.

Er. Pradeep Jha Er. Naveen Tiwari


Head of Department Seminar Coordinator
Computer Science & Engineering Computer Science & Engineering

ii
ABSTRACT

The game of Tic-Tac-Toe is one of the most commonly known game. Tis game

does not allow one to win all the time and a significant proportion of games

played results in a draw. Thus, the best a player can hope is to not lose the game.

This study is aimed at evolving a no. of no loss strategies, using genetic

algorithms and comparing them with existing methodologies. To efficiently

evolve no loss strategies, we have developed innovative ways of representing and

evaluating a solution, initializing the GA population, developing GA operators

including an elite preserving scheme. Interestingly, our GA implementation is

able to find more than 72 thousand no loss strategies for playing the game.

Moreover, an analysis of these solutions has given us insights about how to lay

the game to not lose it. Based on this experience, we have developed specialized

efficient strategies having a high win to draw ratio . This study and its results are

interesting and can be encouraging for the techniques to be applied to other board

games for finding efficient strategies.

iii
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.

ABSTRACT…………………………………….....iii
LIST OF TABLE………………….….…………...vi
LIST OF FIGURES……..……..…………………vii
LIST OF ABBRIVATIONS………………...........viii
ACKNOWLEDGEMENT..………………............ix

1. Introduction to java………………………………1-28
1.1. The java Platform 3
1.1.1. JAVA and open Source 4
1.1.2. JAVA Virtual Machine 4
1.1.3. JAVA runtime environment and JDK 4

1.2. Installation of JAVA 4

1.2.1. Check Installation 4


1.2.2. Installing the JDK 5
1.2.3. Downloading and Installing 5
1.2.4. Note on Editions 5
1.3. Configuring variables 6

1.3.1. For Windows Users 6

1.3.2. For linux and UNIX 6

1.3.3. For Macintosh 7

1.4. Validate Installation 7

1.4.1. Development process with JAVA 7

1.5. Garbage Collector 8

1.6. Classpath 8

iv
1.7. Write, Compile & Run Program 8

1.7.1. Write source code 8

1.7.2. Compile and run 9

1.8. Package, Class and Object 10

1.8.1. Package 10

1.8.2. Class 11

1.8.3 Object 11

1.9. Inheritance 11

1.10. Variables 12

1.11. Methods 13

1.12. Interface 15

1.12.1. Class methods and variables 16

1.12.2. Abstract class and methods 16

1.12.3. Working with classes 17

1.12.4. Working with local variable 19

1.13. Integrated Development Environment 20

1.14. History of JAVA 22

1.15. Features of JAVA 25

2. Tic-Tac-Toe Application………………………….28-42

2.1. Introduction 28

2.2. History 28

2.3. Strategy 29

2.4. Working 31

v
LIST OF TABLES

Table Page no.

1.1 Working with classes 17

1.2 Working with local variables 19

1.3 History of JAVA 24

vi
LIST OF FIGURES

Figure Page no.

1.1 Program to print Hello world 9

1.2 Output of Hello world program 10

1.3 Use of extend keyword 12

1.4 Creating a method in java 13

1.5 Constructor in JAVA 14

1.6 Implementation of Interface 15

2.1 Tic-Tac-Toe 28

vii
LIST OF ABBREVIATIONS

API Application Programming Interface


GNU GNU’s Not Unix
GPL General Public License
IDE Integrated Development Environment
IDL Interface Definition Language
JDK Java Development Kit
JEE Java Enterprise Edition
JIT Just In Time
JME Java Micro Edition
JPEG Joint Photographic Expert Group
JRE Java Runtime Environment
JSE Java Standard Edition
JVM Java Virtual Machine
OOP Object Oriented Programming
PDA Personal Digital Assistant
PNG Portable Network Graphics
XML Extensible Markup Language

viii
ACKNOWLEDGEMENT

A scholarly and quality work like designing of any seminar can be accomplished
by motivation, guidance and inspiration of certain quarters besides the individual
efforts. Let me in this page express my heartiest gratitude to all those who helped
me in various stages of this study.

We are very much thankful to Prof. Himanshu Arora, PRINCIPAL, ACERC


College, Kukas and Er. Pradeep Jha, HOD, and Department of CS &
Engineering for giving me the permission to undergo this seminar and providing
all the necessary facilities.

During my seminar period all the staff members of department have helped us
with their skills. Here by I express our sincere thanks to seminar coordinator Er.
Naveen Tiwari whose valuable guidance and kind cooperation, without which
this seminar would have not been possible.

Khushboo Verma

17EAYCS046

Date :
Computer Science & Engineering

ix
CHAPTER 1

COMPANY PROFILE

BODACIOUS IT HUB PVT. LTD.

Bodacious IT Hub is a Jaipur based company founded by Bijendra


Bhati (popularly known as Bhati Sir). The company deals in software development
and information technology training both. We deliver products as well as
services. We have been developing applications and providing various services
like Corporate Training, IT Consultancy, Software Development Assistance and
IT Outsourcing. Being a pioneer in IT education we always have best of the brains
with us and we are known for providing exceptionally well training to aspirants
and using all the latest technologies. Bodacious IT Hub is a team of
talented professionals who have been working on various types of pr ojects
(desktop applications, web applications and mobile applications) since years using
technologies like Java, iOS, Android, Salesforce, .NET and C++. Bodacious is a
renowned name as far as IT Training is concerned and we also have a team of
skilled and experienced professionals whohave hands on experience on different
technologies so we always havepeople seeking our advice and consultancy. We
have been passionately providing consultancy to clients all over the world.
Our trainees have risen to such heights that they have made the name Bodacious
IT Hub synonyms with success in the IT world. Our trainees are working in the
leading IT companies all over the world (Amazon, Google, Facebook etc.) and
some of them have got certificate of excellence wherever th ey are working.The
achievement of Bodacious IT Hub is consolidated by the fact that we have trainees
coming from various parts of world including USA, CANADA etc. Bodacious IT
Hub has produced hundreds of Sun Certified Java Professionals so far. It is the
leading organization that has been involved in preparing students for online exams.

x
Introduction to Java

With the invention of microprocessors, the world is scientifically developed with sophisticated
equipment’s, systems, and devices. Microprocessors are used in computers, televisions, and
fax machines. Even the hand-held devices such as pagers, PDAs (Personal Digital Assistant),
and cell phones make use of microprocessors. All these electronic devices are helpful because
of their communication capabilities. With the increasing capabilities and decreasing cost of
information processing and networking technologies, the network is growing rapidly for
transmitting information through electronic systems.

Internet is the network of networks between different types of computers located at different
places to transmit information. Information can reach to any place in the world quickly at a
cheaper rate through the Internet. Thus, the Internet has made the world a global village for
information exchange. The emerging infrastructure of electronic devices and interconnected
computer networks create an environment that presents new challenges to software industries.
for this emerging computing environment, Java process to be a well – suited programming
language. it is found suitable for networked environments involving a great variety of
computer and devices.

Java has many characteristics that have contributed to its popularity:

 Platform independence - Many languages are compatible with only one platform.
Java was specifically designed so that it would run on any computer, regardless if it
was running Windows, Linux, Mac, Unix or any of the other operating systems.
 Simple and easy to use - Java's creators tried to design it so code could be written
efficiently and easily.
 Multi-functional - Java can produce many applications from command-line programs
to applets to Swing windows (basically, sophisticated graphical user interfaces).

Java does have some drawbacks. Since it has automated garbage collection, it can
tend to use more memory than other similar languages. There are often
implementation differences on different platforms, which have led to Java being

1
described as a "write once, test everywhere" system. Lastly, since it uses an
abstract "virtual machine", a generic Java program doesn't have access to the
Native API's on a system directly. None of these issues are fatal, but it can mean
that Java isn't an appropriate choice for a particular piece of software.

 Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each


of which represents an instance of a class.
4 main concepts of Object Oriented programming are:

 Abstraction
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a
process where you show only “relevant” data and “hide” unnecessary details of an
object from the user. For example, when you login to your Amazon account online,
you enter your user_id and password and press login, what happens when you press
login, how the input data sent to amazon server, how it gets verified is all abstracted
away from the you.
 Encapsulation
Binding the data with the code that manipulates it. It keeps the data and the code safe
from external interference. Looking at the example of a power steering mechanism of
a car. Power steering of a car is a complex system, which internally have lots of
components tightly coupled together, they work synchronously to turn the car in the
desired direction. It even controls the power delivered by the engine to the steering
wheel. But to the external world there is only one interface is available and rest of the
complexity is hidden. Moreover, the steering unit in itself is complete and independent.
It does not affect the functioning of any other mechanism.
 Inheritance
Inheritance is the mechanism by which an object acquires the some/all properties of
another object.
It supports the concept of hierarchical classification.

2
For example: Car is a four wheeler vehicle so assume that we have a class FourWheeler
and a sub class of it named Car. Here Car acquires the properties of a class
FourWheeler. Other classifications could be a jeep, tempo, van etc. FourWheeler
defines a class of vehicles that have four wheels, and specific range of engine power,
load carrying capacity etc. Car (termed as a sub-class) acquires these properties from
FourWheeler, and has some specific properties, which are different from other
classifications of FourWheeler, such as luxury, comfort, shape, size, usage etc.
 Polymorphism
Polymorphism means to process objects differently based on their data type.
In other words it means, one method with multiple implementation, for a certain class
of action. And which implementation to be used is decided at runtime depending upon
the situation (i.e., data type of the object)
This can be implemented by designing a generic interface, which provides generic
methods for a certain class of action and there can be multiple classes, which provides
the implementation of these generic methods. [2]

1.1 The Java Platform

One thing that distinguished Java from some other languages is its ability to run the same
compiled code across multiple operating systems. In other languages, the source code (code
that is written by the programmer), is compiled by a compiler into an executable file. This file
is in machine language, and is intended for a single operating system/processor combination,
so the programmer would have to re-compile the program separately for each new operating
system/processor combination. Java is different in that it does not compile the code directly
into machine language code. Compilation creates byte code out of the source code. Byte code
generally looks something like this:

a7 f4 73 5a 1b 92 7d

When the code is run by the user, it is processed by something called the Java Virtual Machine
(JVM). The JVM is essentially an interpreter for the byte code. It goes through the byte code
and runs it. There are different versions of the JVM that are compatible with each OS and can

3
run the same code. There is virtually no difference for the end-user, but this makes it a lot easier
for programmers doing software development.

1.1.1 Java and Open Source:-

 In 2006 Sun started to make Java available under the GNU General Public License
(GPL). Oracle continues this project called OpenJDK.

1.1.2 Java Virtual machine:-

 The Java virtual machine (JVM) is a software implementation of a computer that


executes programs like a real machine.
 The Java virtual machine is written specifically for a specific operating system, e.g. for
Linux a special implementation is required as well as for Windows.
 Java programs are compiled by the Java compiler into byte code. The Java virtual
machine interprets this byte code and executes the Java program.

1.1.3 Java Runtime Environment vs. Java Development Kit

 A Java distribution comes typically in two flavors, the Java Runtime Environment
(JRE) and the Java Development Kit (JDK).
 The Java runtime environment (JRE) consists of the JVM and the Java class libraries
and contains the necessary functionality to start Java programs.
 The JDK contains in addition the development tools necessary to create Java programs.
The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java
class libraries.

1.2 Installation of Java

1.2.1 Check installation


 Java might already be installed on your machine. You can test this by opening a console
(if you are using Windows: Win+R, enter cmd and press Enter) and by typing in the
following command:
 java -version

4
 If Java is correctly installed, you should see some information about your Java
installation. If the command line returns the information that the program could not be
found, you have to install Java.

1.2.2 Installing the Java Development Kit

 Before installing the Java Development Kit (JDK), you should probably know what it
is. It is distributed by Oracle. It contains the core libraries and compiler required to
develop Java. The JDK should not be confused with the JRE (Java Runtime
Environment). The JRE is a JVM for running, as opposed to compiling, Java programs.

1.2.3 Downloading and Installing

 To download the JDK go to


http://www.oracle.com/technetwork/java/javase/downloads/index.html. Click on
"JDK with NetBeans Bundle". Follow the instructions for downloading the JDK
installation file.
Windows: If you are running Windows, simply run the executable file and follow the
installation instructions.
Unix, Solaris, or Linux: For Linux and Unix, download the "jdk1 6.0" for Linux
systems. Save the downloaded file in any drive. Once you have saved the file, extract
it to a place that you can remember, by using Terminal or by double clicking on the file.
When you have finished extracting the file, copy the JDK 1.6.0 folder and paste it in
the usr/local(To paste to the usr/local directory, you have to be in root) so that every
user can use the java files. You can delete the downloaded zip file so that it doesn't take
up space on your drive.
Macintosh: The latest available JDK is automatically installed by the operating system.
Because Java for Macintosh is developed and maintained by Apple, in coordination
with Sun, the current version on the Macintosh may not be the current version that is
available
1.2.4 Note on Editions
 The JDK comes in three editions.

5
 Java Standard Edition (JSE) – This version is the basic platform for Java. The course
will focus on this edition.
 Java Enterprise Edition (JEE) – This edition is mainly for developing and running
distributed multitier architecture Java applications, based largely on modular software
components running on an application server. We will not be covering this version in
the course.
 Java Micro Edition (JME) – This edition is primarily for developing programs to run
on consumer applicances, such as PDAs and cell phones.

1.3 Configuring Variables

 Before writing code, it is recommended that you set the Path variable on your system
so you can compile your code more easily.
1.3.1 For Windows Users
 From the Control Panel, double click "System" (System and Maintenance in Vista)
 For Windows 7 or Vista, click on "System," "Advanced System Settings" on the left,
and then on "Environment Variables."
 For XP and 2000, click on the "Advanced" tab and click on "Environment Variables"
For NT, click on the "Environment" tab.
 Select the Path variable and click "Edit"
 Add the path to the bin directory of where Java is installed on your hard drive. It should
probably be: C:\Program Files\Java\jdk1.6.0_20\bin unless you changed it during
installation.
 Click OK

1.3.2 For Linux and UNIX

 One way to set your path in Linux/Unix is to add a path export to your bash profile.
In order to do this, first open your bash profile in a text editor. For example,
 pico ~/.bash_profile Then add this line:
 export PATH=$PATH:/usr/local/jdk/bin

6
 Note that the path to the java directory "/usr/local/jdk/bin" may be different on your
machine
 Restart your shell.

1.3.3 For Macintosh

 Apple sets everything up for you. Sit back and relax.


 The only drawback is that because Apple handles development and maintenance of
Java on the Mac, there is usually a delay from the time that a new version is released
by Sun and the time that the new version is released on the Mac. Also, getting the latest
version sometimes requires an operating system upgrade.
 Oh well, you can't have everything.

1.4 Validate installation

 Switch again to the command line and run the following command.
 java -version
 The output should be similar to the following output.
 java version "1.7.0_25"
 OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1ubuntu0.13.04.2)
 OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)

1.4.1 Development Process with Java

 Java source files are written as plain text documents. The programmer typically writes
Java source code in an Integrated Development Environment (IDE) for programming.
An IDE supports the programmer in the task of writing code, e.g. it provides auto-
formating of the source code, highlighting of the important keywords, etc.
 At some point the programmer (or the IDE) calls the Java compiler (javac). The Java
compiler creates the bytecode instructions. These instructions are stored in .class files
and can be executed by the Java Virtual Machine.

7
1.5 Garbage collector

 The JVM automatically re-collects the memory which is not referred to by other
objects. The java garbage collector checks all object references and find the objects
which can be automatically released.
 While the garbage collector releases the programmer from the need to explicitly
manage memory the programmer still need to ensure that he does not keep unneeded
object references otherwise the garbage collector cannot release the associated memory.
Keeping unneeded object references are typically called memory leaks.

1.6 Classpath

 The classpath defines where the Java compiler and Java runtime look for .class files to
load. This instructions can be used in the Java program.
 For example if you want to use an external Java library you have to add this library to
your classpath to use it in your program.
1.7Write, compile and run a Java program

1.7.1 Write source code

 The following Java program is developed under Linux using a text editor and the
command line. The process on other operating system should be similar and but is not
covered in this description.
 Select or create a new directory which will be used for your Java development. In this
description the path \home\vogella\javastarter is used. On Microsoft Windows your
might want to use c:\temp\javastarter. This path is called javadir in the following
description. Open a text editor which supports plain text, e.g. gedit under Linux or
Notepad under Windows and write the following source code.

8
Fig.1.1 Program to print Hello world

Save the source code in your javadir directory with the HelloWorld.java filename. The name
of a Java source file must always equals the class name (within the source code) and end with
the .java extension. In this example the filename must be HelloWorld.java because the class is
called HelloWorld.

1.7.2 Compile and run your Java program

 Open a shell for command line access. Switch to the javadir directory with the
command cd javadir, for example in the above example via the cd
\home\vogella\javastarter command. Use the ls command (dir under Microsoft
Windows) to verify that the source file is in the directory. Compile your Java source
file into a class file with the following command.

javac HelloWorld.java

Afterwards list again the content of the directory with the ls or dir command. The directory
contains now a file "HelloWorld.class". If you see this file you have successfully compiled
your first Java source code into bytecode.

You can now start your compiled Java program. Ensure that you are still in the jardir directory
and enter the following command to start your Java program.

9
java HelloWorld

The system should write "Hello World" on the command line.

Fig. 1.2 Output of Hello world program

1.8 Package, Class and Object

It is important to understand the base terminology of Java in terms of packages, classes and
objects. This section gives an overview of these terms.

1.8.1 Package

Java groups classes into functional packages.

Packages are typically used to group classes into logical units. For example all graphical
views of an application might be placed in the same package called
com.vogella.webapplication.views.

It is common practice to use the reverse domain name of the company as top level package.
For example the company might own the domain, vogella.com and in this example the Java
packages of this company starts with com.vogella.

Other main reason for the usage of packages is to avoid name collisions of classes. A name
collision occurs if two programmers give the same fully qualified name to a class. The fully

10
qualified name of a class in Java consists out of the package name followed by a dot (.) and the
class name.

Without packages, a programmer may create a Java class called Test. Another programmer
may create a class with the same name. With the usage of packages you can tell the system
which class to call. For example if the first programmer puts the Test class into package report
and the second programmer puts his class into package xmlreader you can distinguish between
these classes by using the fully qualified name, e.g. xmlreader.Test or report.Test.

1.8.2 Class

Def.: Template that describes the data and behavior associated with an instance of that class.

In Java source code a class is defined by the class keyword and must start with a capital letter.
The body of a class is surrounded by {}.

package test;

class MyClass { }

The data associated with a class is stored in variables ; the behavior associated to a class or
object is implemented with methods.

A class is contained in a Java source file with the same name as the class plus the .java
extension.

1.8.3 Object

An object is an instance of a class. The object is the real element which has data and can
perform actions. Each object is created based on the class definition.

1.9 Inheritance

A class can be derived from another class. In this case this class is called a subclass. Another
common phrase is that a class extends another class. The class from which the subclass is
derived is called a superclass. Inheritance allows a class to inherit the behavior and data
definitions of another class. The following codes demonstrates how a class can extend another
class. In Java a class can extend a maximum of one class.

11
Fig. 1.3 Use of extend keyword

1.10 Variables
Variables allow the Java program to store values during the runtime of the program. A
variable can either be a primitive variable or a reference variable. A primitive variable
contains value while the reference variable contains a reference (pointer) to the object.
Hence if you compare two reference variables, you compare if both point to the same
object. To compare objects use the object1.equals(object2) method call.

 Instance variable
Instance variable is associated with an instance of the class (also called object). Access
works over these objects. Instance variables can have any access control and can be
marked final or transient. Instance variables marked as final cannot be changed after
assigned to a value.

12
 Local variable
Local (stack) variable declarations cannot have access modifiers. Final is the only
modifier available to local variables. This modifier defines that the variable can not be
changed after first assignment. Local variables do not get default values, so they must
be initialized before use.

1.11 Methods

A method is a block of code with parameters and a return value. It can be called on the object.

Fig. 1.4 Creating a method in java

Method can be declared with var-args. In this case the method declares a parameter which
accepts from zero to many arguments (syntax: type .. name;) A method can only have one var-
args parameter and this must be the last parameter in the method.

Overwrite of a superclass method: A method must be of the exact same return parameter and
the same arguments. Also the return parameter must be the same. Overload methods: An
overloaded method is a method with the same name, but different arguments. The return type
can not be used to overload a method.

13
 Main method
A public static method with the following signature can be used to start a Java
application. Such a method is typically called main method.

public static void main(String[] args) { }

 Constructor
A class contains constructors that are invoked to create objects based on the class
definition. Constructor declarations look like method declarations except that they use
the name of the class and have no return type. A class can have several constructors
with different parameters. Each class must define at least one constructor.

In the following example the constructor of the class expects a parameter.

Fig. 1.5 Constructor in JAVA

If no explicit constructor is defined the compiler adds implicitly a constructor. If the class is
sub-classed then the constructor of the super class is always implicitly called in this case.

14
Every object is created based on a constructor. This constructor method is the first statement
called before anything else can be done with the object.

1.12 Interface

Interfaces are contracts for what a class can do but they say nothing about the way in which the
class must do it. An interface is a type similar to a class. Like a class an interface defines
methods. An interface can have only abstract methods, no concrete methods are allowed.
Methods defined in interfaces are by default public and abstract – explicit declaration of these
modifiers is optional. Interfaces can have constants which are always implicitly public, static
and final. A class can implement an interface. In this case it must provide concrete
implementations of the interface methods. If you override a method defined by an interface
you can also use the @override annotation. The following code shows an example
implementation of an interface and its usage within a class.

Fig. 1.6 Implementation of Interface

15
1.12.1 Class methods and class variables

Class methods and class variables are associated with the class and not an instance of the class,
i.e. objects. To refer to these element you can use the classname and a dot (".") followed by the
class method or class variable name. Class methods and class variables are declared with the
static keyword. Class methods are also called static methods and class variables are also called
static variables or static fields.

An example for the usage of a static field is println of the following statement:
System.out.println("Hello World"). out is a static field, an object of type PrintStream, and you
call the println() method on this object. If you define a static variable the Java runtime
environment associates one class variable for a class no matter how many instances (objects)
exists. The static variable can therefore be seen as a global variable.

If a variable should be defined as constant, you declare it with the static and the final keyword.
The static method runs without any instance of the class, it cannot directly access non-static
variables or methods.

1.12.2 Abstract class and methods

A class and method can be declared as abstract. An abstract class can not be directly
instantiated. If a class has at least one method which only contain the declaration of the method
but not the implementation then this class is abstract and can not be instantiated. Sub-classes
need then to define the methods except if they are also declared as abstract. If a class contains
an abstract method it also needs to get defined with the keyword abstract. The following
example shows an abstract class.

package com.vogella.javaintro.base;

public abstract class MyAbstractClass { abstract double returnDouble(); }

16
1.12.3 Working With Classes

What to do How to do it
Create a new class called MyNewClass. package test;

public class MyNewClass {

}
Create a new attribute (instance variable) package test;
called var1 of type String in the
MyNewClass class public class MyNewClass { private String
var1; }

Create a Constructor for your MyNewClass package test;


class which has a String parameter and
assigns the value of it to the var1 instance public class MyNewClass { private String
variable. var1;

public MyNewClass(String para1) {


var1 = para1; // or this.var1= para1; } }

Create a new method called doSomeThing package test;


in your class which does not return a value
and has no parameters public class MyNewClass { private String
var1;

public MyNewClass(String para1) {


var1 = para1; // or this.var1= para1; }

public void doSomeThing() { }

17
Create a new method called doSomeThing2 package test;
in your class which does not return a value
and has two parameters, a int and a Person public class MyNewClass { private String
var1;

public MyNewClass(String para1) {


var1 = para1; // or this.var1= para1; }

public void doSomeThing()


{

public void doSomeThing2(int a, Person


person) {

public int doSomeThing3(String a, String


b, Person person) { return 5; // Any value
will do for this example }

Create a class called MyOtherClass with package test;


two instance variables. One will store a
String, the other will store a Dog. Create public class MyOtherClass { String
getter and setter for these variables. myvalue; Dog dog;

18
public String getMyvalue() { return
myvalue; }

public void setMyvalue(String myvalue)


{ this.myvalue = myvalue; }

public Dog getDog() { return dog; }

public void setDog(Dog dog) { this.dog


= dog; } }

Table 1.1 Working with classes

1.12.4 Working With Local Variable

What to do How to do it
Declare a (local) variable of type string. String variable1;
Declare a (local) variable of type string and String variable2 = "Test";
assign "Test" to it.
Declare a (local) variable of type Person Person person;
Declare a (local) variable of type Person, Person person = new Person();
create a new Object and assign the variable
to this object.
Declare a array of type String String array[];
Declare a array of type Person and create an Person array[]= new Person[5];
array for this variable which can hold 5
Persons.
Assign 5 to the int variable var1 (which was var1 = 5;
already declared);
Assign the existing variable pers2 to the ; pers1 = pers2;
exiting variable pers1

19
Declare a ArrayList variable which can ArrayList<Person> persons;
hold objects of type Person
Create a new ArrayList with objects of type persons = new ArrayList<Person>();
Person and assign it to the existing variable
persons
Declare a ArrayList variable which can ArrayList<Person> persons = new
hold objects of type Person and create a ArrayList<Person>();
new Object for it.

Table 1.2 Working with local variables

1.13 Integrated Development Environment

The previous chapter explained how to create and compile a Java program on the command
line. A Java Integrated Development Environment (IDE) provides lots of ease of use
functionality for creating java programs. There are other very powerful IDE's available, for
example the Eclipse IDE. . For an introduction on how to use the Eclipse IDE please see Eclipse
IDE Tutorial. The remaining description uses the phrase: Create a Java project called... ". This
refers to creating a Java project in Eclipse. If you are using a different IDE please follow the
required steps in this IDE. Exercises - Creating Java objects and methods Create a Person
class and instantiate it Create a new Java project called com.vogella.javastarter.exercises1 and
a package with the same name. Create a class called Person. Add three instance variables to it,
one for storing the first name of the person, on for storing the last name and one for storing the
age of the Person. Use the constructor of the Person object to set the values to some default
value. Write a public method called writeName() which uses the System.out.println( method
to print the first name of the person to the console. Create a new class called Main with a public
static void main(String[] args). In this method create an instance of the Person class.

 Use constructor
Add a constructor to your Person class which takes the first name, last name and the
age as parameter. Assign the values to your instance variables. Create in your main
method two objects of type Person and call the writeName method on it.

20
Integrated development environments are designed to maximize programmer productivity by
providing tight-knit components with similar user interfaces. IDEs present a single program in
which all development is done. This program typically provides many features for authoring,
modifying, compiling, deploying and debugging software. This contrasts with software
development using unrelated tools, such as vi, GCC or make.

One aim of the IDE is to reduce the configuration necessary to piece together multiple
development utilities, instead it provides the same set of capabilities as one cohesive unit.
Reducing setup time can increase developer productivity, especially in cases where learning to
use the IDE is faster than manually integrating and learning all of the individual tools. Tighter
integration of all development tasks has the potential to improve overall productivity beyond
just helping with setup tasks. For example, code can be continuously parsed while it is being
edited, providing instant feedback when syntax errors are introduced, thus allowing developers
to debug code much faster and more easily with an IDE.

Some IDEs are dedicated to a specific programming language, allowing a feature set that most
closely matches the programming paradigms of the language. However, there are many
multiple-language IDEs.

While most modern IDEs are graphical, text-based IDEs such as Turbo Pascal were in popular
use before the availability of wisndowing systems like Microsoft Windows and the X Window
System (X11). They commonly use function keys or hotkeys to execute frequently used
commands or macros [3]

An Integrated Development Environment (IDE) is an application that facilitates application


development. In general, an IDE is a graphical user interface (GUI)-based workbench designed
to aid a developer in building software applications with an integrated environment combined
with all the required tools at hand.

Most common features, such as debugging, version control and data structure browsing, help
a developer quickly execute actions without switching to other applications. Thus, it helps
maximize productivity by providing similar user interfaces (UI) for related components and
reduces the time taken to learn the language. An IDE supports single or multiple languages [4]

21
1.14 HISTORY OF JAVA

It is quite interesting to know the development of Java technology, which is widely accepted
in the area of networked/distributed computing. Java evolved from a project developing a
language for programming consumer electronic devices at Sun Microsystems, USA.

Sun’s Stealth Project in 1990 was aimed to do research in the area of application of computers
in the consumer electronics market. Bill Joy, James Gosling, Mike Sheridan, Patrick Naughton
(formerly the project leader of Sun’s Open Windows user environment), and several other
individuals discussed the ideas for the Stealth Project in January 1991.The vision of this project
was to develop smart consumer electronic devices that could all be centrally controlled and
programmed from a handheld-remote-control-like device. The Stealth group began to work to
achieve this goal. It was realized that a platform-independent development-environment was
needed.

Green Project was initiated by Patrick Naughton, Mike Sheridan, and James Gosling of Sun
Microsystems in 1991 (Members of the Stealth Project, which later became known as the Green
Project) The tasks of the project were divided amongst the members of Green Project. Mike
Sheridan concentrated on business development, Patrick Naughton worked on the graphics
system, and James Gosling was to identify the appropriate programming language for the
Green Project. Even though creating a new language was not the aim of Green Project, a new
language was created as a programming tool in this project since C++ was found unsuitable for
the project.

An intelligent remote control called *7 (Star Seven) was delivered as the first product of Green
Project in 1992. It is a PDA- like device comprising of a new language oak, an operating system
called GreenOS, user interface, and hardware. This device was quite impressive to Sun
Executives. But no customer was interested in this project. The market was not conducive to
this type of device in the consumer electronics industry.

The new language Oak was created by James Gosling, a Green Team member, specifically for
*7. Gosling named the new language Oak because that name was struck while looking at an
oak three outside of his office window. The name Oak was later renamed to Java in order to
avoid legal issues since Oak was the name of an existing language.

22
In November 1992, the Green Project was incorporated under the name FirstPerson. In 1993.
Time-Warner was demanding for proposals for set-top box operating systems and videoon-
demand technology with an objective of sending the data to consumer all over the country for
display on the television sets. At the same time (1993(, NCSA released the first graphical web
browser Mosaic 1.0, an easy-to-use front end to the World Wide Web.

When FirstPerson was bidding on the Time-Warner TV trial based on video-on-demand


technology, Time-Warner chose Silicon Graphics, Inc. (SGI) over Sun. Hence, half of the
members of FirstPerson left for SGI and the remaining members continued to work at Sun.

Mosaic web browser revolutionized people’s perceptions. The remaining member of


FirstPerson returned to work on Java (Oak was renamed Java) to develop Java-based web
browser. FirstPerson was dissolved gradually. Naughton and Jonathan Payne developed
WebRunner (named after the movie Blade Runner). Later WevRunner was officially
announced as the HotJavaTM browser in 1994. This was the turning point for Java. At that
time the World Wide Web changed the face of Internet and it was winning the race on Internet.

Arthur Ban Hoff implemented the Java compiler in Java itself whereas Gosling implemented
it in C. The Java compiler, written in Java made the people to accept Java as a fullfeatured
language. Sun Microsystems officially announced Java environment at Sun World’95 on May
23, 1995. Java entered into the mainstream of the Internet after a struggle for about four years.
Netscape Communications incorporated Java into its web browser Netscape Navigator. Within
a decade, Java was destined to be the most overreaching technology in the Internet. Java was
not restricted to the Internet alone. The initial goal of Sun was also achieved by using Java
technology in interactive set-top boxes, hand-held devices and other consumer electronics
products. Sun released the first version 1.0 of Java in 1996. Java is an object-oriented
programming language which evolved from C++. It is also a high-level programming language.
The different forms of Java versions are discussed in the next section.

23
Year Java - Versions and Features
1990 Sun Microsystems started Stealth project supporting application of
computers in the consumer electronics market.
1991 The Green project started with the members of Stealth project such as James
Gosling, Patrick Naughton, and Mike Sheridan. A new programming
language, called Oak was created by Gosling.
1992 An intelligent remote control called StarSeven was delivered. The Green
Project was incorporated was incorporated under the name FirstPerson.
1993 Mosaic Web browser was introduced in the world of Internet.
1994 HotJava Web browser was announced by Sun Microsystems.
1995 Oak was renamed as Java. Sun officially announced Java technology
1996 Sun released the first version 1.0 of Java. Core Language features
supporting: I/O facility, Utilities, Network Programming, User Interface –
AWT, Applets, and Multithreading
1997 Sun released JDK1.1 by including new features such as addition of inner
classes to the language and capabilities such as JavaBeans, JDBC(Java Data
Base Connectivity), and RMI (Remote Method Invocation).
1998 Java 2 Platform, Standard Edition (J2SE)1.2, code named as Playground,
was released. It replaced JDK and distinguished the base platform from j2ee
(Java 2 Platform, Enterprise Edition) and J2ME (Java 2Platform, Micro
Edition). The key features include Swing graphical API, Java IDL (Interface
Definition Language) to support CORBA interoperability. They also added
Collections framework to support various data structures. For the first time,
JVM was equipped with a JIT (Just-inTime) compiler.
2000 J2SE 1.3, code named as Kestrel, was released with key features such as
JavaSound API to support audio operations (e.g., audio playback and
capture/recording, mixing, sequencing, and synthesis), Java Naming and
Directory Interface (JNDI), and Java Platform Debugger Architecture
(JPDA).
2002 H2SE 1.4, code named as Merlin, was released with key features such as (a)
image I/O API for manipulating images in formats like JPEG and PNG, (b)

24
integrated XML parser and XSLT processor (JAXP), integrated security and
cryptography extensions, (c) Java Web Start supporting deployment of Java
software applications over the network.
2004 J2SE 5.0, code named as Tiger, was released with enhancement of Java
platform and inclusion of a number of significant new language features such
as Generics, Enhanced for Loop, Autoboxing/Unboxing, Typesafe Enums,
Varags, Static Import, and Metadata supporting declarative style
programming annotation of source code.
2006 Java SE 6.0, code named as Mustang, was released with enhancement of
performance in Swing, JDBC 4.0 support, Java Compiler API, Upgrade of
JAXB to version 2.0, including integration of a StAX parser, support for
pluggable annotations, and many GUI improvements.
2008 Java SE 7.0, code named as Dolphin, with native support for XML
recognizing its foundation for Web services.

Table 1.3 History of Java

1.15 FEATURES OF JAVA

According to Sun, Java is defined as a simple, object-oriented, distributed, interpreted, robust,


secure, architecture –neutral, portable, high performance, multithreaded, and dynamic
programming language and platform.

Java is simple because the syntax of well-known languages such as C and C++ are used with
modifications meant for simplification and improvement. It is easy to read and write Java code
if the reader is familiar with C/C++.

Almost everything in Java is centered on creating objects, manipulating the objects and making
objects work together. Only the primitive operations and data types are at the sub-object level.
Hence Java is an object-oriented programming language.

25
An application can be distributed in many systems which are connected together. Since
networking capability is incorporated in Java, the data/file can be sent across many systems to
run the application.

Java is robust because it is more reliable. It ensures the reliability by providing early checking
for possible errors. It eliminates error-prone constructs such as pointer. It eliminates error-
prone constructs such as pointer. It also supports runtime error handling.

Java programs are compiled to a byte code format that can be read and run by interpreters on
many platforms including Windows, Linux, etc. Hence, it is architecture neutral. Because of
this feature it is portable to new hardware and operating systems.

Although the speed of execution of Java programs is slower compared to C/C++ programs,
Java is meant for distributed applications. Whenever the file/data is transmitted from one
system to another, the performance is not affected. Hence, it is having high performance.

Java supports multithreaded programming to perform several tasks simultaneously. Any code
can be loaded without recompilation at runtime. Hence it is dynamic.

 Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been
re-implemented in a cleaner way.

 Object Oriented

In java everything is Object which has some data and behaviour. Java can be easily
extended as it is based on Object Model.

 Robust

Java makes an effort to eliminate error prone codes by emphasizing mainly on compile
time error checking and runtime checking. But the main areas which Java improved
were Memory Management and mishandled Exceptions by introducing
automatic Garbage Collector and Exception Handling.

26
 Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.

On compilation Java program is compiled into bytecode. This bytecode is platform


independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.

 Secure

When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java
runtime environment with almost null interaction with system OS, hence it is more
secure.

 Multi-threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
 Architectural Neutral
Compiler generates byte codes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to interpret on any machine.
 Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
 High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like
C or C++. But, Java enables high performance with the use of just-in-time compiler.[5]

27
CHAPTER 2

Tic-Tac-Toe Application

2.1 Introduction

Tic-Tac-Toe (also known as Noughts and crosses or Xs and Os) is a paper and pencil game
for two players, X and O, who take turns marking the spaces in a 3 x 3 grid. The player who
succeeds in placing three of their marks in a horizontal , vertical or diagonal row wins the game.

Fig. 2.1 Tic-Tac-Toe

2.2 History
Games played on three-in-a-row boards can be traced back to ancient Egypt, where such
game boards have been found on roofing tiles dating from around 1300 BCE.
An early variation of tic-tac-toe was played in the Roman Empire, around the first century
BC. It was called terni lapilli (three pebbles at a time) and instead of having any number of
pieces, each player only had three, thus they had to move them around to empty spaces to
keep playing. The game's grid markings have been found chalked all over Rome. Another
closely related ancient game is three men's morris which is also played on a simple grid
and requires three pieces in a row to finish, and Picaria, a game of the Puebloans.
The different names of the game are more recent. The first print reference to "noughts and
crosses" (nought being an alternative word for zero), the British name, appeared in 1858,
in an issue of Notes and Queries. The first print reference to a game called "tick-tack-toe"
occurred in 1884, but referred to "a children's game played on a slate, consisting in trying
with the eyes shut to bring the pencil down on one of the numbers of a set, the number hit

28
being scored". "Tic-tac-toe" may also derive from "tick-tack", the name of an old version
of backgammon first described in 1558. The US renaming of "noughts and crosses" as "tic-
tac-toe" occurred in the 20th century.
In 1952, OXO (or Noughts and Crosses), developed by British computer
scientist Alexander S. Douglas for the EDSAC computer at the University of Cambridge,
became one of the first known video games. The computer player could play perfect games
of tic-tac-toe against a human opponent.
In 1975, tic-tac-toe was also used by MIT students to demonstrate the computational power
of Tinkertoy elements. The Tinkertoy computer, made out of (almost) only Tinkertoys, is
able to play tic-tac-toe perfectly. It is currently on display at the Museum of Science,
Boston.

2.3 Strategy

A player can play a perfect game of tic-tac-toe (to win or at least, draw) if each time it
is their turn to play, they choose the first available move from the following list, as used
in Newell and Simon's 1972 tic-tac-toe program.[16]
 Win: If the player has two in a row, they can place a third to get three in a row.
 Block: If the opponent has two in a row, the player must play the third themselves to
block the opponent.
 Fork: Create an opportunity where the player has two ways to win (two non-blocked
lines of 2
 Blocking an opponent's fork: If there is only one possible fork for the opponent, the
player should block it. Otherwise, the player should block all forks in any way that
simultaneously allows them to create two in a row. Otherwise, the player should create
a two in a row to force the opponent into defending, as long as it doesn't result in them
creating a fork. For example, if "X" has two opposite corners and "O" has the center,
"O" must not play a corner in order to win. (Playing a corner in this scenario creates a
fork for "X" to win.)
 Center: A player marks the center. (If it is the first move of the game, playing on a
corner gives the second player more opportunities to make a mistake and may therefore
be the better choice; however, it makes no difference between perfect players.)

29
 Opposite corner: If the opponent is in the corner, the player plays the opposite corner.
 Empty corner: The player plays in a corner square.
 Empty side: The player plays in a middle square on any of the 4 sides.

The first player, who shall be designated "X", has 3 possible positions to mark during the first
turn. Superficially, it might seem that there are 9 possible positions, corresponding to the 9
squares in the grid. However, by rotating the board, we will find that in the first turn, every
corner mark is strategically equivalent to every other corner mark. The same is true of every
edge (side middle) mark. For strategy purposes, there are therefore only three possible first
marks: corner, edge, or center. Player X can win or force a draw from any of these starting
marks; however, playing the corner gives the opponent the smallest choice of squares which
must be played to avoid losing.[17] This might suggest that the corner is the best opening move
for X, however another study[18] shows that if the players are not perfect, an opening move in
the center is best for X.

The second player, who shall be designated "O", must respond to X's opening mark in such a
way as to avoid the forced win. Player O must always respond to a corner opening with a center
mark, and to a center opening with a corner mark. An edge opening must be answered either
with a center mark, a corner mark next to the X, or an edge mark opposite the X. Any other
responses will allow X to force the win. Once the opening is completed, O's task is to follow
the above list of priorities in order to force the draw, or else to gain a win if X makes a weak
play.

More detailed, to guarantee a draw, O should adopt the following strategies:

 If X plays corner opening move, O should take center, and then an edge, forcing X to block
in the next move. This will stop any forks from happening. When both X and O are perfect
players and X chooses to start by marking a corner, O takes the center, and X takes the
corner opposite the original. In that case, O is free to choose any edge as its second move.
However, if X is not a perfect player and has played a corner and then an edge, O should
not play the opposite edge as its second move, because then X is not forced to block in the
next move and can fork.

30
 If X plays edge opening move, O should take center or one of the corners adjacent to X,
and then follow the above list of priorities, mainly paying attention to block forks.
 If X plays center opening move, O should take corner, and then follow the above list of
priorities, mainly paying attention to block forks.

When X plays corner first, and O is not a perfect player, the following may happen:

 If O responds with a center mark (best move for them), a perfect X player will take the
corner opposite the original. Then O should play an edge. However, if O plays a corner as
its second move, a perfect X player will mark the remaining corner, blocking O's 3-in-a-
row and making their own fork.
 If O responds with a corner mark, X is guaranteed to win, by simply taking any of the other
two corners and then the last, a fork. (since when X takes the third corner, O can only take
the position between the two X's. Then X can take the only remaining corner to win)
 If O responds with an edge mark, X is guaranteed to win, by taking center, then O can only
take the corner opposite the corner which X plays first. Finally, X can take a corner to
create a fork and then X will win on the next move.
2.4 Working

Step 1:-

Step 2:-

31
Step 3:-

Step 4:-

Step 5:-

32
33
References

1. https://beginnersbook.com/2013/05/java-introduction/

2. https://beginnersbook.com/2013/03/oops-in-java-encapsulation-inheritance-
polymorphism-abstraction/

3. https://en.wikipedia.org/wiki/Integrated_development_environment

4. https://www.techopedia.com/definition/26860/integrated-development-environment-ide

5. https://www.studytonight.com/java/features-of-java.php

34
35

S-ar putea să vă placă și