first edition beginning java - techie...

50
By Nayan Seth First Edition Beginning Java iBooks Author

Upload: others

Post on 18-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

By Nayan Seth

First Edition

BeginningJava

iBooks Author

Page 2: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

1 In this chapter we will talk about who developed java and what is java?

Introduction To Java

iBooks Author

Page 3: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

2

James GoslingThe picture you see on left is of JAMES GOSLING. He is the one who developed Java at Sun Microsystems in 1995.

His weblog - http://nighthacks.com/

Section 1

Inventor of Java?

iBooks Author

Page 4: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

3

Java

Java is a programming language which is used widely all over the world. It is used for playing games online as well as for view-ing 3d images. It is used for doing many other things on the web.

It is one of the most powerful languages.

It is built completely on OOP’s Principle. Every program in java has to be written in classes.

Section 2

What is Java?

iBooks Author

Page 5: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

2 In this chapter we will learn about the IDE that can be used for coding in java.

IDE For Java

iBooks Author

Page 6: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

5

Eclipse IDE

Eclipse IDE For Java Developers is one of the most famous pro-grams used for developing in java.

It is available for Macintosh, Windows & Linux. This makes it even more famous.

IIsM

Section 1

Eclipse IDE For Java Developers

iBooks Author

Page 7: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

6

Installing Eclipse IDE

Macintosh

1. Go to http://www.eclipse.org/downloads

2. Select “Mac OS X (Cocoa)” from drop-down menu

3. Click on “Mac OS X 32 Bit or Mac OS X 64 Bit” next to Eclipse IDE For Java Developers.

4. Select one of the servers or select “bit-torrent”

5. Download the “.tar.gz” file

6. Extract the file you downloaded

7. Drag the eclipse folder extracted to the Applica-tions folder on your Mac OS X.

Windows

1. Go to http://www.eclipse.org/downloads

2. Select “Windows” from drop-down menu

3. Click on “Windows 32 Bit or Windows 64 Bit” next to Eclipse IDE For Java Developers.

4. Select one of the servers or select “bit-torrent”

5. Download the “.zip” file

6. Extract the file you downloaded

7. Drag the eclipse folder extracted to the “C:\Program Files” folder on your Windows XP/Vista/7

Linux (Ubuntu)

1. Go to “Ubuntu Software Center”

2. Search for Eclipse

3. Install Eclipse

MOVIE 2.1 Installing Java IDE

Learn how to install java ide on windows, macin-tosh and linux.

iBooks Author

Page 8: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

3 In this chapter we will talk about the basic oop’s features in java. JUST BASIC.........

Basic OOP Terms

iBooks Author

Page 9: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

Features

1. Classes & Objects

2. Data Abstraction

3. Encapsulation

4. Inheritance

5. Polymorphism

6. Dynamic Binding

7. Message Passing

8

OOP’sObject Oriented Programming is a way of coding whereby the program is made up of different small parts for faster execution.

Programs are divided into classes which may have “n” number of objects.

Why OOP’s?1. Data can be hidden from other functions

2. Functions can be created as and when required

3. Depends on use of objects and instances.

4. Make the program to get executed much faster.

5. All the features written on the left...........Blah blah blah

Section 1

Object Oriented Programming

iBooks Author

Page 10: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

9

What is A Object?

Objects are one the key terms in object oriented programming. A object can be anything like dog, cat, television, desk, etc.

Every object has two things in common “state” and “behavior”

Let’s consider a dog. A dog has “state - name, color, breed” and “behavior - fetching, barking, etc.”

Let’s consider another example of speaker. A speaker has “state - volume, frequency, etc” and “behavior - increase vol-ume, decrease volume, change frequency”

Section 2

Objects

iBooks Author

Page 11: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

10

What is A Class?In real world there are thousand’s of automobile (like honda civic, bentley, etc). There may be many automobile of same make and model. At the end every automobile is made up of the same components. So in object oriented terms an automo-bile is taken as an instance or object of the class “automobiles”.

A class can have ‘n’ number of instances or objects.

Syntax

class automobile {

----blah blah blah----

----blah blah blah----

}

