Tải bản đầy đủ (.pdf) (79 trang)

Java learn java in 3 days (david chang programming )

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (575.82 KB, 79 trang )


Java
Learn The Basic In 3 Days
David Chang


Contents
1. Fundamentals of Object Oriented Programming
1.1 Introduction (OOP)
1.2 Objects and Classes
1.3 Data Abstraction
1.4 Encapsulation
1.5 Polymorphism
1.6 Inheritance
2. Introduction to Java
2.1 History of Java
2.2 Basic features of Java
2.3 Compiler and Interpreter
2.4 The JVM
2.5 The Java Runtime Environment (JRE)
2.6 The Java Development Kit (JDK)
2.7 Reserved Words
3. Data Types and Tokens in Java
3.1 Data Types
3.2 Java Tokens
4. Operators and Expressions
4.1 Types of Operators
4.2 Expressions
5. Conditional and Decision Making Statement
5.1 Programming by using assignment statement
5.2 Programming using Streams


5.3 Declarations while using streams
5.4 Decision Making In Java
6. Looping
6.1 Looping Structure
6.2 Types of Loops
7. Array
7.1 Types of Array
7.2 Declaration of an Array


7.3 Passing an Array to a Method
7.4 Basic Operations on Java : Searching and Sorting
8. Classes, Objects and Methods
8.1 Classes in Java
8.2 Creating an Object
8.3 Methods
8.4 Creating Methods
8.5 Method Calling
8.6 Method Overloading 8.7 Method Overriding
9. Interfaces and Packages
9.1 Interfaces
9.2 Packages in Java
9.3 Advantages of Java Package
10. Constructors
10.1 Types of Constructors
11. Thread and Multithread in Java
11.1 Lifecycle of a Thread
11.2 Commonly used methods of Thread class
11.3 Creating Thread
11.4 Multithreading

12. Handling Exceptions and Errors
12.1 Exception Handling with try-catch
12.2 Exception Handling with throws keyword
12.3 Advantages of Exception Handling in Java
12.4 Errors
12.5 Difference between Errors and Exceptions
13. Some Questions and Answers


Chapter 1 FUNDAMENTALS OF OBJECT ORIENTED
PROGRAMMING
1.1 INTRODUCTION (OOP)
Object Oriented Programming (OOP) is an approach to standardize the
programs by creating partitioned memory area for both data and method. It
has been developed to increase the programmer's productivity and also to
overcome the traditional approach of programming. The different Object
Oriented Programming languages are C++, Java, Simula-67, etc.
An Object Oriented Programming (OOP) allows the data to be applied
within designated program area. It gives more significance to data rather
than Methods which means it also provides the reusability feature to
develop productive logic.

FEATURES OF OBJECT ORIENTED PROGRAMMING (OOP)
The objects can be used as a bridge to have data flow from one method
to another.
It gives importance to data items rather than methods.
It makes the complete program simpler by dividing it into a number of
objects.
Data can be easily modified without any change in the method.


PRINCIPLES OF (OOP)
Objects
Classes
Data Abstraction
Encapsulation
Data Hiding
Inheritance
Polymorphism


1.2 OBJECTS AND CLASSES
OBJECTS
Object is a unique entity which contains data and methods (characteristics
and behavior) together in an Object Oriented Programming (OOP) Language.

Example: Let us consider the real world objects, which are visible before us.
Any object in the real world can possess the following characteristics:
It is visible.
It can be described easily.
You can observe that the above mentioned criteria has unique identity,
definite state, or characteristics and behaviors. For example consider an
object Bed:
It has the following characteristics:
It has four legs.
It has a plain top.
And the behaviors are:
It is used to sleep.
It is used to sit.
In Payroll system, an employee may be taken as an example of object where
characteristics are name, designation, basic pay and behavior as calculating

gross pay, provident fund, printing pay slip, etc.


