Java Learn Java in 3 Days! (David Chang - Programming)
Java Learn Java in 3 Days! (David Chang - Programming)
Java Learn Java in 3 Days! (David Chang - Programming)
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 whats 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 & output
statements.
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 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 switch int void default
do break double import boolean
try const long class char
catch if new package goto
for else byte static throws
while short public private 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 double
n=0.0006547839;
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 Character Bit Size Format
type
Single character char 16 bits(2 bytes) char c; c=A;
char d; d=*;
char c =A;
More than one String More than 16 String a;
character/a bits a=College;
word/a sentence
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;
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.
Syntax: if(condition)
{
Statement 1
Statement 2
} Yes
No
If the statement is true the statements (statement 1 and statement 2) are
executed. If the condition is false the control ignores the statements and
passes to the next line of the program.
Example:
public class IfStatement
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 10
int test=10;
//Checking if "test" is greater than 5
if(test>5)
{
//This block will be executed only if "test" is greater than 5
System.out.println("Success");
}
//The if block ends.
System.out.println("Executed successfully");
}
}
Output: Executed successfully
if-else statement
Here if the condition is true, the code which is written inside the curly
brackets {} of the if block will be executed. If the condition is false, the
code which is written inside the curly brackets {} of the else block will be
executed.
Syntax:
if(condition)
{
Statements which will be executed if the condition is true
}
else
{
Statements which will be executed if the condition is false
}
Statements that need to be executed always
Example: public class IfElseStatement
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 10
int test=10;
//Checking if "test" is greater than 5
if(test>5)
{
//This block will be executed only if "test" is greater than 5
System.out.println("Success");
}
else
{
//This block will be executed only if "test" is not greater than 5
System.out.println("Failure");
}
//The if else blocks ends.
System.out.println("Executed successfully");
}
}
Output: Success
Executed successfully
if else-if ladder
Conditions are calculated from top. 1st if( condition-x) will evaluate and if its
true, the code inside the if block will execute else if(condition-x) is false then
else if (condition-y) will evaluate and If(condition-y) is true, then code inside
that else-if block will execute or else If(condition-y) is false then else
if(condition-z) will evaluate. This will go on like this.
If none of the conditions are true, the code inside the else block will execute.
Example:
if(condition-x)
{
Statements execute if condition-x is true
}
else if (condition-y)
{
Statements execute if condition-y is true
}
.
.
.
else if(condition-z)
{
Statements execute if condition-z is true
}
else
{
Statements execute if none of the conditions in condition-x, conditiony,
condition-z are true.
}
Statements execute always
Example:
public class IfElseIfLadder
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 2
int test=2;
if(test==1)
{
//This block will be executed only if "test" is equal to 1
System.out.println("Hello");
}
else if(test==2)
{
//This block will be executed only if "test" is equal to 2
System.out.println("Hi");
}
else if(test==3)
{
//This block will be executed only if "test" is equal to 3
System.out.println("Good");
}
else
{
System.out.println("No Match Found");
}
}
}
Output: Hi
Nested ifelse statement
When you combine multiple if / if-else /if-else-if ladders then lot sequence
decisions are involved. You have to take care of program executes, instructions
when sequence conditions are encountered.
Example:
public class NestedIf
{
public static void main(String args[])
{
//Declaring a variable a and initializing it with a value 5
int a=3;
//Declaring a variable b and initializing it with a value 3
int b=3;
if(a==5)
{
//This block will be executed only if "a" is equal to 5
if(b==3)
{
/*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");
}
else
{
/*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");
}
}
else if(a==4)
{
//This block will be executed only if a is 4
System.out.println("Hi, a is 4");
}
else if(a==3)
{
//This block will be executed only if "a" is 3
if(b==3)
{
/*This block will be executed only if a is equal to 3 and b is equal to 3 */
System.out.println("Hi, a is 3 and b is 3");
}
else if(b==2)
{
/*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
{
/*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 the
control jumps to perform a particular action out of a number of actions
depending upon a switch value. A switch statement is associated with a number
of blocks. Each block is defined under a specific case. The control gets
transferred to a particular case, which matches with the given switch value. Each
case ends with a break statement, which can be used as a case terminator. Break
statement passes the control out of the switch block.
You can use a special case called default case which is automatically
followed 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 users choice.
import java.io.*;
public class choice
{
public static void main(String args[])throws IOException
{
int a,b,ch;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println(Enter two numbers);
a=Integer.parseInt(in.readLine());
b=Integer.parseInt(in.readLine());
System.out.println(Enter 1 to add,2 to sub.,3 to mult);
System.out.println(Enter your choice);
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println(The sum of two nos.=+(a+b));
break;
case 2:
System.out.println(The diff. of two nos.=+(a-b));
break;
case 3:
System.out.println(The product of two nos.=+(a*b);
break;
default:
System.out.println(It is a wrong choice);
}
}
}
Chapter 6 LOOPING
6.1 LOOPING STRUCTURE
A looping structure contains the following parts:
Control Variable
Body of the loop
Test Condition
Step Value
6.2 TYPES OF LOOPS
Types of Loops in Java:
for loop
while loop
do while loop
for loop
We can perform any conditional repetitive type of flow very easily with the
help of for loop. It is used for a fixed number of iterations.
Syntax: for(initial value; final value; step value)
{
task to be performed
}
Example: A Java program to print all natural numbers from 1 to 5.
public class num
{
public static void main(String args[])
{
int a;
for(a=1;a<=5;a++)
{
System.out.println(a);
}
}
Output: 1
2
3
4
5
Nested for loop
When you apply a for loop within another for loop, the structure is termed as
nested for loop.
Example: A Java program to display the given pattern using for loop.
1
1 2
1 2 3
public class pattern
{
public static void main(String args[])
{
int a;
for(a=1;a<=3;a++)
{
for(b=1;b<=a;b++)
{
System.out.print(b);
System.out.println();
}
}
}
while loop
while loop repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body. The loop will continue
executing till the test condition is true.
Syntax: while(condition)
{
Statements to execute
}
Example: A program in Java to display a message on the screen 10 times by
using while statement.
public class msg
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(Welcome to Java Programming.);
i++;
}
}
Infinite while loop
In a while loop, if a user does not provide increment/decrement expression it
becomes infinite loop. The loop repeats infinitely as the test condition always
remains true.
int i=1;
while(i<=10)
{
s=s+i;
}
Nested while loop
Nested while loop can be known as while loop used within another while
loop.
Example: A Java program to display the given pattern using while loop.
1
1 2
1 2 3
public class pattern
{
public static void main(String args[])
{
a=1;
while(a<=3)
{
b=1;
while(b<=a)
{
System.out.print(b);
b++;
}
System.out.println();
a++;
}
Do-while loop
Do-while loop is used in a program where number of iterations is not fixed. In
this system, the control enters the loop without checking any condition, executes
the given steps and then checks the condition for further continuation of the
loop.
Thus, this type of loop executes the tasks at least once. If the condition is not
satisfied, then the control exits from the loop.
Syntax: do
{
task to do
}
while(condition);
Example: A Java program to find the factorial of 10.
public class factorial
{
public static void main(String args[])
{
int i,f;i=1;f=1;
do
{
f=f*i;
i++;
}
while(i<=10);
Sytem.out.println(The factorial of 10 = +f);
}
}
Use of break statement
Sometimes, it is needed to stop a loop suddenly when a condition is satisfied. A
break statement is used for unusual termination of a loop.
Syntax: while(condition)
{
execution continues
if(another condition is true)
break;
------;
------;
}
Use of continue statement
The statement continue, is just the opposite of break statement. As soon as the
continue statement is executed in a loop, the control skips rest of the statement
for that value and resumes for the next iteration.
Syntax: while(condition)
{
Statement 1
------;
------;
if(another condition)
continue;
Statement 2
-------;
-------;
}
Chapter 7 ARRAY
Arrays
In Java programming, you may need to structure the memory to store numerous
data items by applying minimum set of variables and by using optimum memory
space. It becomes necessary to store data within the memory in the most
convenient and economical way.
Java array is an object that contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of
elements in a java array.
Index based Array is in java,
Array First element is stored at 0 index.
First index
0 1 2 3 4 5 6 7 8 9
Array length is 10
7.1 TYPES OF ARRAY
Single Dimensional Array
Double Dimensional Array
Single Dimensional Array
Single Dimensional Array is also known when the elements are specified by a
single subscript,
Syntax to Declare Single Dimensional Array
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
7.2 DECLARATION OF AN ARRAY IN JAVA
Array in java can be Declare like:
arrayVar= new datatype[size];
Example of Single Dimensional Java Array
1. class TestSingleArray{
2. public static void main(String args[]){
3.
4. int a[]=new int[5]; //declaration and instantiation of int
5. a[0]=10; //initialization a[?] with numbers
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Output: 10
20
70
40
50
Instantiate and initializing the java array together can be declared as:
1. class Test1Instantiateandinitializating{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5}; //declaration, instantiation and initialization int
5.
6. //printing array
7. for(int i=0;i<a.length;i++) //length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Output:
33
3
4
5
7.3 PASSING AN ARRAY TO METHOD
We can pass the java array to method so that we can reuse the same logic on any
array.
1. class Test2PassingMethod{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,2,4,5};
14. min(a);//passing array to method
15. }}
Output:2
Double Dimensional Array
In such case, data is stored in row and column based index (also known as matrix form).
Syntax : dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate 2-dimensional array:
int[][] arr = new int[3][3];//3 row and 3 column
Example to initialize 2-dimensional array:
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of 2-dimensional array:
1. class Testarray3Dimensional{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Output: 1 2 3
2 4 5
4 4 5
7.4 BASIC OPERATIONS ON JAVA
Arrays provide the following basic operations:
Searching
Sorting
Insertion
Deletion
Merging
Search
It is a process to determine whether a given item is present in the array or not.
This can be done by two ways:
Linear Search
Binary Search
Linear Search
It is one of the simplest technique in which the searching of an item begins at the
start of an array(i.e. 0th position of the array). The process continues one another,
where each element of the array is checked and compared with a given data
item till the end of the array location is reached. This process is also called as
Sequential Search.
Binary Search
It is the another technique to search an element in the given array by using
minimum possible time. Searching takes place in either half of the array by
further dividing it into two halves.
However, the binary search can be applied only when the array elements are
sorted into a sequence(ascending/descending).It always compares the element to
be searched with the middle element of the sorted array. If the middle member is
smaller then, the search is carried out in upper half, otherwise the search
continues in the lower half. The middle element of the either half is compared
with the search item. This process is repeated till the search terminates.
18 32 50 56 65 79 88
0th 1st 2nd 3rd 4th 5th 6th
First Mid Last
Step 1: First=0,Last=6,Mid=(First+Last)/2=(0+6)/2=3
Step 2: num[Mid]=num[3]=55
55>31
Since, 55 is greater therefore search will take place in the first half of the array.
Step 3: Last=Mid-1 = 3-1=2
(In case, the number to be searched is greater than the mid value then,
First=Mid+1).
Mid=(First+Last)/2 = (0+2)/2=1
Num[Mid]= num[1]=31
18 32 50
0th 1st 2nd
First Mid Last
Sorting
It is a process of arranging data in a specified order which may be either
ascending or descending.
Selection Sort
Bubble Sort
Selection Sort
This is one of the techniques to sort the given data item in a specified
order(ascending/descending).
Suppose you have to arrange numbers in ascending orders from unsorted data.
Step 1: At first, the smallest number is selected through iteration from the
unsorted data list. This number is interchanged with the number at 0th position
(i.e. 16 comes from 6th position to 0th position and 45 goes to 6th position from 0th
position).
45 98 50 57 90 28 16 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 2: Find the next smallest element from 1st position onward(i.e.28).
Interchange it with 1st position element.
16 98 50 57 90 28 45 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 3: Find the next smallest element from 2nd position
onward(i.e.45).Interchange it with 2nd position element.
16 28 50 57 90 98 45 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 4: Find the next smallest element from 3rd position
onward(i.e.50).Interchange it with 3rd position element.
16 28 45 57 90 98 50 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 5: Find the next smaller element from 4th position onward(i.e.57).
Interchange it with 4th position element.
16 28 45 50 90 98 57 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 6: Find the next smaller element from 5th position onward(i.e.78).
Interchange it with 5th position element.
16 28 45 50 57 98 90 78
0th 1st 2nd 3rd 4th 5th 6th 7th
Step 7: Find the next smaller element from 6th position onward(i.e.90).
Interchange it with 6th position element.
16 28 45 50 57 78 90 98
0th 1st 2nd 3rd 4th 5th 6th 7th
Thus, the numbers are arranged in ascending order using Selection Sort.
Bubble Sort
This technique is most widely used for sorting elements in a single dimensional
array. In this technique, array is sequentially scanned several times and during
each iteration the pairs of consecutive elements are compared and interchanged
into a specific order(ascending/descending). It is an easy technique but
consumes lot of time when the number of exchanges is much high.
Technique to sort the numbers using bubble sort
Arranging the elements in ascending order:
10 7 25 4 12
0th 1st 2nd 3rd 4th
Elements 10 and 7 are compared. Both are interchanged as 10>7.
7 10 25 4 12
0th 1st 2nd 3rd 4th
Elements 10 and 25 are compared but not interchanged as 10<25.
7 10 25 4 12
0th 1st 2nd 3rd 4th
Elements 25 and 4 are compared and interchanged as 25>4.
10 7 4 25 12
0th 1st 2nd 3rd 4th
Elements 25 and 12 are compared and interchanged as 25>12.
Thus, the numbers are arranged in ascending order using Bubble Sort.
Insertion
To perform an insertion sort, begin at the left-most element of the array and
invoke Insert to insert each element encountered into its correct position. The
ordered sequence into which the element is inserted is stored at the beginning of
the array in the set of indices already examined.
Chapter 8 CLASSES, OBJECTS AND METHODS
8.1 CLASSES IN JAVA
A class is a blueprint from which individual objects are created.
Example: public class boy
{
String name;
int age;
void study(){
}
void hungry(){
}
void sleeping(){
}
}
A class contain any following variables type.
Local variables Local variables can be defined inside methods,
constructors or blocks.
Instance variables Variables declare within a class but outside any
method and Variables initialized within class are instantiated is Instance
variables. Variables can accessed from inside of any method, constructor
or blocks of particular class.
Class variables With the static keyword, within a class or outside
any method are Class variables.
8.2 CREATING AN OBJECT
An object is created from a class and new keyword is used to create new
objects.
Creating an object from a class there are three steps
Declaration A variable name with an object type.
Instantiation 'new' keyword used to create an object.
Initialization 'new' keyword followed by constructor. This call
initializes new object.
Example: public class Boy{
public boy(String name){
System.out.println(Name is: +name);
}
public static void main(String args[]){
Boy obj = new Boy(Ram);
}
}
Output:
Name is: Ram
8.3 METHODS
A program module used simultaneously at different instances in the program
is known as Methods.
8.4 CREATING METHOD
Syntax: public static int user(int a,int b){
//body
}
Here,
public static modifier
int return type
user name of the method
a, b formal parameters
int a, int b list of parameters
Example: public static int max(int a,int b){
int max;
if(a>b){
max=a;
}
else{
max=b;
}
return max;
}
this keyword in Java
Sometimes, in a member method it is needed to use the object on which the
method is called. Java system uses it with this keyword. The object on which
the method is called can be reffered in the method with this.
Example: class keyword
{
int a,b;
void getvalue(int p,int q)
{
a=p;
b=q;
}
void sum(keyword x, keyword y)
{
this.a=x.a+y.a;
this.b=x.b+y.b;
}
void display()
{
System.out.println(sum of a+a);
System.out.println(sum of b+b);
}
}
class calculate
{
public static void main(String args[])
{
keyword ob1 = new keyword();
keyword ob2 = new keyword();
keyword ob3 = new keyword();
ob1.getvalue(2,3);
ob2.getvalue(4,6);
ob3.sum(ob1,ob2);
ob3.display();
}
}
8.5 METHOD CALLING
There are two ways of a method calling.
Method returns a value
Returning nothing (no return value).
Method calling process is simple. When program invokes method, program
control moved to called method. Then called method returns control to the
caller in two conditions.
First when return statement is execute, and
Second when reached to method ending closing brace.
The void Keyword: It allows us to create methods which do not return a
value.
8.6 METHOD OVERLOADING
It is known when a class has two or more methods with the same name but with
different parameters.
Example: public class MethodOverloading{
public static void main(String[] args){
int w=10;
int x=5;
double y=6.3;
double z=8.4;
int value1= miniVal (w, x);
double value2= miniVal(y, z);
// same type of function name with different parameters
System.out.println(Minimum value = +value1);
System.out.println(Minimum value = +value2);
}
// for integer type
public static int miniVal(int x1, int x2){
int mini;
if(x1>x2){
mini=n2;
}
else{
mini=x1;
}
return mini;
}
// for value function
public static double miniVal (double x1, double x2){
double mini;
if(x1>x2){
mini=x2;
}
else{
mini=x1;
}
double mini;
}
}
8.7 METHOD OVERRIDING
Method overriding in java can be Know If child class (subclass) has same
method as declared in the parent class.
Example: class schoolclass{
void run(){System.out.println("school is running");}
}
class classroom2 extends schoolclass{
void run(){System.out.println("class room is running");}
public static void main(String args[]){
classroom2 obj = new classroom2();
obj.run();
}
1. New : A thread begins its life cycle in the new state. It remains in this
state until the start() method is called on it.
2. Runnable : After invocation of start() method on new thread, the
thread becomes runable.
3. Running : A method is in running thread if the thread scheduler has
selected it.
4. Waiting : A thread is waiting for another thread to perform a task. In
this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its
task.
11.2 MOSTLY USED METHODS OF THREAD CLASS
1. run(): Perform action for a thread.
2. start(): Starts execution of thread by calling run()
method.
3. stop() : Stops the thread.
4. sleep(): For a specified time suspend thread.
5. getPriority(): Priority of the thread returns.
6. setPriority(): Priority of the thread changes.
7. getName(): Name of the thread returns.
8. setName(): Name of the thread changes.
9. getId(): Id of the thread returns.
10. suspend() : Suspend the thread.
11. resume() : Resume the suspended thread.
12. stop() : Stop the thread.
11.3 CREATING A THREAD
There are two ways to create a thread:
1. Extending Thread class
2. Implementing Runnable interface.
Example by extending thread class
class MyThread extends Thread
{
public void run()
{
System.out.println(Concurrent thread started running..);
}
}
class MyThreadDemo
{
public static void main(String args[])
{
MyThread th = new MyThread();
th.start();
}
}
Output: Concurrent thread started running..
Example by implementing Runnable interface
class Test implements Runnable{
public void run(){
System.out.println("Concurrent thread started running..");
}
public static void main(String args[]){
Test x=new x();
Thread y =new Thread(y);
y1.start();
}
}
Output: Concurrent thread started running..
11.4 MULTITHREADING
The Word Multithreading Mean, program contains two or more than two
thread which runs parallel. Multithreading used because threads share a
common memory area without allocating separate memory area to save
more and also it takes less time than previous process.
Chapter 12 HANDLING EXCEPTIONS AND ERRORS
An exception is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the
program terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
Following are some scenarios where an exception occurs.
When a user has entered an invalid data.
When file cannot be found.
When network connection is lost in middle of communications or the
Java Virtual Machine runs out of memory.
These exceptions are caused by user, programmer and by physical resources
that have failed in some method.
12.1 EXCEPTION HANDLING WITH TRY-CATCH
Try keyword contains a block of statements to perform. Any exception
occurring within the try block is trapped. Hence, it is an error trapper. Further a
report is to be passed to the exception handler about the error, which can be
done by catch block.
The finally block contains the statements which are executed any way.
Syntax to use try-catch exception handler:
try
{
Set of statements
}
catch(exception(e)){
}
finally
{
Statement to execute any way
}
Example: import java.io.*;
public class Test{
public static void main(String args[]){
try{
int a[]=new int[2];
System.out.println(Access element three : +a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(Exception thrown : +e);
}
System.out.println(Out of the block);
}
}
Output: java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
12.2 EXCEPTION HANDLING WITH THROWS KEYWORD
If you want that the system is to be reported for an error then you can apply
throws keyword. A throws keyword is applied with function signature.
Example: public void getdata() throws IOException
This indicates, if an error occurs in the function related to I/O operation a report
may be passed to the error handler.
Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
12.3 JAVA EXCEPTION HANDLING ADVANTAGES
Exception handling is Helpful in the Separation of results for less
complex and readable code. It is also more capable, in the logic that the
testing of errors in the normal implementation path is not needed.
Logical error types Exceptions can be group together with errors that are
connected. It enables us to handle associated exceptions using single
exception handler. An exception handler can catch exceptions of the class
or any sub-class specified by its parameter.
Exception handling allows related information to be caught at where an
error occurs and to show it where it can be successfully controlled.
12.4 ERROR
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, etc.
Common Coding Errors:
Syntax Error Syntax errors are errors occurred in the syntax of a
particular sequence of characters of a program.
Logical Errors Logical errors occur when there is a design flaw in your
program.
Runtime Errors Runtime errors occur during the execution of the
program.
12.5 DIFFERENCE BETWEEN ERROR AND EXCEPTIONS
ERRORS EXCEPTIONS
Errors at run time cannot be known Checked exception can be known and
to compiler Uncheck cannot be known at run
time
Error Occurs or caused when an Exceptions Occurs by the application
application runs itself
Errors in java are Mostly Uncheck Check and Uncheck are Two type of
type exceptions in Java
Chapter 13 SOME QUESTIONS AND ANSWERS:
QUESTIONS
1. A program of Java that can be developed and executed by the users, is known as
a> Application b> Applet
c> Object d> none
2. Java Virtual Machine (JVM) is an
a> Interpreter b> Interpreter
c> Machine code d> Byte code
3. To find the square root of a number which of the following package is required?
a> java.txt b> java.math
c> java.lang d> java.net
4. Which of the following is not a Java reserved word?
a> private b> public
c> break d> character
5. The term used to correct the error in a program, is known as
a> bug b> debugging
c> error removing d> none
6. A constant which gives the exact representation of data is called
a> Variable b> Literal
c> Identifier d> Character
7. The statement n++ is equivalent to
a> ++n b> n=n+1
c> n+1 d> none
8. What will be the output of a & b, if int a,b; a=10;b=++a?
a> 10,10 b> 10,11
c> 11,10 d> 11,11
9. What will be the output of a++; int a=-1?
a> 1 b> -1
c> 0 d> none
10. if condition is essentially formed by using
a> Arithmetic operators b> Relational operators
c> Logical operators d> ternary operators
11. If(a!=b){
c=a;
}
else
{
c=b;
}
can be written as
a> c=(b!=a)?a:b; b> c=(a!=b)?a:b;
c> c=(a!=b)?b:a; d> both a & b
12. Which element is represented with a[10]
a> 10th b> 9th
c> 11th d> none
13. The statement : int code[]={26,38,39,43};
a> Assign 38 to code[1] b> Assign 26 to code[1]
c> Assign 39 to code[3] d> none
14. A function with many definitions is known as
a> multiple function b> function overloading
c> floating function d> none
15. A function is invoked through a class type-
a> object b> system
c> parameter d> none
ANSWERS:
1. a 2. a 3. b 4. d 5. b
6. b 7. b 8. b 9. c 10. b
11. d 12. c 13. a 14. b 15. a