* instance and object are one and the same thing

Section 3

Class

iBooks Author

Page 12: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

11

Lets take another example:

1. Lets say there is a class of animals.

2. Now lets think about animal. Lion, Cheetah, Tiger, Cat, Dog, etc are all animals. But in object oriented terms they are considered as an instance of the class animals.

3. Lion, Cheetah, etc will perform the tasks that we define in the class animals.

iBooks Author

Page 13: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

12

Data AbstractionAbstraction in the process of selecting important data sets for an Object in your software, and leaving out the insignificant ones.

This same information can be used in different applications.

eg: let’s say we are making a banking program.

we require info about the person who wants to open a account. this can be his name, address, phone no, pan card no, rashion card, electricity bill, etc...

but we just want some details of this like name, address, phone no. now this same information can be used in maintaining employee database.

Section 4

Data Abstraction

iBooks Author

Page 14: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

13

EncapsulationEncapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone out-side the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that pre-vents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our im-plemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Section 5

Encapsulation

iBooks Author

Page 15: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

14

InheritanceInheritance can be defined as the process where one object of one class acquires the properties of object/objects of another class.

eg: let’s consider a class vehicle which has some values of speed, power, etc.

now we have another class truck. it has an object t1. so now t1 derives data of speed and power from class vehicle.

Section 6

Inheritance

iBooks Author

Page 16: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

15

PolymorphismPolymorphism is the ability to take more than one form.

eg: consider you want to write a program on area. you want to find out the area of circle, rectangle.

now rectangle requires length & breadth values while circle requires only radius.

so we can have two functions for rectangle and circle with ‘l,b’ as argu-ments for rectangle and ‘r’ as argument for circle.

so now when a user types only radius the area of circle is calculated while if he types l & b it will give him area of rectangle.

this is also known as function overloading.

JUST READ THIS WE WILL DISCUSS IN DETAIL LATER.

Section 7

Polymorphism

iBooks Author

Page 17: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

16

What is it?????Dynamic Binding basically means that a particular part of code gets executed when it is called at run-time.

Section 8

Dynamic Binding

iBooks Author

Page 18: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

17

Message Passing?Message Passing basically is a property of java via which ob-jects can communicate with each other.

Section 9

Message Passing

iBooks Author

Page 19: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

4 In this chapter we will talk about the basic terms used in a java program.

Basic Terms In A Java Program

iBooks Author

Page 20: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

1. public

2. protected

3. private

this is a bit hard to understand in the beginning since we have not talked about methods. so just take it this way, public allows access to its contents to various classes, private allows access to its contents only in the class, protected allows access to its contents in the class.

19

What is “public”

public classes, methods, and fields can be accessed from every-where. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, thispublic class represents the ap-plication or the applet, in which case the public keyword is nec-essary to enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only if you ex-plicitly want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its upper-left corner and its size:

eg: public class Square { // public class

int x, y, size; // public instance variables

}

now the variables x, y, size are accessible by other classes.

“public” in public static void main basically means that the con-tents of main function can be accessed by any other class in the program.

Section 1

Access Specifiers

iBooks Author

Page 21: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

20

protected

protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its sub-classes, and within classes of the same package, but not from any-where else. You use theprotected access level when it is appropri-ate for a class's subclasses to have access to the method or field, but not for unrelated classes.

private

private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, theprivate access specifier is opposite to the pub-lic access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. An ex-ample, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual coordi-nates are not accessible to the user.

eg: public class Square { // public class

private double x, y // private (encapsulated) instance variables

public setCorner(int x, int y) { // setting values of private fields

this.x = x;

this.y = y;

}

public getCorner() { // setting values of private fields

return Point(x, y); } }

iBooks Author

Page 22: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

21

default Access Specifier

If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package.

Overview of Access Specifier

Note the difference between the default access which is in fact more restricted than the protected access. Without access specifier (the default choice), methods and variables are accessible only within the class that defines them and within classes that are part of the same package. They are not visible to subclasses unless these are in the same package. protected methods and variables are visible to subclasses regardless of which package they are in.