CLASSES
Class is a set of different objects. Class can contain fields and methods to
explain about the behavior of an object. Each object of a class possesses
same attributes and behavior defined within the same class. Class is also
termed as Object factory.
For Example: If Rainbow is the class then the colors in the rainbow represent
the different objects of the class Rainbow.
Similarly, we can consider a class named fruit where apple, mango, orange
are members of the class fruit.
If fruit is defined as a class, then the statement:
fruit apple = new fruit(); will create an object apple belonging to the class
fruit.
1.3 DATA ABSTRACTION
Abstraction refers to the act of representing essential features (relevant
data) without including background details in order to reduce
complexity and increase efficiency.
Abstraction is the absolute property of a class. The class binds the data items
and functions to promote abstraction. The data members are accessed only
through the related methods. A class uses the property of abstraction called as
abstract data type.
For Example: For driving a car, you only use the essential features without
knowing in details the internal mechanism of the system. You can apply
brake to stop the car, press accelerator to speed up the car and press clutch to
change the gears.
Do you ever think what changes are taking place in the machinery part of the
engine? The answer is simply No. This act of driving a car is termed as
abstraction.



1.4 ENCAPSULATION
Encapsulation is the system of wrapping up of data and functions into a
single unit (called class).
For Data Hiding Encapsulation run on an important OOP concept. In Object
Oriented Programming (OOP), data cannot move freely from method to
method. They are kept in the corresponding classes in such a way that they
will not be accessible to the outside world except by using them through the
related methods.
It is the most important feature of a class. The functions used in a class can
only access the data items. These functions provide interface between data
items of the objects and the calling program.
Such insulation of data, which cannot be accessed directly outside class
premises although they are available in the same program, is known as
DATA HIDING.
1.5 POLYMORPHISM
The literal meaning of Polymorphism is “available in many forms”. Suppose
you have developed a method to perform the addition then it will find the
sum of two numbers passed to the method. In case the passed arguments are
strings, the function will produce the concatenated (joined) string.
Hence, Polymorphism is the ability of different objects to respond, each
in its own way, to identical messages. It allows the use of different
internal structure of the object by keeping the same external interface.
1.6 INHERITANCE
Inheritance can be defined as the process by which objects of one class
can link and share some common properties of objects from another
class.
An object of a class acquires some properties from the objects of another



class. Superclass or base class is a class that used as basis for inheritance.
Subclass or derived class is known as a class that inherits from a superclass.

BENEFITS OF OBJECT ORIENTED PROGRAMMING (OOP)
Some benefits of OOP are as listed below:
You can create different modules in your project through objects.
You can extend the use of existing class through inheritance.
Using the concept data hiding can generate secured program.
It is highly beneficial to solve complex problems.
It is easy to modify and maintain software complexity.


Chapter 2 INTRODUCTION TO JAVA
2.1 HISTORY OF JAVA
Java programming language was originally developed by James Gosling at
Sun Microsystems (Broomfield, Colorado, USA) and released in 1995 as a
core component of Sun Microsystems' Java platform. This language was
initially called Oak (named after the Oak trees outside Gosling’s office).The
platform independence is one of the most significant advantage that JAVA
has over other languages.
JAVA encapsulates many features of C++. Originally JAVA was designed to
execute applets, downloaded while Web browsing. But gradually, the
language has been gaining wide acceptance as a programming language, very
often replacing C or C++.
2.2 BASIC FEATURES OF JAVA
JAVA possesses the following features:
Java is not a purely Object Oriented Programming language.
Java programs are both compiled and interpreted.
It can access data from a local system as well as from net.

Java programming is written within a class. The variables and functions
are declared and defined with the class.
Java programs can create Applets (the programs which run on Webbrowsers).
Java is case sensitive language. It distinguishes the upper case and
lower case letters.
2.3 COMPILER AND INTERPRETER
All high level languages need to be converted into machine code so that the
computer understands the program after taking the required inputs.
The conversion of high-level language to machine-level language can be


done in two possible ways. It can be done either by using a Compiler or an
Interpreter.
The software, by which the conversion of the high level instructions is
performed line by line to machine level language, is known as an Interpreter.
If an error is found on any line, further execution stops till it is corrected.
This process of error correction is much easier but the program takes longer
time to execute successfully.
SOURCE CODE -> COMPILER/INTERPRETER -> MACHINE CODE
However, if all the instructions are converted to machine level language at
once and all the errors are listed together, then the software is known as
Compiler. This process is much faster but sometimes it becomes difficult to
debug all the errors together in a program.
The Java source code and Java bytecodes are compiles in javac command.
Compilation Syntax: javac filename.java

