Beginning Java
-
Upload
nayan-seth -
Category
Documents
-
view
224 -
download
0
Transcript of Beginning Java
-
8/3/2019 Beginning Java
1/50
BeginningJava
iBooks Author
-
8/3/2019 Beginning Java
2/50
1In this chapter we will talk
about who developed java
and what is java?
Introduction To Java
iBooks Author
-
8/3/2019 Beginning Java
3/50
2
James GoslingThe picture you see on left is of JAMES GOSLING. He is theone who developed Java at Sun Microsystems in 1995.
His weblog - http://nighthacks.com /
Section 1
Inventor of Java?
iBooks Author
http://nighthacks.com/http://nighthacks.com/ -
8/3/2019 Beginning Java
4/50
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 OOPs Principle. Every program in java
has to be written in classes.
Section 2
What is Java?
iBooks Author
-
8/3/2019 Beginning Java
5/50
2In this chapter we will learn
about the IDE that can be
used for coding in java.
IDE For Java
iBooks Author
-
8/3/2019 Beginning Java
6/50
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 ForJava Developers
iBooks Author
-
8/3/2019 Beginning Java
7/50
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
http://www.eclipse.org/downloadshttp://www.eclipse.org/downloadshttp://www.eclipse.org/downloadshttp://www.eclipse.org/downloads -
8/3/2019 Beginning Java
8/50
3In this chapter we will talk
about the basic oops
features in java. JUSTBASIC.........
Basic OOP Terms
iBooks Author
-
8/3/2019 Beginning Java
9/50
Features
1. Classes & Objects
2. Data Abstraction
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing
8
OOPsObject 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 OOPs?
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 OrientedProgramming
iBooks Author
-
8/3/2019 Beginning Java
10/50
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
Lets consider a dog. A dog has state - name, color, breed and
behavior - fetching, barking, etc.
Lets 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
-
8/3/2019 Beginning Java
11/50
10
What is A Class?In real world there are thousands 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
-
8/3/2019 Beginning Java
12/50
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
-
8/3/2019 Beginning Java
13/50
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: lets 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
-
8/3/2019 Beginning Java
14/50
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
-
8/3/2019 Beginning Java
15/50
14
InheritanceInheritance can be defined as the process where one object of
one class acquires the properties of object/objects of another
class.
eg: lets 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
-
8/3/2019 Beginning Java
16/50
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
-
8/3/2019 Beginning Java
17/50
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
-
8/3/2019 Beginning Java
18/50
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
-
8/3/2019 Beginning Java
19/50
4In this chapter we will talk
about the basic terms used
in a java program.
Basic Terms In AJava Program
iBooks Author
-
8/3/2019 Beginning Java
20/50
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 theposition 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 inthe program.
Section 1
Access Specifiers
iBooks Author
-
8/3/2019 Beginning Java
21/50
20
protected
protected methods and fields can only be accessed within thesame 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 sameclass 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
-
8/3/2019 Beginning Java
22/50
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 whichthe 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
-
8/3/2019 Beginning Java
23/50
5Lets write out first java
program.
Hello Java!
iBooks Author
-
8/3/2019 Beginning Java
24/50
23
Programclass test{
public static void main(String args[])
{
System.out.print(Hello Java);
}
}
Output
Hello 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
-
8/3/2019 Beginning Java
25/50
6Lets Comment
Comments
iBooks Author
-
8/3/2019 Beginning Java
26/50
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 Types
1. 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 signand a forward slash (*/).
eg: /**hey this is a comment */
Section 1
Comments
iBooks Author
-
8/3/2019 Beginning Java
27/50
7What variables and
datatypes? What is that?
Variables &Datatypes
iBooks Author
-
8/3/2019 Beginning Java
28/50
27
What is that????
Variables are assigned with some data. They are basically
given names. Names are easier to remember than values.
Lets try remembering our mathematic lectures where we use to
have word problems. There many times we were given values.
Lets 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 lets 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
-
8/3/2019 Beginning Java
29/50
28
What Are Datatypes?
Now we just talked about variables but java doesnt understandwhether 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
-
8/3/2019 Beginning Java
30/50
-
8/3/2019 Beginning Java
31/50
30
We are going to talk only about primitive datatypes.
Data
TypeType Bit
Space
Req
Signed/
UnsignedRange
Default
Value
bytebyte-length
integer8 1 byte Signed -128 to 127 0
shortshort-length
integer16 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
float
single
precision
decimal
32-bitIEEE754
4 bytes Signed
1.40129846432481707e-45 to
3.40282346638528860e+38 (positive
or negative)
0.0f
double
double
precision
decimal
64-bitIEEE754
8 bytes Signed
4.94065645841246544e-324d to
1.79769313486231570e+308d
(positive or negative)
0.0d
boolean True/False 1 bit FALSE
charsingle
character
16-bitUnicod
echaract
er
2 bytes Unsigned 0 to 65,535 \u0000
iBooks Author
-
8/3/2019 Beginning Java
32/50
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
-
8/3/2019 Beginning Java
33/50
32
Another Reason...You Could Say
I 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
-
8/3/2019 Beginning Java
34/50
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.
String
String 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 Value
Basically 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.
Syntax
datatype_namevariable_name = value;
eg: byte x = 10;
iBooks Author
-
8/3/2019 Beginning Java
35/50
8Lets learn how we can
import packages in java.
Java Packages
iBooks Author
-
8/3/2019 Beginning Java
36/50
35
What is it???Huh??
Just like in C++ where we have to include header files, in javawe import packages.
Benefits Of Packages In Java
The 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.*;
Syntax
eg: importjava.package_name.class_name;
import java.util.Scanner;
importjava.package_name.*;
this imports all classes from that particular package
import java.io.*;
Section 1
Java Packages
iBooks Author
-
8/3/2019 Beginning Java
37/50
9Ahh..Escape....What!!!
Escape Sequences
iBooks Author
-
8/3/2019 Beginning Java
38/50
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.
Syntax
System.out.print(\n hey);
iBooks Author
-
8/3/2019 Beginning Java
39/50
10What huh!!!!
Type Casting &Type Conversion
iBooks Author
-
8/3/2019 Beginning Java
40/50
39
Introduction
Now 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 Conversion
Now lets 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
-
8/3/2019 Beginning Java
41/50
-
8/3/2019 Beginning Java
42/50
41
Type Casting
We 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.
Syntax
data_typevariable_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;
}
}
Explanation
int 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
-
8/3/2019 Beginning Java
43/50
11Learn how to take input
from user in JAVA.
Taking Input FromUser
iBooks Author
-
8/3/2019 Beginning Java
44/50
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
-
8/3/2019 Beginning Java
45/50
44
Scanner
Scanner is one the most common method used for taking inputfrom user in java.
We import the java.util package with class Scanner.
import java.util.Scanner;
Syntax
Scanner 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
-
8/3/2019 Beginning Java
46/50
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
-
8/3/2019 Beginning Java
47/50
46
BufferedReader
This method of taking input from user is very commonly taughtto 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
-
8/3/2019 Beginning Java
48/50
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
Explanation
import java.io.* - we want 3 classes from the java.io package ieBufferedReader, 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
-
8/3/2019 Beginning Java
49/50
IDE
Integrated Development Environment. It is basically a platform used for programming
in a particular language.
Related Glossary Terms
Index
Drag related terms here
iBooks Author
-
8/3/2019 Beginning Java
50/50
Java
A programming language developed by james gosling at sun microsystems in 1995.
Related Glossary Terms
Index
Drag related terms here
iBooks Author