java book for beginners_first chapter

21
Mathwhiz India A Programming module for beginners Java 1.0 with application and game development tutorials Conceptualized, designed and developed by: Mathwhiz India An initiative by graduates of IIT, IIM and BITS Pilani dedicated to generate youth’s interest in Programming and Mathematics. reimagining education And I thought It was difficult ! Let’s learn Java in a playful way

Upload: aamir-mojeeb

Post on 14-Apr-2017

86 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Java book for beginners_first chapter

Mathwhiz India

A Programming module for beginners

Java 1.0 with application

and game development tutorials

Conceptualized, designed and developed by:

Mathwhiz IndiaAn initiative by graduates of IIT, IIM and BITS Pilanidedicated to generate youth’s interest in Programmingand Mathematics.

reimagining education

And I thought It was

difficult !

Let’s learn Java in a playful way

Page 2: Java book for beginners_first chapter

A transformed way of learning by providing comicappearance to a theory book

This is a book having explanation of every single term usedthat might seem new and strange to you

A module on the simplest language possible with back toback counter questions and answers to clarify every singledoubts that might come to your mind while going through

A journey that transforms your dream to reality, that makesyour passion worth pursuing and gives you a stand in thiscompetitive environment

Step by step explanation of making own games andapplications

Have a look at what the book has to offer!!

A game played by five characters to teach you every basicconcept of programming

A solution to the problem that young graduates are facingdue to not having a prior knowledge of programming

Page 3: Java book for beginners_first chapter

PREFACE

This book is a revolutionary attempt to exceed the regular pattern of

learning. Keeping in mind the importance of 21st century skills, we are

introducing the most interactive and easy to understand book for the

beginners in the field of programming. Efforts have been made to help

students master programming in a very exclusive and engaging way. We

have introduced fun elements, cartoon characters, doubts, questions

and explanations that maintain the interest of students. Technical

detailing, erudite language and incomprehensible vocabulary is avoided

to make the book student friendly.

The response and feedback from the readers across the country helped

us recognise the problems faced by students in learning a programming

language. Extensive efforts have been made to simplify and present the

content in the most user-friendly way. The book is designed by experts

to help students navigate and conquer the territory of programming.

Good luck in you expedition!

Page 4: Java book for beginners_first chapter

Views of trendsetters towards programming

“Learning to write programs stretches your mind, and helps youthink better, creates a way of thinking about things that I think ishelpful in all domains.”

Stephen HawkingTheoretical Physicist, Cosmologist,

and Author

“Whether you want to uncover the secrets of theuniverse, or you just want to pursue a career in the 21stcentury, basic computer programming is an essentialskill to learn.”

Steve JobsCofounder, Chairman, and CEO

of Apple Inc.

“Everybody in this country should learn to program acomputer, because it teaches you how to think.”

Mark ZuckerbergCo-Founder and CEO,

Facebook

“Everyone can learn programming logic, even the primary school kids.”

BillGatesChairman, Microsoft

Dr. Larry CoreyPresident, Fred

Hutchinson Cancer Research Center

“Computers are an increasingly essential part ofunderstanding cancer and developing new therapies.Knowledge of computer programming is almost as importantas knowledge of anatomy when it comes to medical researchor clinical care”

The following are the comments on programming by great successful peoplewho have shaped the world. They are people from different fields supportingour claim that says “Programming is needed no matter in what field you are”.

Page 5: Java book for beginners_first chapter

Views of brands towards this initiative of Mathwhiz India

Knowing how to program make kids thinkcomputationally and understand and tinkerthe world that they are living in. It is essentialthat we constantly innovate and whileeveryone has ideas, what shall separate thosewho will make them a reality is simple: theability to code. Coding is an emerginglanguage and this initiative believes ininvesting this in future.

Deepesh BharaniB.Tech, Computer Science, IIT Delhi

Quantitative Researcher at WorldQuant

Nice idea. I believe an initiative like this can goa long way in increasing programming skills andawareness among kids. A lot of students todayopt for Computer Science, B.Tech withouthaving a real interest or even being aware ofwhat it’s about. This can potentially providethem with good exposure to the same.

Dravyansh SharmaB.Tech, Computer Science, IIT Delhi

Software Engineer at Google