2.4 THE JVM
JAVA is a high level language (HLL)and the program written in HLL is
compiled and then converted to an intermediate language called Byte Code.
Byte code makes a Java program highly portable as its Bytes code can easily

be transferred from one system to another. When this Byte code is to be run
on any other system, an interpreter, known as Java Virtual Machine is needed
which translates the byte code to machine code.


Java machine code varies from different platforms like Windows 98, Unix
System, etc. Hence, JVM acts as a virtual processor and converts the byte
code to the machine code for concerning platform. That is why it is called
Java Virtual Machine.
Three notions of JVM are: Implementation, instance and specification. The
specification document describes what’s required of JVM implementation.
Single specification ensures all implementation are interoperable.
Implementation program meets the requirements of the JVM specification.
JVM Instance is implementation running in process that executes a program
compiled into Java bytecode.
Thus, the Java machine uses compiler and interpreter too.
2.5 JAVA RUNTIME ENVIROMENT (JRE)
Java Runtime Environment is used to provide runtime environment. It is
the implementation of JVM. It contains other files and set of libraries
that used at runtime by JVM. It is a software package that contains what is
required to run a Java program. It includes together Java Class Library
Implementation and Java Virtual Machine implementation. The Oracle
Corporation, which owns the Java trademark, distributes a Java Runtime
environment with their Java Virtual Machine called HotSpot.


2.6 JAVA DEVELOPMENT KIT (JDK)
Java Development Kit (JDK) contains JRE and development tools. JDK
Tools such as the compilers and debuggers are necessary for developing
applications and applets.

Java Libraries in JDK 1.3
Java Development Kit (JDK) contains a Java Class Library for different
purposes. Some useful packages in it are mentioned below:
java.io : to support classes to deal with input &
statements.

output

java.lang : to support classes containing String,
Math, Integer,Thread etc.

Character,

java.net : to support classes for network related operations and
dealing with URL (Uniform Resource Locator)
java.txt : for supporting text elements such as date, times and
currency etc.
java.math : to support mathematical functional such
roots (integer & decimal both)

as square

java.applet : to support classes to generate applet – specific
environment
java.awt : to support abstract window tool kit and managing GUI
(Graphic User Interface)
2.7 RESERVED WORDS
Reserved words or keywords are those words which are preserved with the
system. These words cannot be applied as a variable name in any program.
Java also has reserved words. Some of the reserved/key words are listed

below:
case
do
try

switch
break
const

int
double
long

void
import
class

default
boolean
char


catch
for
while

if
else
short


new
byte
public

package
static
private

goto
throws
float

Comment Statements in Java Programming
There are some cases where it becomes difficult for a user to understand the
logic applied in a program particularly when any other person has developed
it. In such cases, the programmer keeps mentioning the purpose and action
being taken in different steps by applying comment statement in the program.
There are three ways to give a comment in Java programming.
1. //

: used for single line comment

2. /* comments to be written */ : used for multi line comment
3. /** documenting comment */


Output Statement in Java Programming
System.out.println() and System.out.print() are the statements that are used
to get the output of the program or to display messages on the screen.
While using System.out.println() statement, the cursor skips the line and

passes to the next line after displaying the required result.
And, when you use System.out.print() statement, the cursor remains on the
same line after displaying the result.
Syntax: System.out.println(“Welcome to Java”);
System.out.println(“The product of two numbers is” +a);

Note:
The message is to be written within double quotes (“ “)
enclosed
within braces.
When a message is to be displayed along with a variable, then they
are to be separated with ‘+’ (plus) sign.


Chapter 3 DATA TYPE AND TOKENS IN JAVA
3.1 DATA TYPES
Data types are predefined types of data, which are supported by the
programming language. It specifies the size and type of values that can be
stored in a variable. In Java Programming we have to deal with various types
of data, hence it becomes necessary for a programmer to select an appropriate
data type according to the data taken in a program.
The data type has been divided into two types:
Primitive Type
Non-Primitive Type

