Core Java HRP
Core Java HRP
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called
Green Team.
Originally designed for small, embedded systems in electronic appliances
like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling and file extension was
.gt. After that, it was called Oak and was developed as a part of the Green
project.
In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.
According to James Gosling "Java was one of the top choices along with
Silk". Since java was so unique, most of the team members preferred java.
Java is an island of Indonesia where first coffee was produced (called java
coffee).
Notice that Java is just a name not an acronym.
Java programming language was originally developed by Sun Microsystems
which was initiated by James Gosling and released in 1995 as core
component of Sun Microsystems. (which is now a subsidiary of Oracle
Corporation)
On 8 May, 2007, Sun finished the process, making all of Java's core code
free and open-source, aside from a small portion of code to which Sun did
not hold the copyright.
The latest release of the Java Standard Edition is Java SE 10.0.1. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for
Enterprise Applications.
Java Platform, Micro Edition (Java ME) provides a robust, flexible environment for
applications running on embedded and mobile devices in the Internet of Things: micro-
controllers, sensors, gateways, mobile phones, personal digital assistants (PDAs), TV
set-top boxes, printers and more. Java ME includes flexible user interfaces, robust
security, built-in network protocols, and support for networked and offline applications
that can be downloaded dynamically. Applications based on Java ME are portable across
many devices, yet leverage each device's native capabilities.
Netbeans: A Java IDE that is open-source and free, which can be downloaded from
http://www.netbeans.org/.
Eclipse: A Java IDE developed by the eclipse open-source community and can be
downloaded from http://www.eclipse.org/.
Java 1.0.2 - slow – 250 classes – lots of bugs – applet is the big thing
Java 2 version 1.2-1.4 – much faster – 2300 classes – comes in three flavours – J2SE,
J2ME, J2EE
Encapsulation and Data abstraction: Wrapping up (combing) of data and methods into
a single unit (class) is known as encapsulation. The data is not accessible to the outside
world and only those methods which are wrapping in the class can access it. This
insulation of the data from direct access by the program is called data hiding or
information hiding.
Encapsulation makes it possible for objects to be treated like ‘black boxes’, each
performing a specific task without any concern for internal implementation.
Data abstraction refers to, providing only needed information to the outside world and
hiding implementation details.
Inheritance: inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports the concept of hierarchical
classification. Inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a
new class from the existing one.
The inheritance mechanism allows the programmer to reuse a class that is almost, but
not exactly, what he wants, and to tailor the class in such a way that it does not introduce
any undesirable side effects into the rest of the classes.
Derived class known as subclass.
Polymorphism: polymorphism means ability to take more than one form. An operation
may exhibit different behaviours in different instances. The behaviour depends upon the
types of data used in the operation.
C++ supports operator overloading and function overloading.
Operator overloading is the process of making an operator to exhibit different behaviours
in different instances is known as operator overloading.
Function overloading is using a single function name to perform different types of tasks.
Dynamic Binding: In dynamic binding, the code associated with a given procedure call
is not known until the time of the call at run time. The code to be executed in response to
procedure call is decided at runtime.
Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a method in the receiving object that generates the
desired results. Message passing involves specifying the name of the object, the name of
the method and the information to be sent.
Java is:
Compiled and Interpreted: Java combines both making it a two stage system. First java
compiler translates source code into byte code. This byte code is not machine
instructions and therefore in second stage java interpreter generates machine code that
can be executed by the machine that is running java program.
Object Oriented: In Java, everything is an Object. Java can be easily extended since it
is based on the Object model. All program code and data resides in the object only.
Simple, familiar: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master. Familiar and look like a c++, it does
not support pointer and other features of c or c++.
Robust and Secure: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking. It provides
reliable code. It is designed as garbage-collected, relieving programmers from memory
management problem. It also incorporate concept of exception handling which eliminates
any risk of crashing the system.
The absence of pointer in the java ensures that program cannot access memory location
without proper authorization, no virus communicate with applet.
Distributed: Java is designed for the distributed environment of the internet. It can share
and access remotely data and program over internet make multiple programmer to work
together on a single project.
Multithreaded: With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly. Listening audio, scrolling page
and downloading can be done simultaneously.
import java.applet.*;
import java.awt.*;
public class HelloworldApplet extends Applet {
}
Javac HelloworldApplet.java
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloworldApplet.class" width="25" height="50">
</applet>
<hr>
</html>
Appletviewer test.html
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:
Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\JAVAPROGRAM.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line
Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your
path to read 'C:\WINDOWS\ SYSTEM32;C:\Program Files\java\jdk\bin'.
You will be able to see ' Hello World ' printed on the window.
A source code file with .java extension holds one class definition. A class has one or
more methods. A method is set of statements.
public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaProgram
Method Names - All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Java identifiers must start with a letter, a currency character ($), or a connecting
character such as the underscore ( _ ). Identifiers cannot start with a number.
After first character identifiers can contain any combination of letters, currency
characters, connecting characters, or numbers. For example,
o int variable1 = 10 ; //This is valid
o int 4var =10 ; // this is invalid, identifier can’t start with digit.
Identifiers, method names, class names are case-sensitive; tar and Tar are two
different identifiers.
You can’t use Java keywords as identifiers,
Below table shows a list of Java keywords.
A name used which refers to data stored in memory—is called a variable. Each variable
in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable. All variables are declared before they can
be used.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
Local Variable:
A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation. X=’A’
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these
number systems for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
char is a single 16-bit Unicode character 16-bit Unicode 0 Unicode 2^16- Character
It is used to store any character
'\u0000' 1 =65535
'\uffff'
int is a 32-bit signed two's complement integer 32-bit -2^31 +2^31-1 Integer
Integer is generally used as the default data
(- (2,147,483,647
type for integral values unless there is a
concern about memory. 2,147,483,64 )
The default value is 0 8)
float is a single-precision 32-bit IEEE 754 32-bit Approx range 1.4e-045 to Float
floating point
3.4e+038
Float is mainly used to save memory in large
arrays of floating point numbers
Default value is 0.0f
double is a double-precision 64-bit IEEE 754 64-bit Approx range 4.9e-324 to Double
floating point
1.8e+308
This datatype is generally used as the default
data type for decimal values, generally the
default choice
Default value is 0.0d
Wrapper Classes
Java is an object-oriented language and as said everything in java is an object. What about the
primitives datatypes? As a solution to this problem, Java allows you to include the primitive
datatypes in the family of objects by using what are called wrapper classes.
There is a wrapper class for every primitive date type in Java. This class encapsulates a single
value for the primitive data type. For instance the wrapper class for int is Integer, for float is Float,
and so on.
The wrapper classes in the Java API serve two primary purposes:
To provide a mechanism to “wrap” primitive values in an object so that the primitives can be
included in activities reserved for objects, like as being added to Collections, or returned from a
method with an object return value.
To provide an assortment of utility functions for primitives. Most of these functions are related to
various conversions: converting primitives to and from String objects, and converting primitives
and String objects to and from different bases (or radix), such as binary, octal, and
hexadecimal.
Wrapper Class functions / methods
The wrapper class methods that are static in nature can be directly accessed as –
Function Description
booleanValue( ) Convert Boolean object to boolean primitive datatype.
valueOf( ) Convert String to Boolean object.
toString( ) Convert Boolean object to String.
Function Description
parseByte( ) Converts String to byte primitive datatype.
valueOf( ) Converts String to Byte object.
Function Description
parseShort( ) Converts String to short primitive datatype.
valueOf( ) Converts String to Short object.
toString( ) Converts short primitive to String object.
// Object to primitive
int i= I1.intValue();
System.out.println("Object to primitive "+i);
System.out.println("Object to primitive "+F1.floatValue());
//String to Object
Integer I2 = new Integer("1234");
//Object to String
String s = I2.toString();
System.out.println("Object to String "+s);
//String to primitive
String s1 ="3.56";
float f = Float.parseFloat(s1);
System.out.println("String to primitive using parse method : "+
f);
// primitive to string
String s2 = Double.toString(35.6);
System.out.println("Primitive to String using toString method : "+
s2);
// primitive to String
String s3 = String.valueOf(234);
String s4 = Integer.toString(234);
System.out.println("Primitive to String using valueOf method : "+
s3);
System.out.println("Primitive to String using toString method : "+
s4+" length "+s4.length());
To use objects instead of primitive data types, Java provides wrapper class
Character for primitive data type char.
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println( Character.isUpperCase('c'));
System.out.println( Character.isUpperCase('C'));
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C'));
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
Compiler creates a String object with its value; create String objects by
using the new keyword and a constructor.
The String class is immutable; so that once it is created a String object
cannot be changed. If there is a necessity to make a lot of modifications to
Strings of characters, then String Buffer & String Builder Classes are used.
Strings, objects of type StringBuffer can be modified over and over again
without leaving behind a lot of new unused objects.
We can say that, the main difference between String and StringBuffer is
String is immutable while StringBuffer is mutable means you can modify a
StringBuffer object once you created it without creating any new object. This
mutable property makes StringBuffer an ideal choice for dealing with Strings
in Java.
public StringBuffer append(String s)
Updates the value of the object that invoked the method.
Every string object contains a function named length that computes the
number of characters in that string. Note that this function has no parameter.
S1.length()
S1.concate(String s2)
Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Addition +, Subtraction -, Multiplication *, Division / , Modulus (remainder) %, ++
increment, -- decrement
Relational Operators
== (equal to) , != (not equal to) , > (greater than)
< (less than) , >= (greater than or equal to)
<= (less than or equal to)
Bitwise Operators
& (bitwise and), | (bitwise or) , ^ (bitwise XOR)
~ (bitwise compliment) , << (left shift)
>> (right shift) , >>> (zero fill right shift)
Logical Operators
&& (logical and) , || (logical or) , ! (logical not)
Assignment Operators
=, += a+=c means a=a+c, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=
Control Structure
There may be a situation when you need to execute a block of code several number of
times. A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the programming
languages:
int no = 1;
while (no) { } is wrong
A: A Boolean and an integer are not compatible types in Java. The result of a conditional
test must be a Boolean; the only variable you can directly test (without using a
comparison operator) is a Boolean. For example, you can say:
Boolean nvalue = true;
while (nvalue) { } is true.
Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
Statement Description
if statement An if statement consists of a boolean expression
followed by one or more statements.
if...else statement if statement can be followed by an optional else
statement, which executes when the boolean
expression is false.
// Prime Number
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
import java.util.Scanner;
sc.close();
}
import java.util.*;
public class SwitchExample {
switch(a)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("No of days is 31");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("No of days is 30");
break;
case 2:
System.out.println("No of days is 28 or 29");
break;
default:
System.out.println("Enter valid month");
}
s.close();
}
Arrays: an array is a group of contiguous or related data items that share a common name.
Array can be of any variable type.
It is often more useful to think of an array as a collection of variables of the same type.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way. Style come from c++
Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
Arrays are always objects, whether they are declared to hold primitives or object
reference.
Once you have declared an array, you can’t put anything in it except the things that are of the
declared array type. You can’t stick a double into an int array type. But you can put a Byte into an
int array type. Byte will always fit into an int sized.
import java.util.*;
public class IntArrayForLoop {
int number[];
number = new int[5];
// Enter the array elements
Scanner sc=new Scanner(System.in);
--------------------------------
// Convert number amount into word amount
import java.util.*;
String[] tens = {
"", // 0
"", // 1
"Twenty", // 2
"Thirty", // 3
"Forty", // 4
"Fifty", // 5
"Sixty", // 6
"Seventy", // 7
"Eighty", // 8
"Ninety" // 9
};
if (n < 0) {
System.out.println("Amount is Negative");
}
System.out.println("Amount is :" +
twodigit[p] + " hundred " + twodigit[r]);
}
else {
int p1 = r/10;
int r1 = r%10;
System.out.println("Amount is :" +
twodigit[p] + " hundred " + tens[p1] + " " + twodigit[r1]);
}
}
} // end of function
public static void main(String[] args) {
// TODO Auto-generated method stub
int no;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to convert into word format
:");
no =sc.nextInt();
NumberToWordConverter fa = new NumberToWordConverter();
fa.ConvertStr(no);
}
}
--------------------------------------------------------------
Array – Object
import java.lang.String;
public class ReferenceArrayExample {
String title;
String author;
public static void main(String[] args) {
// TODO Auto-generated method stub
ReferenceArrayExample[] myBooks = new
ReferenceArrayExample[3];
myBooks[0] = new ReferenceArrayExample();
myBooks[1] = new ReferenceArrayExample();
myBooks[2] = new ReferenceArrayExample();
int x = 0;
myBooks[0].title = "The Grapes of Java";
myBooks[1].title = "The Java Gatsby";
myBooks[2].title = "The Java Cookbook";
myBooks[0].author = "bob";
myBooks[1].author = "sue";
myBooks[2].author = "ian";
while (x < 3) {
System.out.print(myBooks[x].title);
System.out.print(" by ");
System.out.println(myBooks[x].author);
x = x + 1;
}
}
}
// Student Array
import java.util.*;
public class StudentArray {
int rollno;
String sname;
int semester;
String division;
void studentdata() {
Scanner sc = new Scanner(System.in);
rollno = sc.nextInt();
sname = sc.next();
semester = sc.nextInt();
division = sc.next();
}
void Display() {
System.out.println(rollno);
System.out.println(sname);
System.out.println(semester);
System.out.println(division);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentArray sa[] = new StudentArray[3];
for(int i=0;i<3;i++) {
sa[i] = new StudentArray();
System.out.println("Enter " +i +" Student Details");
sa[i].studentdata();
}
for(int i=0;i<3;i++) {
System.out.println("Print " +i +" Student Details");
sa[i].Display();
}
}
}
Data_Type[][] Array_Name;
Second Approach
int[][] Student_Marks={{10, 20, 30},{15, 25, 35},{22, 44, 66},{33, 55, 77}};
Here, we did not mention the row size and column size but the compiler is
intelligent enough to calculate the size by checking the number of elements
inside the row and column. 4 X 3
Condition inside the for loops (rows < a.length) will ensure the compiler, not to exceed
the array row limit and (rows < a[0].length) will ensure the compiler not to exceed the
array column limit.
int k=1;
import java.util.*;
public class MultiplicationMatrix {
// Multiplication
int[][] c = new int[rowsInA][columnsInB];
A B
123 123
456 456
789
Mathematical Functions
To get the absolute value of a number, or round a number, or find the larger of two
numbers, to print number with exactly two decimal places, or you might want to put
commas into your large numbers to make them easier to read, to print dates In a variety
of ways, parsing a String Into a number Or turning a number into a String
/* The method converts the value of the Number Object into the primitive data type. Here
is a separate method for each primitive data type.
byte byteValue()
short shortValue()
int int Value()
long longValue()
float floatValue()
double doubleValue()*/
/* However, two different types cannot be compared, both the argument and the Number
object invoking the method should be of the same type.
Return Value
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
If the Integer is greater than the argument then 1 is returned. */
Float xx = 34.23f;
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8));
System.out.println(xx.compareTo(8.2f));
/* The method determines whether the Number object that invokes the method is equal
to the object that is passed as an argument.
The method returns True if the argument is not null and is an object of the same type and
with the same numeric value. */
Integer a = 5;
Integer b = 10;
Integer c = 5;
Short d = 5;
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals(d));
/ * The valueOf method returns the relevant Number Object holding the value of the
argument passed. The argument can be a primitive data type, String, etc.
Integer valueOf(int i)
Integer valueOf(String s)
Integer valueOf(String s, int radix) */
Integer x1 =Integer.valueOf(9);
Double c1 = Double.valueOf(5);
Float a1 = Float.valueOf("80");
Integer b1 = Integer.valueOf("444",8);
System.out.println(x1);
System.out.println(c1);
System.out.println(a1);
System.out.println(b1);
// The method is used to get a String object representing the value of the Number Object.
If the method takes a primitive data type as an argument, then the String object
representing the primitive data type value is returned.
String s1;
s1 = a.toString();
System.out.println(s1);
s1 = Integer.toString(55);
System.out.println(s1);
//This method is used to get the primitive data type of a certain String.
int x2 =Integer.parseInt("9");
double c2 = Double.parseDouble("5");
int b2 = Integer.parseInt("444",16);
System.out.println(x2);
System.out.println(c2);
System.out.println(b2);
// CEIL - This method returns the smallest integer that is greater than or equal to the
argument. Returned as a double
// FLOOR - The method floor gives the largest integer that is less than or equal to the
argument.
double d2 = 100.675;
float f2 = -90.500f;
float f4 = 90.500f;
System.out.println(Math.ceil(d2));
System.out.println(Math.ceil(f2));
System.out.println(Math.floor(d2));
System.out.println(Math.floor(f2));
/* The method round returns the closest long or int, as given by the methods return type.
long round(double d)
int round(float f) */
long d3 = Math.round(d2);
int f3 = Math.round(f2);
int f5 = Math.round(f4);
System.out.println(d3);
System.out.println(f3);
System.out.println(f5);
Min() method gives the smaller of the two arguments. The argument can be int, float,
long, double.
Max() method gives the maximum of the two arguments. The argument can be int, float,
long, double.
double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)
System.out.println(Math.min(12.123, 12.456));
System.out.println(Math.min(23.12, 23.0));
System.out.println(Math.max(12.123, 12.456));
System.out.println(Math.max(23.12, 23.0));
Exp() method returns the base of the natural logarithms, e, to the power of the argument.
double exp(double d)
Log() method returns the natural logarithm of the argument.
double log(double d)
Pow() method returns the value of the first argument raised to the power of the second
argument.
double pow(double base, double exponent)
double d6 = Math.sqrt(4.0);
System.out.println(d6);
Sin() method returns the sine of the specified double value.
double sin(double d)
Random() method is used to generate a random number between 0.0 and 1.0. The range
is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic
operations.
double random()
This is a default method and accepts no parameter.
This method returns a double.
System.out.println( Math.random() );
}
-------------------------------
public class PhraseOMatic {
public PhraseOMatic() {
// TODO Auto-generated constructor stub
}
The java.io package includes a PrintStream class that has two formatting
methods printf and format methods that you can use to replace print and
println.
The format string contains plain text as well as format specifiers, which are
special characters that format the arguments of Object.
Format specifiers begin with a percent sign (%) and end with a converter.
The converter is a character indicating the type of argument to be formatted.
In between the percent sign (%) and the converter you can have optional
flags and specifiers.
There are various converters, flags, and specifiers, which are documented
in java.util.Formatter
The following table lists some of the converters and flags that are used in
the sample program, TestFormat.java.
import java.util.Calendar;
//import java.util.Locale;
double pi = Math.PI;
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> " July 05, 2018"
-------------------------------------------------------
To initialize the instance variables of all objects individually, does not
promote data hiding and it would be inconvenient if the number of objects is
very large.
A better solution of this problem is to initialize values to the object at a time
of its creation in the same way as we initialize values to the variable of
primitive data types.
Constructor makes an object to initialize itself at the time of its creation
without the need to make separate call to the instance method.
What is a Constructor?
A constructor is similar to a method (but not actually a method) that is
invoked automatically when an object is instantiated.
Java compiler distinguishes between a method and a constructor by its
name and return type. In Java, a constructor has same name as that of the
class, and doesn’t return any value.
class Test {
Test() {
// constructor body
}
}
Here, Test() is a constructor; it has same name as that of the class and
doesn’t have a return type.
class Test {
void Test() {
// method body
}
}
Here, Test() has same name as that of the class. However, it has a return
type void. Hence, it’s a method not a constructor.
No-Argument Constructor
public class ConstructorExample {
int x;
public ConstructorExample() {
// TODO Auto-generated constructor stub public or private no
change
System.out.println("Constructor Called");
x = 5; // if int x = 5 means it’s a local variable and output of x =0
}
When you run the program, the output will be:
Constructor Called
Value of x = 5
Default Constructor
class DefaultConstructor {
int a;
boolean b;
private DefaultConstructor() {
a = 0;
b = false;
}
public ConstructorExample() {
// TODO Auto-generated constructor stub
System.out.println("Constructor Called");
x = 5;
}
public ConstructorExample(int x1) {
// TODO Auto-generated constructor stub
System.out.println("Constructor one argument Called");
y = x1;
}
public ConstructorExample(int x2, int x3) {
// TODO Auto-generated constructor stub
System.out.println("Constructor two argument Called");
y = x2;
z = x3;
}
public ConstructorExample(int x2, int x3, String s1) {
// TODO Auto-generated constructor stub
System.out.println("Constructor three argument Called");
y = x2;
z = x3;
s = s1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorExample con = new ConstructorExample();
System.out.println("Value of x = " + con.x);
ConstructorExample con1 = new ConstructorExample(3);
System.out.println("Value of y = " + con1.y);
ConstructorExample con2 = new ConstructorExample(7,8);
System.out.println("Value of y = " + con2.y + " and Value of z = "
+ con2.z);
ConstructorExample con3 = new
ConstructorExample(9,10,"Hello");
System.out.println("Value of y = " + con3.y + " and Value of z = "
+ con3.z + " value of s =" + con3.s);
}
}
Constructor Called
Value of x = 5
Constructor one argument Called
Value of y = 3
Constructor two arguments Called
Value of y = 7 and Value of z = 8
Constructor three arguments Called
Value of y = 9 and Value of z = 10 value of s =Hello
--------------------------------------------------------------------
Private Constructor:
One application is in the singleton design pattern. The policy is that only one
object of that class is supposed to exist, so no other class than itself can
access the constructor. This ensures the single instance existence of the
class.
}
Output :
0 null 0.0
0 null 0.0
In the below example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
Public class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}
Important notes
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
A Java constructor name must exactly match with the class name (including case).
A Java constructor must not have a return type.
If a class doesn't have a constructor, Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with
default values. For example: int variable will be initialized to 0
Constructors cannot be abstract or static or final.
Constructor can be overloaded but cannot be overridden.
Copy Constructor –
Sometimes a programmer wants to create an exact but separate copy of an existing
object so that any changes to the copy should not alter the original or vice versa. This is
made possible by using the copy constructor. A copy constructor is a constructor that
creates a new object that is using an existing object of the same class and initializes
each instance variable of newly created object with corresponding instance variables of
the existing object passed as argument. This constructor takes a single argument whose
type is that of the class containing the constructor.
Program Example of Copy Constructor:
Let us consider a program in which we create a copy of an existing object.
First we create a class Rectangle in which we declare the copy constructor to initialize
length and breadth:
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and breadth of rectangle
Rectangle(int l, int b)
{
length=l;
breadth=b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("copy constructor invoked");
length=obj.length;
breadth=obj.breadth;
}
//method to calculate area of rectangle
int area()
{
return (length*breadth);
}
}
//Second create a class CopyConstructorExample which inherit the methods of above
class Rectangle and create its object and calculate area:
//class to create a rectangle objects and calculate area
-------------------------------------------------------------------------------------
Dynamic Array
ArrayList in Java
ArrayList is a part of collection framework and is present in java.util
package. It provides dynamic arrays in Java. Though, it may be slower than
standard arrays but can be helpful in programs where lots of manipulation in
the array is needed.
Java ArrayList allows us to randomly access the list because array works at
the index basis.
ArrayList cannot be used for primitive types, like int, char, etc. We need a
wrapper class.
Difference
/* ........... Normal Array............. */
// Need to specify the size for array
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
/*............ArrayList..............*/
// Need not to specify size
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// We can add more elements to arrL
Array can contain both primitive data types as well as objects of a class
depending on the definition of the array.
However, ArrayList only supports object entries, not the primitive data types.
Note: When we do arraylist.add(1); : it converts the primitive int data type
into an Integer object.
// Example
import java.util.*;
public class ArrayListExample1 {
// Printing elements
System.out.println(arrli);
For reading all elements from ArrayList, by using Iterator class. We can iterate
through the ArrayList based on index.
import java.util.*;
public class ArrayListExample2 {
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); // next string
}
} // End of Main
} // End of Class
import java.util.*;
class StudentData{
int rollno;
String name;
int age;
StudentData(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
//Getting Iterator
Iterator<StudentData> itr=AL.iterator();
import java.util.*;
public class ArrayListExample2 {
list2.add("Sunil");
list2.add("Sachin");
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); // next string
}
System.out.println("For Loop");
for (int counter = 0; counter < list.size(); counter++) {
System.out.println(list.get(counter));
}
list2.add("Gopal");
//while(itr.hasNext()){
// System.out.println(itr.next()); // next string
// }
System.out.println(list.size());
System.out.println("For Loop");
for (int counter = 0; counter < list.size(); counter++) {
System.out.println(list.get(counter));
}
}
This method is used to retain all matching elements in the current ArrayList instance that
match all elements from the Collection list passed as a parameter to the method.
import java.util.*;
public class ArrayListExample3 {
OutPut:
---------------------------------------------------
Vectors:
This class can be used to create a generic dynamic array which can hold
objects of any type and any number. The objects do not have to be homogeneous.
import java.util.*;
public class VectorExample2 {
}
OutPut:
C:\HRP_JAVA>java VectorExample2 Ada Basic C++ Fortran Java
[Ada, Basic, Cobol, C++, Fortran, Java]
List of Languages
Ada
Basic
C++
Fortran
Java
import java.util.*;
public class VectorExmple1 {
v.add(0, 1);
v.add(1, 2);
v.add(2, "Manish");
v.add(3, "Mahesh");
v.add(4, 3);
v.add(5, 1);
v.add(6, 2);
v.add(7, "Poojan");
v.add(8, "Parth");
v.add(9, 3);
v.add(10, 1);
v.add(11, 2);
v.add(12, "geeks");
v.add(13, "forGeeks");
v.add(14, 3);
System.out.println("Vector is " + v);
System.out.println((int)v.get(4) * (int)v.get(6));
}
OBJECT:
In java, programmers care about two areas of memory-the one where objects live (the
heap), and the one where method live and local variables live (the stack).
When a JVM starts up, it gets a chunk of memory from the underlying OS, and uses it to
run your Java program. How much, memory, and whether or not you can adjust it, is
dependent on which version of the JVM and on which platform you are running.
All objects live on the garbage-collectible heap, but where variables live. And where a
variable lives depends on what kind of variable it is. And by "kind", we don't mean type
(i.e. primitive or object reference).
The two kinds of variables whose lives we care about now are instance variables and
local variables. Method invocation and local variables are also known as stack variables,
which is a big clue for where they live.
Instance Variables
Instance variables are declared inside a class but not inside a method. They represent
the "fields" that each Individual object has (which can be filled with different values for
each Instance of the class). Instance variables live inside the object they belong to.
Local Variables
Local variables are declared inside a method, including method parameters, they are
temporary, and live only as long as the method is on the stack (in other words, as long as
the method has not reached the closing curly brace).
The method at the top of the stack is always the currently-running method for that stack
(for now, assume there is only one stack.) A method stays on the stack until the method
hits its closing curly brace (which means the method's done). If method foo() calls
method bar(), method bar() is stacked on top of method foo().
The method on the top of the stack is always the currently executing method.
A stack scenario
Public void dostuff(){
Boolean b = True;
Go(4);
}
Public void Go(int x){
Int z = x +24;
Crazy();
}
The code on the top is a snippet (we don't care what the rest of the class looks like) with three
methods. The first method dostuff() calls the second method Go() , and the second method calls
the third Crazy(). Each method declares one local variable within the body of the method, and
method Go() has two local variables.
Code from another doStuff() calls go(), Go() calls crazy(), crazy() completes,
class calls dostuff(), go() is pushed on top Crazy() is now on the and its stack frame is
and dostuff() goes of the stack. top of the stack, with popped off the stack.
into a stack frame at Variables 'x' and 'z' variable 'c' in the Execution goes back
the top of the stack. are in the go() stack frame. to the go() method.
The Boolean variable frame. and picks up at the
named 'b' goes on line following the call
the doStuff() stack to crazy().
frame.
____________ ____________ Crazy() - c
____________ Go() – x z Go() – x z Dostuff() - b
Dostuff() - b Dostuff() - b Dostuff() - b Go() – x z
Duck reference variable d declared inside the method, it is a local variable and goes on
to stack, but object goes on the heap.
Why are we learning the whole stack/heap thing? How does this help?
Knowing the fundamentals of the Java Stack and Heap is crucial If you want to
understand variable scope, object creation Issues, memory management, threads, and
exception handling.
If local variables live on the stack where do instance variables live?
Class Cellphone(){
Int a;
Long b;
Private antenna ant = new antenna();
}
When you say new Cellphone(), Java has to make space on the Heap for that
CellPhone. But how much space?
Enough for the object, which means enough to house the entire object’s instance
variables. It means instance variables live on the Heap, inside the object they belong to.
Remember that the values of an object's instance variables live inside the object. If the
instance variables are all primitives, Java makes space for the instance variables based
on the primitive type.
But what if the instance variables are objects? For example CellPhone has a reference
variable of type Antenna.
When the new object has instance variables that are object references rather than
primitives, the real question is: does the object need space for all of the objects it holds
references to?
The answer is, not exactly. No matter what, Java has to make space for the instance
variable values. But remember that a reference variable value is not the whole object, but
merely a remote control (reference) to the object.
When does the Antenna object get space on the Heap? First we have to find out when
the Antenna object itself is created. That depends on the instance variable declaration. If
the instance variable is declared but no object is assigned to it, then only the space for
the reference variable (the remote control) is created.
--------------------------------------------------------------------------
There is no global anything in Java. But think about this: what if you have a method
whose behaviour does not depend on an instance variable value. Take the round ()
method in the Math class, for example.
It does the same thing every time-round a floating point number (the argument to the
method) to the nearest integer every time. If you had 10,000 instances of class Math, and
ran the round (42.2) method, you would get an integer value of 42 every time. In other
words, the method acts on the argument, but is never affected by an instance variable
state. The only value that changes the way the round () method runs is the argument
passed to the method.
In fact the Math class doesn't have any instance variables. So there's nothing to be
gained by making an instance of class Math. If you try to make an instance of class Math:
Math mathObject = new Math () , You will get error.
Methods in the Math class don't use any instance variable values. Because the methods
are 'static', you don't need to have an instance of Math.
The static keyword is used in java mainly for memory management. It is used with
variables, methods, blocks and nested class. It is a keyword that are used for share the
same variable or method of a given class. This is used for a constant variable or a
method that is the same for every instance of a class. The main method of a class is
generally labelled as static.
Let us assume that we want to define a member that is common to all objects and
accessed without using a particular object. That is the member belongs to the class as a
whole rather than the objects created from the class. Such members can be defined as
follows:
The static variable allocate memory only once in class area at the time of class loading.
Using static variable we make our program memory efficient (i.e it saves memory).
Static variables in a class are initialized before any object of that class can be created.
Static variables in a class are initialized before any static method of the class runs.
Static variables are initialized when the class is loaded. If you don't explicitly initialize a
static variable (by assigning it a value at the time you declare it), it gets a default value,
so int variables are initialized to zero.
You can not make reference to a static variable from a non-static method. To understand
this, you need to understand the difference between static and non-static.
Static variables are class variables, they belong to the class with their only one instance,
created at the first only. Non-static variables are initialized every time you create an
object of the class.
When you use new() operator we will create a copy of every non-static field for every
object, but it is not the case for static fields. That's why it gives compile time error if you
are referencing a static variable from a non-static method.
// Method example
public class StaticMathExample {
---------------------------------------
Nested class meaning:
public class NestedClassExample {
int no;
Pass by Value
Let us understand what is pass by value. Actual parameter expressions that
are passed to a method are evaluated and a value is derived. Then this value
is stored in a location and then it becomes the formal parameter to the
invoked method. This mechanism is called pass by value and Java uses it.
When we pass a primitive type to a method, it is passed by value.
class PassByValue
{
static void change(int a){
a = 500;
System.out.println("value of n changed in the function : "+a);
}
public static void main(String args[]){
int n = 56;
System.out.println("value of n before calling a function : "+n);
change(n);
System.out.println("value of n after calling a function : "+n);
}
}
Pass by Reference
In pass by reference, the formal parameter is just an alias to the actual
parameter. It refers to the actual argument. Any changes done to the formal
argument will reflect in actual argument and vice versa.
When we pass an object to a method, the objects are passed by what is
effectively call-by-reference. While creating a variable of a class type, we only
create a reference to an object. Thus, when we pass this reference to a
method, the parameter that receives it will refer to the same object as that
referred to by the argument.
This effectively means that objects act as if they are passed to methods by
use of call-by-reference.
Changes to the object inside the method do reflect in the object used as
an argument.
class School{
String name;
School(String n){
name = n;
}
}
class PassByRef{
static void change(School S){
S.name = "Udgam School";
System.out.println("School namevalue of S changed in the function :
"+S.name);
}
s1.display();
s2.display();
s3.display();
StaticExample1.change();
s1.display();
s2.display();
s3.display();
--------------------------------------------------------------
//a program to accept two nos through command line args and add the nos.
public class CommandLineExample1 {
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
c=a+b;
// write an application that converts between meters and feet. Its first
command line argument
// is a number. Its second argument is either 'feet' or 'meters'.
// If this argument is 'feet' display equivalent meters and vice versa. 1 M =
3.28 FT
int no = Integer.parseInt(args[0]);
if (args.length == 0)
{
System.out.println("command-line arguments are not passed");
System.exit(0);
}
----------------------------------
In Java, it is common to combine several classes in one .jar ("java archive") file. Library
classes are stored that way. Larger projects use jar files. You can create your own jar
file combining several classes, too.
jar files are created using the jar.exe utility program from the JDK. You can make your
jar file runnable by telling jar.exe which class has main. To do that, you need to create a
manifest file. A mainfest is a one-line text file with a "Main-Class" directive. For
example:
Main-Class: Craps
This line must end with a newline.
A jar file created with a main class manifest can be used both as a library and a runnable
jar. If you use it as a library, you can edit and compile any of the classes included in the
jar, and add it to your project. Then it will override the one in the jar file.
Once you have a manifest and all your classes have been compiled, you need to run
JDK's jar.exe utility. It is located in the JDK’s bin folder, the same place where javac.exe
and java.exe are. jar.exe takes command-line arguments; if you run it without any
arguments, it will display the usage information and examples. You need
C\mywork> jar cvfm MyJarName.jar mainfest.txt *.class
cvfm means "create a jar; show verbose output; specify the output jar file name; specify
the mainfest file name." This is followed by the name you wish to give to your jar file, the
name of your manifest file, and the list of .class files that you want included in the jar.
*.class means all class files in the current directory.
Actually, if your manifest contains only the Main-Class directive, you can specify the main
class directly on the jar.exe's command line, using the e switch, instead of m. Then you
do not need a separate manifest file; jar will add the required manifest to your jar file for
you. For example:
C\mywork> jar cvfe MyJarName.jar MyMainClass *.class
Below is a reference for creating a jar file in Eclipse and the detailed steps for doing this
in Command Prompt and in JCreator.
Creating a jar File in Eclipse
In Eclipse Help contents, expand "Java development user guide" ==> "Tasks" ==>
"Creating JAR files." Follow the instructions for "Creating a new JAR file" or "Creating a
new runnable JAR file."
The JAR File and Runnable JAR File commands are for some reason located under the
File menu: click on Export... and expand the Java node.
Inheritance
The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of parent class. Moreover, you can add new
methods and fields in your current class also.
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.
Example:
// First Example
class Employee{
float salary=40000;
}
public class InheritExample extends Employee{
int bonus=10000;
public static void main(String[] args) {
// TODO Auto-generated method stub
InheritExample p=new InheritExample();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
// Second Example
class shape{
int l;
int b;
public void cirarea(int x) {
b = x;
double carea = 3.14 * b * b;
System.out.println(carea);
}
public void sqrarea(int x) {
b = x;
double sarea = b * b;
System.out.println(sarea);
}
// Little Change
class shape{
int b;
public void cirarea(int x) {
b = x;
double carea = 3.14 * b * b;
System.out.println(carea);
}
public void sqrarea(int x) {
b = x;
double sarea = b * b;
System.out.println(sarea);
}
}
class shapevolume extends shape {
int l;
int h;
public void rectarea(int x, int y) {
l = x;
b = y;
double rarea = l * b;
System.out.println(rarea);
}
public void rectvol(int x, int y, int z) {
l = x;
b = y;
h = z;
double rvol = l * b * h;
System.out.println(rvol);
}
}
public class InheritExample1 extends shapevolume {
Method Overloading
When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from
overriding. In overriding, a method has the same method name, type,
number of parameters. Overloading lets you make multiple versions of a
method, with different argument lists, for convenience to the callers. Here
return type is different.
Types of inheritance
Inheritance may take different forms.
class room
{
int length;
int breadth;
void getdata(){
length=10;
breadth=14;
}
int area(){
return(length
length*breadth);
}
}
class bedroom extends room
{
int height=10,vol;
void display()
{
vol=height*length
length*breadth;
System.out.println(
.println(vol);
}
}
public class InheritExample2 {
public static void main(String[] args) {
// TODO Auto-
-generated method stub
bedroom r1=new
new bedroom();
r1.getdata();
.getdata();
r1.area();
r1.display();
.display();
}
Example:
class Animal
{
void eat()
{
System.out.println("Animal can eat");
}
}
// class 'Mango'
' inherits from class 'Fruit'
class Mango extends Fruit {
public void mangoInfo() {
fruitInfo(); // calling base class function
System.out.println(
.println("My name is mango. ");
}
}
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.
Java does not support multiple inheritance with classes. In java, we can
achieve multiple inheritance only through Interfaces.
Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.
The Object class, in the java.lang package, sits at the top of the class hierarchy tree.
Every class is a descendant, direct or indirect, of the Object class. Every class you use or
write inherits the instance methods of Object.
java.lang.Object class is the super base class of all Java classes. Every other Java
classes descend from Object.
Should we say the God class?
If a class is declared without extending another class then it will implicitly extend Object
class. This is taken care of by the JVM.
The reason for this design decision: By having the Object as the super class of all Java
classes, without knowing the type we can pass around objects using the Object
declaration.
Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.
Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods for accessing
its private fields, these can also be used by the subclass.
Protected
Protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes
of the same package, but not from anywhere else. You use the protected
access level when it is appropriate for a class’s subclasses to have access to
the method or field, but not for unrelated classes.
class Animal{
protected int no = 5;
protected void eat(){
System.out.println("Animal can eat");
}
}
Private
Private Methods and fields can only be accessed within the same class to
which the methods and fields belong. Private methods and fields are not
visible within subclasses and are not inherited by subclasses.
class Animal{
private void eat(){
System.out.println("Animal can eat");
}
public void disp(){
Animal a1 = new Animal();
a1.eat();
}
}
So, the private access specifier is opposite to the public access specifier. It is
mostly used for encapsulation: data are hidden within the class and accessor
methods are provided.
------------------------------------------------------------------------------------------
The use of super keyword
In java to access the data members of parent class when both parent and
child class have member with same name. (Variables or methods)
To access the method of parent class when child class has overridden that
method.
--------------------------------------------
In java a subclass inherits the accessible variables and methods from its superclass, but the constructors
of the superclass are not inherited in the subclass. They can only be invoked from constructors of subclass
using the keyword super.
The superclass constructor call must be the first statement in the body of childclass constructor. If one
does not specify super, the compiler implicitly inserts super(); at the beginning of the childclass’s default
constructor to call the superclass’s default constructor.
When you have a method in child class which is already present in the
parent class then in order to access the method of parent class, you need to
use the super keyword.
class Super1{
void show(){
System.out.println("Super Class method has been called");
}
}
class Sub1 extends Super1{
void show(){
super.show();
System.out.println("sub Class method has been called");
}
}
public class InheritExample6 {
When you have a variable in child class which is already present in the
parent class then in order to access the variable of parent class, you need to
use the super keyword.
class Super1{
int x = 30;
void show(){
System.out.println("Super Class method has been called");
}
}
class Sub1 extends Super1{
int x = 35;
void show(){
super.show();
System.out.println("sub Class method has been called");
System.out.println("Supper class x value :" + super.x);
System.out.println("sub class x value :" + x);
}
}
public class InheritExample6 {
When we create the object of sub class, the new keyword invokes the
constructor of child class, which implicitly invokes the constructor of parent
class. So the order to execution when we create the object of child class is:
parent class constructor is executed first and then the child class constructor
is executed. It happens because compiler itself adds super()(this invokes
the no-arg constructor of parent class) as the first statement in the
constructor of child class.
Let’s see an example to understand:
class Supercl1{
int x;
Supercl1(){
x = 30;
System.out.println("Supper class x value :" + x);
}
void show(){
System.out.println("Super Class method has been called");
}
}
class Subcl1 extends Supercl1{
int x;
Subcl1(){
x = 35;
System.out.println("sub class x value :" + x);
}
void show(){
super.show();
System.out.println("sub Class method has been called");
}
}
public class InheritExample7 {
}
OUTPUT:
Supper class x value :30
sub class x value :35
Super Class method has been called
sub Class method has been called
class Supercl1{
Supercl1(int y){
System.out.println("Supper class y value :" + y);
}
}
class Subcl1 extends Supercl1{
Subcl1(int y){
super(30);
System.out.println("Sub class y value :" + y);
}
}
public class InheritExample7 {
--------------------------------------
// another example
class studentdetail{
String sname;
int rollno;
studentdetail(String sname, int rollno){
this.sname = sname;
this.rollno = rollno;
}
}
---------------------------------------------------------------------------
Rules of Super Keyword
The superclass constructor call, using keyword super must be the first statement in the
body of subclass constructor.
A superclass constructor can only be called from a subclass constructor. Any other
subclass method cannot call it.
A superclass constructor call requires the use of super. It is illegal to specify the actual
name of the class.
When a child class declares a same method which is already present in the parent class
then this is called method overriding. When child class doesn’t override the parent
class method then we don’t need to use the super keyword to call the parent class
method.
---------------------------------------------------------------------------
//Recursion Method
public class FibRecursion {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FibRecursion fr = new FibRecursion();
fr.fibonacci(6, 0, 1);
}
class fibo{
public static int fibb(int n) {
if(n <= 0) {
//System.out.println(n);
return 0;
}
if (n == 1) {
//System.out.println(n);
return 1;
}
else {
//System.out.println(n);
return(fibb(n-1)+fibb(n-2));
}
}
}
public class FibRecursion1 {
// Without Recursion
public class FibwoRecursion {
int n1 = 0;
int n2 = 1;
int s = 0;
void fibonacciwr(int n)
{
if (n<=0)
return;
while ( n > 0) {
s = n1 + n2;
n1 = n2;
n2 = s;
n = n - 1;
System.out.println(s);
}
}
fr.fibonacciwr(6);
}
}
Final variable
All methods and variables are overridden in subclasses. To prevent the subclasses from
overriding the members of the superclass, declare them final using the keyword final as
a modifier.
Final variables are nothing but constants. We cannot change the value of a final variable
once it is initialized.
class finalvariable{
final int temp = 10;
}
public class FinalExample1 {
class finalvariable{
final int temp;
finalvariable(int x){
temp = x;
}
}
public class FinalExample1 {
Final method
A final method cannot be overridden, which means even though a sub class can call the
final method of parent class without any issues but it cannot override it.
class s1{
void display() { // Add final keyword
System.out.println(" Super class ");
}
}
class d1 extends s1{
void display() { /this method should be in comment
super.display();
System.out.println(" Derived class ");
}
}
public class FinalExample3 {
Final class:
When a class is declared with final keyword, it is called a final class. There are two uses
of a final class:
One is definitely to prevent inheritance, as final classes cannot be extended (inherited).
For example, all Wrapper Classes like Integer, Float etc. are final classes. We cannot
extend them.
The other use of final with classes is to create an immutable class like the predefined
String class.
}
---------------------------------------------------------------------------
Final variable
Final method
Final class
---------------------------------------------------------------------------
A class that is declared with abstract keyword is known as abstract class in java. It can
have abstract and non-abstract methods (method with body). It needs to be extended
and its method implemented. It cannot be instantiated.
A method that is declared as abstract and does not have implementation is known as
abstract method.
In short Abstract class means it must be extended and an abstract method means it must
be overridden.
If you declare an abstract method, you MUST mark the class abstract as well. You can’t
have an abstract method in a non-abstract class. But you can mix both abstract and non-
abstract method in an abstract class.
By marking the class as abstract, the compiler will stop creating an instance. You cannot
create the object.
With an abstract class, doing the work at runtime are instances of a subclass of your
abstract class.
The important point is that the reference type and the object type are the same. i.e.
Rectangle1
But with polymorphism, the reference and the object can be different. GraphicShape and
Rectangle1. Reference variable type is declared as GraphicShape, but the object is
Rectangle1.
With polymorphism, the reference type can be a superclass of the actual object type.
public class AbstractExample1 {
public static void main(String[] args) {
If you can declare a reference variable of a supertype, and assign a subclass object to it,
think of how that might work when the reference is an argument to a method.
If I write my code using polymorphic arguments, where I declare the method parameter
as a super-class type, I can pass in any subclass object at runtime. Because that also
means I can write my code, go on vacation, and someone else can add new subclass
types to the program and my methods will still work.
/*
Describe abstract class called Shape which has three subclasses say Triangle,
Rectangle, Circle. Define one method area()in the abstract class and override this area()
in these three subclasses to calculate for specific object i.e. area() of Triangle subclass
should calculate area of triangle etc. Same for Rectangle and Circle.
*/
import java.util.Scanner;
What is an Interface?
An interface is just like Java Class, but it only has static constants and
abstract method. Java uses Interface to implement multiple inheritance. A
Java class can implement multiple Java Interfaces. All methods in an
interface are implicitly public and abstract.
Another class "Combo drive" is inheriting both CD and DVD (see image
below). Which play method should it inherit? This may cause serious design
issues. And hence, Java does not allow multiple inheritance.
Another example of Dog:
Suppose you have a requirement where class "dog" inheriting class "animal" and "Pet"
(see image below). But you cannot extend two classes in Java. So what would you do?
The solution is Interface.
// Example -1
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
// Example-2
interface Pet{
int a = 10;
public void test();
}
interface A{
public void disp();
}
interface B{
public void disp();
}
Example:
interface A {
default void disp(){
System.out.println("Interface A default method");
}
}
interface B {
default void disp(){
System.out.println("Interface B default method");
}
}
When you extend an interface that contains a default method, you can do the
following:
1 Not mention the default method at all, which lets your extended interface
inherit the default method.
2 Redeclare the default method, which makes it abstract.
3 Redefine the default method, which overrides it.
We can define static methods which don’t require any object for calling.
interface Petd{
int a = 10;
static void test(){
System.out.println("Interface Method Implemented");
}
}
public class InterfaceExample3 implements Petd{
// Another Example
interface Drawable{
void draw();
}
}
// another Example
interface Inf1{
void method1();
}
interface Inf2 extends Inf1{
void method2();
}
interface Banksbi{
public void disp();
int x = 10;
}
interface Bankpnb{
public void disp();
int x = 100;
}
public class InterfaceExample5 implements Banksbi,Bankpnb {
public void disp() {
System.out.println("Hello Interface");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample5 obj = new InterfaceExample5();
obj.disp();
System.out.println(Banksbi.x);
System.out.println(Bankpnb.x);
}
// Another Example
interface Banksbi{
public void disp();
int x = 10;
public int calintrest();
}
interface Bankpnb{
public void disp();
int x = 100;
public int calintrest(int a);
}
public class InterfaceExample5 implements Banksbi,Bankpnb {
public void disp() {
System.out.println("Hello Interface");
}
public int calintrest() {
return(6);
}
public int calintrest(int a) {
return(a);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceExample5 obj = new InterfaceExample5();
obj.disp();
System.out.println(Banksbi.x);
System.out.println(Bankpnb.x);
System.out.println(obj.calintrest());
System.out.println(obj.calintrest(7));
}
interface Circle{
void area_circle();
void circum_circle();
}
interface Square{
void area_square();
void circum_square();
}
interface Rectangle1{
void area_rect();
void circum_rect();
}
class drgShapes implements Circle,Square,Rectangle1{
public void area_circle(int r){
double area=3.14*Math.sqrt(r);
System.out.println("Area of Circle :" + area);
}
public void circum_circle(int r){
double circum=6.28*r;
System.out.println("Circumference of Circle :" + circum);
}
public void area_square(int a){
int area=a*a;
System.out.println("Area of Square :" + area);
}
public void circum_square(int a){
int circum=4*a;
System.out.println("Circumference of Square :" + circum);
}
public void area_rect(int l,int b){
int area=l*b;
System.out.println("Area of Rectangle :" + area);
}
public void circum_rect(int l,int b){
int circum=2*l+b;
System.out.println("Circumference of Rectangle :" + circum);
}
@Override
public void area_rect() {
// TODO Auto-generated method stub
}
@Override
public void circum_rect() {
// TODO Auto-generated method stub
}
@Override
public void area_square() {
// TODO Auto-generated method stub
}
@Override
public void circum_square() {
// TODO Auto-generated method stub
}
@Override
public void area_circle() {
// TODO Auto-generated method stub
}
@Override
public void circum_circle() {
// TODO Auto-generated method stub
}
}
public class InterfaceExample6 {
}
Must know facts about Interface
A Java class can implement multiple Java Interfaces. It is necessary that the class must
implement all the methods declared in the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning which classes it
belongs.
Class needs to provide functionality for the methods declared in the interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only one class
but implement any number of interfaces
An interface cannot implement another Interface. It has to extend another interface if
needed.
An interface which is declared inside another interface is referred as nested interface
At the time of declaration, interface variable must be initialized. Otherwise, the compiler
will throw an error.
The class cannot implement two interfaces in java that have methods with same name
but different return type.
Make a class that doesn’t extend anything (other than Object) when your new class
doesn’t pass the IS-A test for any other type.
Make a subclass (in other words, extend a class) only when you need to make a more
specific version of a class and need to override or add new behaviours.
Use an abstract class when you want to define a template for a group of subclasses,
and you have at least some implementation code that all subclasses could use.
Make the class abstract when you want to guarantee that nobody can make objects of
that type.
Use an interface when you want to define a role that other classes can play, regardless
of where those classes are in the inheritance tree.
When you don’t want anyone to make a new object of that class type, mark the class with
the abstract keyword.
If a class has even one abstract method, the class must be marked abstract.
An abstract method has no body, and the declaration ends with a semicolon (no curly
braces).
All abstract methods must be implemented in the first concrete subclass in the
inheritance tree.
Every class in Java is either a direct or indirect subclass of class Object (java.lang.
Object).
JAVA PACKAGE
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
The Java API is a library of prewritten classes, that are free to use, included
in the Java Development Environment.
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import
keyword:
We can assume package as a folder or a directory that is used to store similar
files.
In short interfaces and classes with the same name cannot appear in the
same package, they can appear in different packages. This is possible by
assigning a separate namespace to each package.
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like d:/abc. If you want to keep the package
within the same directory, you can use . (dot).
import package.*;
import package.classname;
fully qualified name.
1. Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2. Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname
//save by B.java
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
//save by B.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
package mypack;
public class calculator {
public int add(int a, int b){
return a+b;
}
}
import mypack.*;
public class calc{
public static void main(String args[]){
calculator obj = new calculator();
System.out.println(obj.add(100, 200));
}
}
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize
the package further.
As an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized
the java package into subpackages such as lang, net, io etc. and put the Input/Output
related classes in io package, Server and ServerSocket classes in net packages and so
on.
Example of Subpackage
package pack.subpack;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java pack.subpack.Simple
Output:Hello subpackage
java.lang.*
This package is used for achieving the language functionalities such as
conversion of data from string to fundamental data, displaying the result on
to the console, obtaining the garbage collector. This is the package which is
by default imported for each and every java program.
java.io.*
This package is used for developing file handling applications, such as,
opening the file in read or write mode, reading or writing the data, etc.
java.awt.event.*
Event is the sub package of awt package. This package is used for
providing the functionality to GUI components, such as, when button is
clicked or when check box is checked, when scroll box is adjusted either
vertically or horizontally
.
java.applet.*
This package is used for developing browser oriented applications. In other
words this package is used for developing distributed programs. An applet is
a java program which runs in the context of www or browser.
java.net.*
This package is used for developing client server applications.
java.util.*
This package is used for developing quality or reliable applications in java or
J2EE. This package contains various classes and interfaces which improves
the performance of J2ME applications. This package is also known as
collection framework (collection framework is the standardized mechanism
of grouping of similar or different type of objects into single object. This
single object is known as collection object).
java.text.*
This package is used for formatting date and time on day to day business
operations.
java.lang.reflect.*
Reflect is the sub package of lang package. This package is basically used
to study runtime information about the class or interface. Runtime
information represents data members of the class or interface, Constructors
of the class, types of methods of the class or interface.
java.sql.*
This package is used for retrieving the data from data base and performing
various operations on data base.
/* if Comp class is used in this file, and if the class file is available, this
program will compile successfully; but if the Comp.class file is not available
and that class is stored in Comp.java file, then when you compile this class,
it will automatically compile that Comp.java file and create Comp.class and
this program will compile successfully;
*/
class Comp{
void disp(){
System.out.println("disp method of Computer ");
}
}
class Mech{
void dispClass2() {
Comp c1 = new Comp();
c1.disp();
}
}
class AutoCompile{
public static void main(String args[]){
Mech m = new Mech();
m.dispClass2();
}
}
------------------------------
EXCEPTION HANDLING
------------------------------
Exception handling allows us to handle the runtime errors caused by
exceptions.
What is an exception?
String t = “two”;
int y = Integer.parseInt(t);
This message is not user friendly so a user will not be able to understand
what went wrong. In order to let them know the reason in simple language,
we handle exceptions. We handle such conditions and then print a user
friendly warning message to user, which lets them correct the error.
Most of the time exception occurs due to bad data provided by user. There
can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by user etc.
Exception handling ensures that the flow of the program doesn’t break when
an exception occurs.
Errors indicate that something is wrong and the application will crash rather
than try to handle the error.
Exceptions are events that occur in the code. A programmer can handle
such conditions and take necessary corrective actions. Few examples:
Checked exceptions
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These
exceptions are not checked at compile-time so compiler does not check, but
it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block.
catch block
A catch block is where you handle the exceptions, this block must follow the
try block. A single try block can have several catch blocks associated with it.
You can catch different exceptions in different catch blocks. When an
exception occurs in try block, the corresponding catch block that handles
that particular exception executes.
EXAMPLE-1
public class ExceptionExample1 {
}
OUTPUT:
You should not divide a number by zero
I'm out of try-catch block in Java.
Why we need other catch handlers when we have a generic that can handle
all?
This is because in generic exception handler you can display a message but
you are not sure for which type of exception it may trigger so it will display
the same message for all the exceptions and user may not be able to
understand which exception occurred. That is the reason you should place
all the specific exception catch blocks before generic.
EXAMPLE-2
public class ExceptionExample2 {
}
OUTPUT:
Warning: ArrayIndexOutOfBoundsException
Out of try-catch block...
Example:-
catch(NumberFormatException e){
temp=0;
lena = lena - 1;
}
System.out.println("temp =" + temp);
sum = sum +temp;
}
System.out.println("Sum =" + sum);
try{
avg = sum /lena;
}
catch(ArithmeticException e){
avg = 0.0f;
}
Exception Meaning
Arithmetic error, such as integer divide-by-
ArithmeticException
zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
Assignment to an array element of an
ArrayStoreException
incompatible type.
ClassCastException Invalid cast.
An attempt is made to use an undefined
EnumConstantNotPresentException
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on
IllegalMonitorStateException
an unlocked thread.
Environment or application is in an incorrect
IllegalStateException
state.
Requested operation not compatible with current
IllegalThreadStateException
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException The array created with a negative size.
NullPointerException Invalid use of a null reference.
Invalid conversion of a string to a numeric
NumberFormatException
format.
SecurityException Attempt to violate security.
Attempt to index outside the bounds of a
StringIndexOutOfBoundsException
string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
ClassNotFoundException Class not found.
Attempt to clone an object that does not
CloneNotSupportedException
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
Attempt to create an object of an abstract
InstantiationException
class or interface.
One thread has been interrupted by another
InterruptedException
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
ReflectiveOperationException Superclass of reflection-related exceptions.
Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");
OUTPUT:
WelCome for Voting
Exception in thread "main" java.lang.ArithmeticException: Age is not valid
at ExceptionExample6.validateage(ExceptionExample6.java:5)
at ExceptionExample6.main(ExceptionExample6.java:13)
The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to see
if it has a catch statement that matches the type of exception. If it finds a
match, control is transferred to that statement otherwise next enclosing try
block is checked and so on. If no matching catch is found then the default
exception handler will halt the program.
Class constructors
Throwable(): This constructs a new throwable with null as its detail
message.
Throwable(String message): This constructs a new throwable with the
specified detail message.
Throwable(String message, Throwable cause): This constructs a new
throwable with the specified detail message and cause.
Throwable(Throwable cause): This constructs a new throwable with the
specified cause.
Class methods
1 Throwable fillInStackTrace()
This method fills in the execution stack trace.
2 Throwable getCause()
This method returns the cause of this throwable or null if the cause is
nonexistent or unknown.
3 String getLocalizedMessage()
This method creates a localized description of this throwable.
4 String getMessage()
This method returns the detail message string of this throwable.
5 StackTraceElement[] getStackTrace()
This method provides programmatic access to the stack trace information
printed by printStackTrace().
6 Throwable initCause(Throwable cause)
This method initializes the cause of this throwable to th
thee specified value.
7 void printStackTrace()
This method prints this throwable and its backtrace to the standard error
stream.
8 void printStackTrace(PrintStream s)
This method prints this throwable and its backtrace to the specified print
stream.
9 void
id printStackTrace(PrintWriter s)
This method prints this throwable and its backtrace to the specified print
writer.
10 void setStackTrace(StackTraceElement[] stackTrace)
This method sets the stack trace elements that will be returned by
getStackTrace() and printed by printStackTrace() and related methods.
11 String toString()
This method returns a short description of this throwable.
System.out.println(e.getMessage());
System.out.println("");
System.out.println(e.toString());
System.out.println("");
// Prints what exception has been thrown
System.out.println(e);
System.out.println("");
// printStackTrace method
// prints line numbers + call stack
e.printStackTrace();
}
}
}
OUTPUT:
/ by zero
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at ExceptionExample16.main(ExceptionExample16.java:8)
Throws
Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that method
gets a prior knowledge about which exceptions are to be handled. A method
can do so by using the throws keyword.
Throws indicate that this method might throw one of the listed type
exceptions. The caller to these methods has to handle the exception using a
try-catch block.
We can use throws keyword to delegate the responsibility of exception
handling to the caller (It may be a method or JVM) then caller method is
responsible to handle that exception.
Syntax:
type method_name(parameters) throws exception_list
{ //definition of method }
exception_list is a comma separated list of all the exceptions which a
method might throw.
OUTPUT:
Inside check function
Caught--java.lang.ArithmeticException: demo
You just need to extend the Exception class to create your own Exception
class. These are considered to be checked exceptions.
An exception class is like any other class, containing useful fields and
methods.
----------Example--------
import java.util.*;
class RangeException extends Exception
{
}
public class ExceptionExample8 {
static int add() throws RangeException{
int sum = 0;
System.out.println("Enter the number for summation");
for(int i=0;i<5;i++) {
Scanner s = new Scanner (System.in);
int no = s.nextInt();
if(no > 25 && no <50) {
throw new RangeException();
}
sum = sum + no;
}
return(sum);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int Total = add();
System.out.println("Total =" + Total);
}
catch(RangeException e) {
System.out.println("No is out of range");
}
}
}
----------------Example--------------
import java.util.*;
class RangeOutofException extends Exception
{
}
public class ExceptionExample9 {
A finally block is where you put code that must run regardless of an
exception.
-------------Example-------------
import java.util.*;
class RangeOutofException extends Exception
{
}
public class ExceptionExample9 {
import java.util.*;
class SemException extends Exception
{
}
public class ExceptionExample11 {
int sem;
String name;
Scanner Sc = new Scanner(System.in);
-----Another Example-----------
import java.util.*;
class NotSufficientFundException extends Exception
{
}
public class ExceptionExample10 {
String name;
int ac_no;
String type;
long balance;
Scanner s = new Scanner(System.in);
void getData(){
System.out.print("Enter name:");
name=s.nextLine();
System.out.print("Enter number:");
ac_no=s.nextInt();
System.out.print("Enter type(Saving/Current):");
type=s.nextLine();
System.out.print("Enter initial Balance:");
balance=s.nextLong();
}
void display(){
System.out.println("Name :"+name);
System.out.println("Number :"+ac_no);
System.out.println("Type :"+type);
System.out.println("Balance :"+balance);
}
void deposit(){
System.out.print("Enter amount to deposit :");
int amt = s.nextInt();
balance = balance + amt;
System.out.println("New Balance :"+ balance);
}
void withdraw() throws NotSufficientFundException{
System.out.print("Enter amount to withdraw :");
int amt = s.nextInt();
if(balance > amt){
balance -= amt;
System.out.println("New Balance :"+ balance);
}
else
throw new NotSufficientFundException();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionExample10 cust = new ExceptionExample10();
System.out.println("\n1. Open an Account");
System.out.println("\n2. Deposit");
System.out.println("\n3. Withdraw");
System.out.println("\n4. Display");
System.out.println("\n5. Exit");
Scanner s = new Scanner(System.in);
System.out.print("\n\n. Enter your choice(1-5):");
boolean ac_opened = false;
int choice = s.nextInt();
switch(choice)
{
case 1: if( ac_opened == false){
cust.getData();
ac_opened=true;
}
else
System.out.println("Your account
is opened !!");
break;
case 2: cust.deposit(); break;
case 3:
try{
cust.withdraw();
}
catch(NotSufficientFundException e)
{ System.out.println("Not sufficient fund");
}
break;
case 4: cust.display(); break;
case 5: System.exit(0);
default : System.out.println("Enter choice between 1 to
5");
}
}
------------------------------------------
In Below Example constructor of MyExampleException requires a
string as its argument. The string is passed to parent class
Exception’s constructor using super().
}
OUTPUT:
Caught
Error Generated
-----------------------------------------------
In a nut shell:
Important points to remember about throws keyword:
throws keyword is required only for checked exception and usage of throws
keyword for unchecked exception is meaningless.
throws keyword is required only to convince compiler and usage of throws
keyword does not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the
method about the exception.
Throw
1. Java throw keyword is used to explicitly throw an exception.
2. Checked exception cannot be propagated using throw only.
3. Throw is followed by an instance.
4. Throw is used within the method.
5. You cannot throw multiple exceptions.
Throws
1. Java throws keyword is used to declare an exception.
2. Checked exception can be propagated with throws.
3. Throws is followed by class.
4. Throws is used with the method signature.
5. You can declare multiple exceptions e.g. public void method()throws
IOException,SQLException
In the above example exception occurs in m() method where it is not handled, so it
is propagated to previous n() method where it is not handled, again it is
propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method, p()
method, n() method or m() method.
------------------------------------------------------------------------------------------
Give Answer:
1) What is the output of the following program?
public class Test
{
public static void main(String[] args)
{
try
{
System.out.printf("1");
int sum = 9 / 0;
System.out.printf("2");
}
catch(ArithmeticException e)
{
System.out.printf("3");
}
catch(Exception e)
{
System.out.printf("4");
}
finally
{
System.out.printf("5");
}
}
}
System.out.printf("7");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionExample13 obj = new ExceptionExample13();
obj.m1();
}
With more than one call Stack, we get the appearance of having multiple
things happen at the same time. In reality, only a true multiprocessor system
can actually do more than one thing at a time, but with Java threads, it can
appear that you're doing several things simultaneously. In other words,
execution can move back and forth between stacks so rapidly that you feel as
though all stacks are executing at the same time.
Multiple threading in Java means we have to look at both the thread and the
job that's run by the thread. And we will also have to look at the Thread class
in the java.lang package.
Every Java application starts up a main thread - the thread that puts the
main() method on the bottom of the stack. The JVM is responsible for starting
the main thread. As a programmer, you can write code to start other threads
of your own.
Java's multithreading system is built upon the Thread class, its methods, and
its companion interface - Runnable.
The Thread class defines several methods that help in manage threads.
The easiest way to create a thread is to create a class that implements the
Runnable interface.
Pass the new Runnable object to the Thread constructor. This tells the new
Thread object which method to put on the bottom of the new stack- the
Runnable's run() method.
myThread.start();
Nothing happens until you call the Thread's start() method. When the new
thread starts up, it takes the Runnable object's run() method and puts it on
the bottom of the new thread's stack.
When you pass a Runnable to a Thread constructor, you're really just giving
the Thread a way to get to a run() method. You're giving the Thread its job to
do.
System.out.println("Back in main()");
}
}
--------------------------------------------------------------------------------------------------
The thread scheduler makes all the decisions about who moves from
runnable to running, and about when (and under what circumstances) a
thread leaves the running state. The scheduler decides who runs, and for
how long, and where the threads go when the scheduler decides to kick them
out of the currently-running state.
The scheduler implementations are different for different JVM's, and even
running the same program on the same machine can give you different
results.
Putting a thread to sleep, even for a few milliseconds, forces the currently-
running thread to leave the running state, thus giving another thread a
chance to run.
Thread Priorities
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of
1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.
------------------------------------------------------------------------------------------------
domore();
}
public void domore(){ System.out.println("top of the
stack");
}
}
myThread.start(); System.out.println(myThread.getName());
System.out.println("after start(), tt.isAlive()=" +
myThread.isAlive());
try {
Thread.sleep(1000); System.out.println("Back
in main()");
}catch(InterruptedException ex) {
ex.printStackTrace();
}
}
Output:
before start(), tt.isAlive()=false
Thread-0
after start(), tt.isAlive()=true top
of the stack
Back in main()
---------------------------------------------------------------------------
}
public void run() {
}
}
Output:
Thread names are following:
Thread1
Thread2
Inside run( ), we will define the code that constitutes the new thread. Example:
When the thread is started it will call the run() method of the MyClass instance
instead of executing its own run() method.
The second way to create a thread is to create a new class that extends
Thread, then override the run() method and then to create an instance of that
class. The run() method is what is executed by the thread after you call
start(). Here is an example of creating a Java Thread subclass:
class MyThreadclass extends Thread{
public void run(){
System.out.println("My Thread Class running");
}
}
To create and start the above thread you can do so like this:
}
}
class A1 {
public void f1() {
System.out.println();
}
}
public class ThreadingExample7 extends A1 implements Runnable{
public void run() {
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadingExample7 t = new ThreadingExample7();
t.f1();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}
}
Output:
New thread: Thread[One,5,main] New
thread: Thread[Two,5,main] New
thread: Thread[Three,5,main] One: 5
Two: 5
Three: 5
Three: 4
Two: 4
One: 4
Three: 3
Two: 3
One: 3
Two: 2
One: 2
Three: 2
Three: 1
One: 1
Two: 1
ThreeExiting.
OneExiting.
TwoExiting.
Main thread exiting.
For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be
closing the same file.
In short when more than one thread try to access a shared resource, we
need to ensure that resource will be used by only one thread at a time. The
process by which this is achieved is called synchronization. The
synchronization keyword in java creates a block of code referred to as
critical section.
class PrintCounter {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter---"+ i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadCounter extends Thread {
private String threadName;
PrintCounter PC;
ThreadCounter(String name, PrintCounter pc) {
threadName = name;
PC = pc;
}
T1.start();
T2.start();
}
}
OutPut:
Starting -- Thread - 1
Starting -- Thread - 2
Counter --- 5
Counter --- 5
Counter --- 4
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 3
Counter --- 1
Counter --- 2
Counter --- 1
Thread --Thread - 1 exiting. Thread
--Thread - 2 exiting.
class PrintCounter {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter---" + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadCounter extends Thread {
private String threadName;
PrintCounter PC;
ThreadCounter(String name, PrintCounter pc) {
threadName = name;
PC = pc;
}
T1.start();
T2.start();
}
}
Output:
Starting -- Thread - 1
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread --Thread - 1 exiting.
Starting -- Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread --Thread - 2 exiting.
}
Output:
Main thread execution completes
Child Thread executing Interruption
occur
Stream Classes
In Java, a stream is a path along which the data flows. Every stream has a
source and a destination. We can build a complex file processing sequence
using a series of simple stream operations.
Two fundamental types of streams are Writing streams and Reading streams.
While a Writing streams writes data into a source (file), a Reading streams is
used to read data from a source (file).
Types of Streams
The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be
categorized into two groups based on the data type on which they operate.
Byte stream classes Character stream classes
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
import java.io.*;
public class fileIOExample1 {
We can re-write the above example, which makes the use of these two
classes to copy an input file (having unicode characters) into an output file –
import java.io.*;
public class fileIOExample2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are three popular methods to create file in java.
File.createNewFile()
java.io.File class can be used to create a new File in Java. When we initialize
File object, we provide the file name and then we can call createNewFile()
method to create new file in Java.
File createNewFile() method returns true if new file is created and false if file
already exists.
This method also throws java.io.IOException when it is not able to create the
file.
The files created is empty and of zero bytes.
When we create the File object by passing file name, it can be with absolute
path, or we can provide relative path.
For non-absolute path, File object tries to locate files in the project root
directory. If we run the program from command line, for non-absolute path,
File object tries to locate files from the current directory.
import java.io.File;
import java.io.IOException;
import java.io.*;
public class FileExample1 {
FileOutputStream.write(byte[] b)
If you want to create a new file and at the same time write some data into it,
you can use FileOutputStream write method. Below is a simple code snippet
to show it’s usage. The rules for absolute path and relative path discussed
above is applicable in this case too.
import java.io.*;
public class fileIOExample4{
try {
// create new file output stream
fos = new FileOutputStream("F://test.txt");
// prints
System.out.print(c);
}
} catch(Exception ex) {
// if an error occurs
ex.printStackTrace();
} finally {
// closes and releases system resources from stream
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
}
}
}