Computers are already everywhere andaffecting every single part of our lives.Over the next 10 years, there will be 1.4million jobs requiring knowledge ofprogramming and only 400,000 ofstudents who will graduate with computerscience degree in the period. The world ischanging and its time we catch up with it.

B.Tech, Computer Science, IIIT HyderabadSoftware Engineer at Facebook

Co-founder InterviewBit

A child’s brain is very agile, thus making it a placewhere creativity evolves. In order to create new, oneshould know the current ones to its depth. Similarly,coding helps in activating the brain of a child totransform their ideas into innovation.

Alfateh MustafaBCA, Christ University

Network Operation Centre Engineer, LinkedIn

Page 6: Java book for beginners_first chapter
Page 7: Java book for beginners_first chapter

MathWhiz India is a Start-up dedicated to generate youth’s interest in Mathematicsand Programming. MathWhiz India provides methods for quick calculations aimed atcountering ‘Math-Phobia’ among young students. The idea of the company wasselected as one among the top 500 ideas by ‘The Economic Times’ in 2012. Now thecompany has initiated a step to introduce programming language in the curriculumof primary schools in India. MathWhiz India provides different levels of Javaprogramming modules for beginners.

Copyright © 2015 MathWhiz IndiaAll Rights Reserved. This document contains highly confidential information and isthe sole property of MathWhiz India. Disclosing, copying, circulating, quoting orotherwise reproducing any or all contents of this document is strictly prohibited.Access to this information is provided exclusively for the benefit of the people ororganization concerned. It may not be accessed by, or offered whether for sale orotherwise to any third party.

Page 8: Java book for beginners_first chapter

T

b L

a

e

ofCon

tents

Team introduction 1

What is programming? 4

The basic operation in a computer 4

Importance of programming 5

The depth of programming 6

What is algorithm 7

What is the necessity of learning programming in schools 8

Let’s start with the types of programming language 8

What is Java 9

Why Java 11

What would you able to do after learning this language 11

Programming recipes 12

History of Java 14

Versions of Java 14

Features of Java programming language 15

Java as a platform independent language 16

Java Virtual Machine (JVM) 17

Java programs 18

Integrated Development Environment (IDE) 21

Object 22

Object Oriented Programming language 23

Class – a basis of all computations 23

Character Set 25

Tokens 26

Data Types 32

Syntax of writing programs 38

Operators 46

Programming section 57

Loop in Java 79

Make your own application 87

Make your own game 90

Have patience, we will discuss every topic in detail!!

Page 9: Java book for beginners_first chapter

Hello students !!My name is Mr. Head. I am here to teachyou the programming concepts with thehelp of a game. In the game there areseveral players playing different roles. Letus begin with the introduction of all theplayers participating in the game.

Hey Dexters !!I am the wisest player in the game. Sinceyou know that wise people speak less buttheir words are gems, so whenever Ispeak, listen to it carefully for it can be animportant lesson. I am also known as the“Do you know baba”

Hello Folks !!I am the one who will always be there toassist you with your doubts or questions. Ispeak a lot and therefore people usuallycall me the speaker.

Hello Pals !!My job is to give you the basicintroduction of all the new concepts. So tounderstand the subject, you need tofollow me at each and every step. I amplaying the role of a teacher.

Hello Students !!Meet me; I am a confused student justlike you who doesn’t have any idea of theprogramming concepts. So here I am inthe game. As my teacher says that if Ifollow him till the end, I will also becomea learned person like him.

Java 1.0

Mathwhiz India An Initiative to change Indian programming culture

P a g e | 1

Page 10: Java book for beginners_first chapter

These are the four players of the game who will surelymake your learning of the programming concepts funand memorable. So get ready for the journey students,you will have a great time ahead.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 2

Page 11: Java book for beginners_first chapter

Yesterday I met one of my friends; he showed me hissmartphone having many varied games and applications. Iasked him how are these cool applications created? Hereplied that they are all designed using computerprogramming.

My dad showed me a website on which anyone can book railway tickets,movie tickets, order online food and can do many other interesting things.I was astonished and when I asked him about the technology behind thecreative world of websites, the reply I got was the same, that they all aredesigned with the help of programming codes.