iBooks Author

Page 23: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

5 Let’s write out first java program.

Hello Java!

iBooks Author

Page 24: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

23

Programclass test{

public static void main(String args[])

{

System.out.print(“Hello Java”);

}

}

OutputHello Java

Section 1

Helloooo...Explanation --->

name of the class - test

main function header is - public static void main (String args[])

Keywords -

System.out.print >>> allows printing anything

public - the main function is public.

static - does not create an object and asks compiler to directly execute the main function.

void - its a return type which does not return any value (we will come to this later)

args[] - used for passing array of arguments (we will come to it later.)

iBooks Author

Page 25: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

6 Lets Comment

Comments

iBooks Author

Page 26: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

25

What is that!!!Now comments are something that may be anything that you write. It is not taken as a part of code. It is usually used to ex-plain what the program is about or it may be used to explain some part of code.

3 Types1. Single Line - Statements beginning with two forward slash.

eg: // hey this is a comment

2. Block Comments - Statements beginning with forward slash and a star sign (“/*”) & ending with a star sign and a forward slash (“*/”).

eg: /* hey this

is a

comment */

3. Documentation Comments - Statements beginning with for-ward slash and two star sign (“/**”) & ending with a star sign and a forward slash (“*/”).

eg: /**hey this is a comment */

Section 1

Comments

iBooks Author

Page 27: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

7 What variables and datatypes? What is that?

Variables & Datatypes

iBooks Author

Page 28: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

27

What is that????Variables are assigned with some data. They are basically given names. Names are easier to remember than values.

Let’s try remembering our mathematic lectures where we use to have word problems. There many times we were given values.

Let’s say we have two values now 20 and 40. So basically we use to assign two name to number 20 and 40 respectively.

eg: x = 20, y = 40

now in java x and y are the variable name.

now let’s take another example. I have a string ie “this is nayan”

i store it in str = “this is nayan”

it means “str” is the variable.

Section 1

Variables

iBooks Author

Page 29: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

28

What Are Datatypes?Now we just talked about variables but java doesn’t understand whether we are specifying a number or string in the variable.

So in order to make java understand what that variable is ie whether it is a integer, floating number or string we have da-tatypes.

We will learn about different datatypes and how to use them ahead.......

Section 2

Datatypes"

iBooks Author

Page 30: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

29

iBooks Author

Page 31: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

30

We are going to talk only about primitive datatypes.

Data Type Type Bit Space

ReqSigned/

Unsigned Range Default Value

byte byte-length integer 8 1 byte Signed -128 to 127 0

short short-length integer 16 2 bytes Signed -32768 to 32767 0

int integer 32 4 bytes Signed -2,147,483,648 to -2,147,483,647 0

long long integer 64 8 bytes Signed -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807 0L

floatsingle

precision decimal

32-bit IEEE 754

4 bytes Signed1.40129846432481707e-45 to

3.40282346638528860e+38 (positive or negative)

0.0f

doubledouble

precision decimal

64-bit IEEE 754

8 bytes Signed4.94065645841246544e-324d to 1.79769313486231570e+308d

(positive or negative)0.0d

boolean True/False 1 bit FALSE

char single character

16-bit Unicod

e charact

er

2 bytes Unsigned 0 to 65,535 ‘\u0000’

iBooks Author

Page 32: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

31

WHY NO UNSIGNED DATA-TYPES IN JAVA???? (ASK GOSLING)Read this answers of Dennis Ritchie (Developer C), Bjarne Stroustrup (Developer C++) and James Gosling (Developer Java).

Q. Programmers often talk about the advantages and disadvantages of programming in a "simple language."  What does that phrase mean to you, and is [C/C++/Java] a simple language in your view?

Ritchie: C (and the others for that matter) are simple in some ways, though they are also subtle; other, somewhat similar languages like Pascal are arguably simpler. What has become clear is that aspects of the environment like libraries that aren't part of the core lan-guage are much bigger and more complicated. The 1999 C standard grew hugely more in the library part than in the language; the C++ STL and other things are big; AWT and other things associated with Java are too.