Primitive Data Types

Primitive data types are pre-defined or built-in data types, which are
independent of any other type. For eg. int, long, float, double etc.
Integer Type

Integer types can hold whole numbers such as 123 and −96. The values size


can depend on stored integer type that we choose. It does not contain decimal
point. There are two types of declarations under this heading:
int : applied for short integer number.
Bit size -> 32 bits, Format -> int a; a=10; or int a=10;
long : applied for large integer number.
Bit size -> 64 bits, Format -> long b; b=345678; or
long b=345678;
Floating Type
Floating point data types are used to represent numbers with a
fractional part. There are two types of declarations under this heading:
float : applied for small range of decimal values.
Bit size -> 32 bits, Format -> float m; m=32.65; or float m=32.65;
double : applied for wide range of decimal values.
Bit size -> 64 bits, Format -> double n; n=0.0006547839; or
n=0.0006547839;

double

Character Type
It stores character constants in the memory and contains a single
character. A character is enclosed in single quotes (‘ ‘).Strings are
enclosed in double quotes(“ “).
The character types in Java are as follows:
Non Numeric
Single character

More than one

character/a
word/a sentence

Character
type
char

String

Bit Size

Format

16 bits(2 bytes) char c; c=’A’;
char d; d=’*’;
char c =’A’;
More than 16
String a;
bits
a=”College”;


Boolean Type
Boolean data types are used to store values with two states: true or
false. These are non-figurative constants. You can use Boolean type
variable to set true or false in order to ensure whether a logical
condition is satisfied or not. It assumes one of the values true or false
without quotes.
For Example: boolean flag=true; or boolean flag=false;
Non-Primitive Data Type


Classes
A class, in the context of Java, are templates that are used to create
objects, and to define object data types and methods.
For Example:
public class MyFirstJavaProgram {
/*
This is my first java program.
This will print ‘Welcome’ as the output.
*/
public static void main (String[] args){
System.out.println(“Welcome”); // prints Welcome


}

}
Let's look at how to save the file, compile, and run the program−
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you
saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile
your code.
If no errors in code then command prompt
will process to next line.
Then, type ' java
MyFirstJavaProgram ' and press enter to run your program.
You will be able to see ' Welcome ' printed on the window.
We will study later about Arrays in chapter 7

3.2 JAVA TOKENS
Each individual character used in a java statement is known as Java
Token.
Types of Java Tokens
Literals
Identifiers
Assignments
Punctuators
Operators
Literals (Constants)
These are the constants used in a Java program. Java uses the literals
classified in the following ways:
Integer Literals : These are the whole numbers having positive or
negative values. e.g. 15, 256,etc.


Real Literals : They represent numbers with decimal points. e.g. 24.6,
0.0045, etc.
Character Literals : The constants which are alphanumeric in nature are
called character literals. e.g. ‘A’, ‘b’, ‘1’, ‘*’ etc.
String Literals : String is a set of alphanumeric characters.
e.g. “Year 2017”, etc.
Identifiers (Variables)
Identifiers are also called variables in Java programming. A variable is a
named memory location, which contains a value. A variable can be
treated by any combination of letters without spaces. We can declare
more than one variables of the same type in a statement.
Syntax: datatype variable name;
e.g. int a; float a,b,c;
Assignments

Assignment token assigns the value on its right to the operand on its left.
To assign object references operator can also be used.
e.g. int speed = 0; int gear = 1;
Punctuators
Punctuators are the punctuation signs used in Java. Some punctuators are
: ; , ? etc.
Separators
These are special characters that are used in Java to separate the
characters or variables.
e.g. (,),{,},[,] etc.

Operators
The operators are the symbols used to perform arithmetical or logical
operations in Java programming. e.g. +,-,*,/,||,&&,<,> etc.


Note: We have Detail Explain about Operators in Next Chapter