I have been using my computer for quite a long timebut never inquired about the core technology usingwhich everything in the computer worksautomatically. I asked my brother how thecomputers work. He informed me about theprogrammed chips inside the computer.

Whenever I ask anyone about the technology behind the functioning of mostof the computing devices, I get the same answer that it is all done usingcomputer programming. Now will someone please tell me what thisprogramming is?

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 3

Page 12: Java book for beginners_first chapter

Programming is a process of writing computer programswhich contains instructions for the machine or computerto perform a task automatically. It is an innovative processdone by programmers to instruct the machine/computeron how to perform a task.

Programming can be inferred as the instruction to a computer on how toperform a specific function like running games, playing videos and other tasks.Suppose you are teaching a man prepare tea. You will tell him to put somewater and milk in a kettle and add sugar and tea leaf. In the same way in orderto calculate two numbers you instruct the computer to bring the twonumbers, take one and add another to it and display the result.

The basic operation in a computer

ProcessInput Output

Mathwhiz India An Initiative to change Indian programming culture

What is programming?

The basic operation in a computer is getting the input, processing it and producing the output and programming is the main thing behind this processing.

Java 1.0 P a g e | 4

Page 13: Java book for beginners_first chapter

The world has changed due to programs. There has been a lotof automation introduced in almost everything around us.

Programming has completely transformed the world. It has made differentcomplex tasks simple, efficient and far less time consuming. The offlinemarkets and transactions have been transformed to online shopping & selling,money order to online banking or ATM and telephone culture to texting andvideo chatting.

Programming has not only changed social life but medical sciences as well.Now a days, most of the machines are programmed to give accurate andhuman error free results.

For example, Programmed Pacemakers, Robotic health check up’s, wrist healthbands, Diabetes check up devices, inoculation modulating device and manyother devices which you may have not heard about but definitely will as yougrow up and learn.

The world of space has become accurate and advance due to programming ofmachines in Airplanes, Fighter jets, Rockets and many advance automatedtelescopes which are searching for the life on other planets of the universe.It is the programming which has developed a system to control “ Mars Rover-”of its own on the land of Mars which is doing research and analysis on theplanet in every aspect which is impossible for a Human to do with that paceand accuracy.

Mathwhiz India An Initiative to change Indian programming culture

Importance of programming

Java 1.0 P a g e | 5

Page 14: Java book for beginners_first chapter

So now since you have understood the importance ofprogramming, let us understand the interconnection ofprogramming and our real world. Like it was mentionedearlier, you can also program for a table fan. So how doyou do it? Suppose you want a table fan to be controlledwith the help of a mobile phone. How would you do that?

You simply design a chip, write the code and voila! It is done. And the bestthing of this is, you can use Java as your language.The new generation has every dependency on codes. The ATM machines haveprograms. The cell towers have it. Also to note, the ease of making a programcan be made is astonishing. You can relate every code to a real worldexample.

Oh ! So this is the use of programming in our real world. NowI can say that every technology in our world is somehowlinked to programming. But how are the codes? Is it verydifficult and time consuming?

The depth of programming

Programming can be of hundreds of thousands of linesor simply a 5 lines of codes. Different kind of workrequires different set of codes to perform differentaction. Programming is nothing but steps to do a taskautomatically. You can program to predict the weatheror to calculate the probability to become the richestperson in the world. It just takes your ability and mindto relate different things to each other and createsomething that is innovative.

In programming the most important thing is the algorithm that determines the path of the written programs.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 6

Page 15: Java book for beginners_first chapter

What is Algorithm

A finite set ofprocedures/formula/steps/instructions written in a sequence tosolve a problem. It must haverecognizable set of stoppingpoint.We use algorithm every day. Inthe simplest term, algorithm isthe step by step technique ofperforming any task. Algorithmscan be expressed in anylanguage, from naturallanguages like English, Hindi,French etc. to programminglanguages like Java.

Do You Know??

Muhammad ibn Musa Al-Khwarizmi developed theconcept of the algorithm inmathematics (called as thefather of Computer Science bysome people). Today, peopleuse algorithms to do addition,long division etc., principlesthat were found in Al-Khwarizmi were text writtenabout 1200 years ago.

So now you have understood the importance ofprogramming, let us start learning a programming language.

No, I have heard that programming is very vast andtough to learn. Is it necessary to learn programming inschool?

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 7