Stroustrup: I see three obvious notions of "simple:" to be easy to learn, to make it easy to express ideas, and to have a one-to-one correspondence to some form of math. In those terms, none of the three languages is simple. However, once mastered, C and C++ make it easy to express quite complex and advanced ideas -- especially when those ideas have to be expressed under real-world re-source constraints.

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

Check the interview at - http://www.gotw.ca/publications/c_family_interview.htm

iBooks Author

Page 33: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

32

Another Reason...You Could SayI was digging through web pages and found this. Originally Java was known as Oak. One of its oldest guide says this

“The specification says: "The four integer types of widths of 8, 16, 32 and 64 bits, and are signed unless prefixed by the unsigned modi-fier.”

In the sidebar it says: "unsigned isn't implemented yet; it might never be." How right you were.”

Check Section 3.1 on http://www.artima.com/weblogs/viewpost.jsp?thread=7555

iBooks Author

Page 34: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

33

Difference Between Unsigned & Signed?????1. Unsigned datatypes can hold only positive values but their range increases

eg: if i have a datatype with range -127 to 128 then its unsigned will become 0 to 255

2. Signed datatypes can hold both positive and negative values.

StringString is nothing but a primitive datatype which helps in printing statements.

Default Value - null.

eg: This is Nayan, India is a country, Tech Barrack Solutions Pvt Ltd is a company

Default ValueBasically default value is either 0 or null. It is assigned to the datatype when the datatype is not initialized. And it works only for field variables and not for local variables. The variables in the main function are local variables. We will learn about field variables later.

Syntaxdatatype_name variable_name = value;

eg: byte x = 10;

iBooks Author

Page 35: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

8 Lets learn how we can import packages in java.

Java Packages

iBooks Author

Page 36: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

35

What is it???Huh??Just like in C++ where we have to include header files, in java we import packages.

Benefits Of Packages In JavaThe best part of java packages is we can import the class that we require rather than importing the whole package.

Default Package

import java.lang.*;

Syntaxeg: import java.package_name.class_name;

import java.util.Scanner;

import java.package_name.*;

this imports all classes from that particular package

import java.io.*;

Section 1

Java Packages

iBooks Author

Page 37: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

9 Ahh..Escape....What!!!

Escape Sequences

iBooks Author

Page 38: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

37

Section 1

Escape Sequences

Escape Sequence Function

\t inserts a tab

\b backspace

\n creates a new line

\r carriage return

\f form feed

\’ inserts a single quote

\” inserts a double quote

\\ inserts a backslash

What is that?These are characters preceded by a backslash(\). They are used in the System.out.print statements.

SyntaxSystem.out.print(“\n hey”);

iBooks Author

Page 39: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

10 What huh!!!!

Type Casting & Type Conversion

iBooks Author

Page 40: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

39

IntroductionNow we have many data-types in java. But if we want to con-vert one data-type to another we make use of type conversion or type casting.

Type ConversionNow let’s consider that we arrange data-types in ascending or-der i.e. by that i basically mean from a data-type which holds smaller value to one which holds the max value. So the data-types in ascending order will be like this >>> byte, short, int, long, float & double.

Type Conversion is kind of automatic conversion.

eg: So byte can be converted to short, int and long, float & dou-ble only. !

short can be converted to int, long, float & double.

int can be converted to long, float & double.

long can be converted to float and double.

long can never undergo type conversion to int, short or byte.

int can never undergo type conversion into short or byte.

Similarly short can never undergo type conversion into byte.

Section 1

Type Conversion & Type Casting

iBooks Author

Page 41: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

40

Or the other way round float can only be converted to double.

double can never undergo type conversion.

eg:

class test{

public static void main(String args[]){

short x = 5;

int y = x;

long z = y;

float a = z;

double b = a;

}

}

ExplanationNow we have a variable x of data-type short. It gets type con-verted to a variable y of data-type int. Now variable y gets con-verted to variable z of data-type long.

That was for integer. Now for floating part. We have a variable a of data-type float which gets type converted to variable b of data-type b.

