Chapter 1 FUNDAMENTALS OF OBJECT ORIENTEDPROGRAMMING 1.1 INTRODUCTION OOP Object Oriented Programming OOP is an approach to standardize the programs by creating partitioned memory area f
Trang 2Java Learn The Basic In 3 Days
David Chang
Trang 32.2 Basic features of Java
2.3 Compiler and Interpreter
5.3 Declarations while using streams
5.4 Decision Making In Java
Trang 47.3 Passing an Array to a Method
7.4 Basic Operations on Java : Searching and Sorting
8 Classes, Objects and Methods
8.6 Method Overloading 8.7 Method Overriding
9 Interfaces and Packages
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
Trang 5Chapter 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 Ithas been developed to increase the programmer's productivity and also toovercome the traditional approach of programming The different ObjectOriented 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 ofobjects
Data can be easily modified without any change in the method
Trang 61.2 OBJECTS AND CLASSES
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
Trang 7Class 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 representthe different objects of the class Rainbow
Similarly, we can consider a class named fruit where apple, mango, orangeare 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 classfruit
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 itemsand functions to promote abstraction The data members are accessed onlythrough 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 withoutknowing in details the internal mechanism of the system You can applybrake to stop the car, press accelerator to speed up the car and press clutch tochange the gears
Do you ever think what changes are taking place in the machinery part of theengine? The answer is simply No This act of driving a car is termed as
abstraction.
Trang 81.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 theywill not be accessible to the outside world except by using them through therelated methods
It is the most important feature of a class The functions used in a class canonly access the data items These functions provide interface between dataitems 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” Supposeyou have developed a method to perform the addition then it will find thesum of two numbers passed to the method In case the passed arguments arestrings, 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
Trang 9class 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
Trang 10Chapter 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, veryoften 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 functionsare declared and defined with the class
Java programs can create Applets (the programs which run on browsers)
Web-Java is case sensitive language It distinguishes the upper case andlower case letters
2.3 COMPILER AND INTERPRETER
All high level languages need to be converted into machine code so that thecomputer understands the program after taking the required inputs
The conversion of high-level language to machine-level language can be
Trang 11done in two possible ways It can be done either by using a Compiler or anInterpreter.
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 longertime to execute successfully
SOURCE CODE -> COMPILER/INTERPRETER -> MACHINE CODE
However, if all the instructions are converted to machine level language atonce and all the errors are listed together, then the software is known as
Compiler This process is much faster but sometimes it becomes difficult todebug 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 iscompiled 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 neededwhich translates the byte code to machine code
Trang 12Java machine code varies from different platforms like Windows 98, UnixSystem, etc Hence, JVM acts as a virtual processor and converts the bytecode 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.
Trang 132.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 developingapplications and applets
java.lang : to support classes containing String, Character,
Math, Integer,Thread etc
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 as square
roots (integer & decimal both)
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 thesystem These words cannot be applied as a variable name in any program.Java also has reserved words Some of the reserved/key words are listedbelow:
Trang 14catch if new package goto
while short public private float
Comment Statements in Java Programming
There are some cases where it becomes difficult for a user to understand thelogic applied in a program particularly when any other person has developed
it In such cases, the programmer keeps mentioning the purpose and actionbeing 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 */
Trang 15Output 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 theyare to be separated with ‘+’ (plus) sign
Trang 16Chapter 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 bestored 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 appropriatedata 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
Trang 17can depend on stored integer type that we choose It does not contain decimalpoint 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 doublen=0.0006547839;
Character Type
It stores character constants in the memory and contains a single
character A character is enclosed in single quotes (‘ ‘).Strings areenclosed in double quotes(“ “)
The character types in Java are as follows:
Non Numeric Character
type
Bit Size Format
Single character char 16 bits(2 bytes) char c; c=’A’;
char d; d=’*’;char c =’A’;More than one
Trang 18Boolean Type
Boolean data types are used to store values with two states: true orfalse These are non-figurative constants You can use Boolean typevariable 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 falsewithout 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
Trang 19}
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 yousaved the class Assume it's C:\
Type 'javac MyFirstJavaProgram.java' and press enter to compileyour code If no errors in code then command promptwill process to next line Then, type ' javaMyFirstJavaProgram ' 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
Trang 20Real Literals : They represent numbers with decimal points e.g 24.6,0.0045, etc.
Character Literals : The constants which are alphanumeric in nature arecalled 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 anamed memory location, which contains a value A variable can betreated by any combination of letters without spaces We can declaremore 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;
The operators are the symbols used to perform arithmetical or logical
operations in Java programming e.g +,-,*,/,||,&&,<,> etc.
Trang 21Note: We have Detail Explain about Operators in Next Chapter
Trang 22Chapter 4 OPERATORS AND EXPRESSIONS
An operator is basically a symbol or token, which performs logical orarithmetical operations and gives meaningful result The values which areinvolved in the operation, are termed as operands
For example :[ a + b * c] where a b and c are operands, + and * are theoperators
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.
Trang 23Unary Increment and Decrement Operators:
Unary Increment Operator (++) increases the value of an operand by onewhereas Unary Decrement Operator ( ) decreases the value of anoperand 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
Trang 24When 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
Binary Arithmetic Operators
An arithmetic operator, which deals with two operands is known asBinary Arithmetic Operators e.g a + b, a – b, etc
Ternary Operators (Conditional Operator)
Ternary Operators takes three operands It is also called conditionaloperator because the value assigned to a variable depends upon a logicalexpression
Syntax: variable = (test expression)? Expression 1:Expression 2;
The variable contains the result of expression 1 if the test condition is trueotherwise 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;
Trang 25Test condition Expression 1 Expression 2
Since, the test condition is false, it will operate expression 2 whichenables value 12 to be stored in max Hence, max = 12
Java uses logical operators AND(&&), OR(||) or NOT(!) These operators
yield 1 or 0 depending upon the output of different expressions.
Trang 26An expression which includes different types of variables or values toyield a result is called as Mixed Expression.
e.g int a; float b; double c;
double z = a + b * c;
Implicit Type Conversion
In mixed expression, the data type of the result gets convertedautomatically into its higher type without intervention of the user This
type conversion is known as Implicit Type Conversion.
Explicit Type Conversion
When the data type gets converted to another type after user intervention,the type conversion is known as Explicit Type Conversion
e.g int a, b;
float x = (float) (a+b);
Trang 27Chapter 5 CONDITIONAL AND DECISION MAKING STATEMENTS
In the first part of the chapter, we will discuss about unconditionalstatements, which will help to give a detailed idea of writing Javainstructions in a program
In order to perform a specified task in a program you need to providesome values, which can be used during execution of the program Thestatement, which accepts the values from the users, is known as inputstatement Java provides various ways to use input statements inprogramming They are as follows:
By assigning the values
By using input streams
By using Command line arguments
5.1 PROGRAMMING BY USING ASSIGNMENT STATEMENT
By using assignment statement, you can take values of data of your own
or mentioned in the program
Example: A program in Java to find the sum of two numbers using
Trang 28}
Output:
The sum of the two numbers = 60
5.2 PROGRAMMING USING STREAMS
Package in Java is basically a collection of classes Each package
includes related built-in functions, which may be used while developing
programming logic
Buffer
CPU or processor is the fastest device in a computer Other peripheraldevices are comparatively slower then processor Due to speeddifferences it becomes difficult to have data communication betweenprocessor and peripheral devices Hence, a high speed memory is appliedbetween I/O devices and processor used as a bridge to synchronize theirspeeds This high-speed temporary storage (cache memory) is termed asBuffer You need to activate the buffer before any input/output operation
Activating Buffer in Java
InputStreamReader <object name1> = new InputStreamReader (System.in);
BufferedReader <object name2> = new BufferedReader (<object name1>)
OR
DataInputStream<object name> = new DataInputStream(System.in);
Main function
The next step is to declare a main function as given below:
public static void main (string args[])throws IOException
The main function is issued to execute a program Thereafter, throwsIOException eliminates I/O errors in the program(if any) It passes areport on I/O errors to the exception handler of Java System
Trang 295.3 DECLARATIONS WHILE USING STREAMS
1 At first Java library package needs to be defined
Syntax: import java.io.*; or
import java.io.lang or may be both the packages
2 Two statements are essentially needed, when you are using Inputstream to activate buffer
DataInputStream in = new DataInputStream(System.in);
OR
public static void main(String args[])throws IOException
InputStreamReader read = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(read);
3 A message is to be displayed before Input statement in order to enable
input editor.
Syntax: System.out.println(“Enter your name”);
4 The Syntax of Input statement in Java programming:
n = Integer.parseInt(in.readLine());
This statement will accept only integer from the user whereas :
n = Float.parseFloat(in.readLine());
will accept fractional numbers from the user
Example: A Java program to accept perpendicular and base of a Rightangled triangle
calculating and displaying the hypotenuse and area of the triangle
Trang 30float p,b;
double area=0,hyp=0;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println(“Enter perpendicular and base”);
5.4 DECISION MAKING IN JAVA
Sometimes our program needs to take a decision based on whether a
particular condition has occurred or not Then our program will executecertain statements based on this decision
Decision making in Java can be achieved using any of the following
You can use if statement to check a specified condition It performs a course
of action if the condition is true otherwise, the action is ignored
Syntax: if(condition)
Trang 31{ Statement 1
Trang 32Statements that need to be executed always
Example: public class IfElseStatement
{
{
Trang 33//Declaring a variable "test" and initializing it with a value 10
If none of the conditions are true, the code inside the else block will execute.Example:
Trang 34Statements execute if none of the conditions in condition-x, conditiony,
…condition-z are true
Trang 35Nested if…else statement
When you combine multiple if / if-else /if-else-if ladders then lot sequencedecisions are involved You have to take care of program executes,
instructions when sequence conditions are encountered
/*This block will be executed only if
a is equal to 5 and b is equal to 3 */
System.out.println("Hi, a is 5 and b is 3");
}
Trang 36else
{
/*This block will be executed only if
a is equal to 5 and b is some value other than 3 */
System.out.println("Hi, a is 5 and b is some value other than 3");
/*This block will be executed only if
a is equal to 3 and b is equal to 2 */
System.out.println("Hi, a is 3 and b is 2");
}
}
else
Trang 37{
/*This block will be executed only if
a is some value other than 5,4,3*/
System.out.println("Hi, a is some value other than 5,4,3");
}
}
}
Output: Hi, a is 3 and b is 3
Switch case statement
Switch case statement is a multiple branching statement In this system thecontrol jumps to perform a particular action out of a number of actionsdepending upon a switch value A switch statement is associated with anumber of blocks Each block is defined under a specific case The controlgets transferred to a particular case, which matches with the given switchvalue Each case ends with a break statement, which can be used as a caseterminator Break statement passes the control out of the switch block You can use a special case called default case which is automaticallyfollowed if no case matches with the given switch value
Example: A Java program to accept two numbers and find the sum,
difference or product according to user’s choice
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println(“Enter two numbers”);