Page 16: Java book for beginners_first chapter

What is it necessary to learn programming at schools

• Programming can be called as the language of thepresent world

• The coding culture of the world is on the rise• Every field like engineering, medical or commerce is

somewhat related to programming and it wouldpotentially be better if you have initialized it at anearly stage

• Capability of learning and innovation are more at ayounger age

• It is difficult to have commands on a language in ashort period of time

• Programming is not that difficult to learn

All right teacher, if it is so important, I am ready to learn programming.

Programming language

Imperative

Procedural eg. C

Object Oriented eg.

Java

Declerative

Functional eg. Haskell

Logic eg. Prolog

Let’s start with the types of programming language

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 8

Page 17: Java book for beginners_first chapter

In imperative programming language one needs to provide a step by step solution to the question “what is to be done?”.• Procedural eg. C• Object Oriented eg. Java

Declarative: In declarative language, there is only a need to express what one wants without specifying the procedure.• Functional eg. Haskell• Logic programming language eg. Prolog

You will learn the details of other different languages later on but firstly we will concentrate on one particular language.

So if there are a lot of different programming languages which language shall we start with?

We will start with Java, the most important andcommonly used programming language. Let me giveyou an introduction to this language.

What is Java?

A common purpose programming language designed to create or produceprograms that will run in any computer system. Java allows you to play games,to chat with people at different distances, view videos and images in 3D and alot more things. There are millions of websites and applications that run withJava programming language.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 9

Page 18: Java book for beginners_first chapter

Do You Know??

As per 2014 data in all over the world

9 million Java Developers

1 billion Java downloads

per year

3 billion devices run

Java

97% of enterprise

desktops run Java

89% of Desktops (or Computers) in the U.S. run Java

125 million TV devices

run Java

Yes sir, I understood that the language Java is of greatimportance. But what is the reason behind Java being sopopular and successful as a language? There must besomething behind the popularity of this language.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 10

Page 19: Java book for beginners_first chapter

Why Java?

Unlike other programming language such as C, C++,the programs in Java don’t interact directly with thecomputer Central Processing Unit (CPU) or theOperating System (OS) and therefore Java is platformindependent meaning they can run on any personalcomputer, workstation or any mainframe computer.

What would you be able to do after learning this language?

Every language acts as a medium to communicate. For example English, Hindi,French, German etc. are languages used for communicating to people ofsimilar social group but if you are aware of English language, you can say thatit is famous and known to almost every part of the world.

Java is just like the English language of Computer Race that is famous, easyand very effective to use in any part of the Programming language.It is the language that gives key to develop Android Applications, RobotProgrammes, Games and many other things that are used to give instructionor command or a way to communicate between machine and human.

Let us go through some of the recipes of programming language and some of the terms used frequently in programming vocabulary.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 11

Page 20: Java book for beginners_first chapter

What is syntax?Syntax is rules and symbols for validating the programming language that isjust like the Grammar of language English.

What do you mean by compiling and interpreting a program?Programmers/users/people write a program in a form called source code. Thissource code is basically a high level language that needs to be converted toobject code for the computer to understand the program. This process ofconverting source code into machine code is called as compiling a programwhich is the function of a compiler. The compiler also checks whether there isan error in the language of any form and returns the error message after thewhole program is compiled. After making the program error free, a separateexecuting command is given to run the program.

Programming recipes

The interpreter basically serves the same purpose as compiler but it directlyexecutes the program rather than first compiling and then executing leadingto the consumption of lesser time. The interpreter converts high levellanguage into machine language line by line executing it simultaneouslystopping the translating process the moment it finds the first error. Forexample: it translates the first line then execute it if there isn’t any error. Thenit moves to the second line and then to the third and so on. The moment itfinds an error it stops then and there and doesn’t proceed until it getscorrected.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 12

Page 21: Java book for beginners_first chapter

Hello students !!

Going through the introduction of programming,you must have realized the importance and theadvantage of learning the language. Moving on inthe next chapter, you will learn more about Javaprogramming language and at the end of it youwill be able to write simple and interesting codes.So stay tuned with the team and enjoy thelearning process.

Mathwhiz India An Initiative to change Indian programming culture

Java 1.0 P a g e | 13