So here we can notice that everything gets automatically con-verted without the user requiring to put any extra code.

iBooks Author

Page 42: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

41

Type CastingWe just learnt about Type Conversion now what is Type Cast-ing.

Okay so we saw that there are no automatic conversion from large data-type to small data-type. Type Casting solves our problem.

Syntaxdata_type variable_name = (data_type)either number or other variable;

eg:

class test{

public static void main(String args[]){

int x = 5;

short y = (short)x;

double z = (double)y;

long a = (long)z;

}

}

Explanationint x get type casted to short y. And a integer type variable i.e. short y gets converted to floating type i.e. double z. double z gets converted to long z which is a integer type

iBooks Author

Page 43: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

11 Learn how to take input from user in JAVA.

Taking Input From User

iBooks Author

Page 44: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

Three Methods

1. Scanner

2. BufferedReader

3. Data InputStreamReader

43

Basically there are three methods by which input from a user can be taken in java. We are only going to talk about the first two methods.

Section 1

Input From User

iBooks Author

Page 45: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

44

ScannerScanner is one the most common method used for taking input from user in java.

We import the java.util package with class Scanner.

import java.util.Scanner;

SyntaxScanner sc = new Scanner (System.in);

int i = sc.nextInt();

Data - Type Syntax

byte sc.nextByte();

short sc.nextShort();

int sc.nextInt();

long sc.nextLong();

float sc.nextFloat();

double sc.nextDouble();

string sc.next(); or sc.nextLine();

boolean sc.nextBoolean();

Section 1.1

Scanner

iBooks Author

Page 46: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

45

eg:

import java.util.Scanner;

class test{

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

int i = sc.nextInt();

System.out.println(i);

}

}

Output >>4

4

Explanationjava.util.Scanner - java.util is the package and Scanner is the class inside the package.

Scanner sc - sc is the name of the scanner that we are going to use in the program.

new Scanner - we are creating a object of sc using “new Scanner”

System.in - it tells java to take input from keyboard.

int i = sc.nextInt() - takes integer input from user

System.out.println - prints the input taken from user.

iBooks Author

Page 47: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

46

BufferedReaderThis method of taking input from user is very commonly taught to students in Educational Institutions.

In this method whatever input we take from user has to be taken in the form of String. And then it has to be type casted into a particular datatype. Basically type casted means con-verted to desired data type.

We also have throw an exception in the main function for this method.

SyntaxInputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String str = br.readLine();

Section 1.2

BufferedReader"Data - Type Syntax

byte Byte.parseByte();

short Short.parseShort();

int Integer.parseInt();

long Long.parseLong();

float Float.parseFloat();

double Double.parseDouble();

string br.readLine();

boolean Boolean.parseBoolean();

iBooks Author

Page 48: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

47

eg:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

class test{

public static void main(String args[]){

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String str = br.readLine();

int i = Integer.parseInt();

System.out.println(i);

}

}

Output >>4

4

Explanationimport java.io.* - we want 3 classes from the java.io package ie BufferedReader, InputStreamReader, IOException.

InputStreamReader isr - isr is the name of the InputStream-Reader that we are going to use in the program.

new InputStreamReader - we are creating a object of isr using “new InputStreamReader”

System.in - it tells java to take input from keyboard.

BufferedReader br - br is the name of BufferedReader that we are going to use in the program

new BufferedReader - creates object of br

String str = br.readLine(); - takes input from the user in string for-mat.

int i = Integer.parseInt(); - converts string input of user into inte-ger.

System.out.println - prints the input taken from user.

instead we can also write

import java.io.*;

iBooks Author

Page 49: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

IDEIntegrated Development Environment. It is basically a platform used for programming in a particular language.

Related Glossary Terms

Index

Drag related terms here

Find Term

iBooks Author

Page 50: First Edition Beginning Java - Techie Sparksdownloads.techbarrack.com/books/programming/Beginning-Java.pdfprogram is made up of different small parts for faster execution. Programs

JavaA programming language developed by james gosling at sun microsystems in 1995.

Related Glossary Terms

Index

Drag related terms here

Find Term

iBooks Author