Chapter 4 OPERATORS AND EXPRESSIONS
An operator is basically a symbol or token, which performs logical or
arithmetical operations and gives meaningful result. The values which are
involved in the operation, are termed as operands.
For example :[ a + b * c] where a b and c are operands, + and * are the
operators.
4.1 TYPES OF OPERATORS
Basically, there are three types of operators in Java which are as follows:
Arithmetical
Relational
Logical

ARITHMETICAL OPERATORS
The operators, which are applied to perform arithmetical
calculations in a program, are known as arithmetical operators like
+,-,*,etc.
Arithmetical Expression:
An arithmetical expression may contain variables, constants and
arithmetical operators together to produce a meaningful result.
e.g. a+b,x-10,b*b-4*a*c etc.
Arithmetical Statement:
If an arithmetical expression is assigned to a variable then it is known as
an arithmetical statement.
Syntax: Variable = Arithmetical Expression;
e.g. x = a + b, z=b*b-4*a*c
Types of Arithmetical Operators
Unary Operator


Binary Operator
Ternary Operator
Unary Operator
Unary operator can also be known as arithmetical operator which can be
applied with a single operand. e.g. +,-,++ etc.
Unary Increment and Decrement Operators:
Unary Increment Operator (++) increases the value of an operand by one
whereas Unary Decrement Operator (--) decreases the value of an
operand by one.
Example:
1. i = i + 1
By applying increment operator it can be written as i++ or ++i
2. j = j – 1

By applying decrement operator it can be written as j-- or --j
Unary Increment/Decrement Operators:
Prefix
Postfix
Prefix
When increment or decrement operators are applied before the operand, it
is known as prefix operators. This operator works on the principle
‘CHANGE BEFORE ACTION’. It means the value of the variable
changes before the action takes place.
Example : p = 5;
p = ++p * 4; gives the result 24 as p increases by 1 before the operation
performed.
p = --p * 4; gives the result 16 as p decreases by 1 before the operation is
being performed.
Postfix


When increment or decrement operators are applied after the operand, it
is known as postfix operators. This operator works on the principle
‘CHANGE AFTER THE ACTION’. It means the value of the variable
changes after performing the operation.
Example : p = 5;
p = p++ * 4; gives the result 20 as p increases by 1 after the operation
performed.
p = p-- * 4; gives the result 20 as p decreases by 1 after the operation is
being performed.
Binary Arithmetic Operators
An arithmetic operator, which deals with two operands is known as
Binary Arithmetic Operators. e.g a + b, a – b, etc.
Ternary Operators (Conditional Operator)

Ternary Operators takes three operands. It is also called conditional
operator because the value assigned to a variable depends upon a logical
expression.
Syntax: variable = (test expression)? Expression 1:Expression 2;
The variable contains the result of expression 1 if the test condition is true
otherwise expression 2.
e.g. a = 4; b = 2;
max = (a>b)? a:b;
Here, the condition is true so the output will be 4 as the value of a is 4.
Nested Ternary Operator
You can use ternary operator in nested form as shown below :
e.g. Program to find maximum among three numbers:
int a = 4, b = 10, c = 2;
max = (a>b)? (a>c)? a:b

: (b>c)? b:c;


Test condition Expression 1

Expression 2

Since, the test condition is false, it will operate expression 2 which
enables value 12 to be stored in max. Hence, max = 12.
RELATIONAL OPERATORS
Relational operators compare the values of the variables and return a
boolean value in terms of ‘True’ or ‘False’ (i.e. 0 or 1). Java has
six relational operators that are < , > , <= , >= , == , and != .
LOGICAL OPERATORS
Java uses logical operators AND(&&), OR(||) or NOT(!). These operators

yield 1 or 0 depending upon the output of different expressions.
e.g. (a>b)&&(a>c),!(a==b)

Note: If a statement contains all the three logical operators then NOT
operator will perform first.
BITWISE OPERATORS
Bitwise operators use byte, short, int and long type operands. However,
float and double types are not allowed.
e.g. & - Bitwise AND
| - Bitwise OR
^ - Bitwise XOR
<< - Left Shift
>> - Left Shift
4.2 EXPRESSIONS
When you write a program in Java, it is necessary to represent the
arithmetical expressions into Java expressions.
Mixed Expression


×