Java Basics:: Unit-I
Java Basics:: Unit-I
Java Basics:
History of JAVA
Java is a high level programming Language. It was introduced by ―SUN Microsystems‖ in June
1995. It was developed by a team under James Gosling. Its original name was ―OAK‖ and later
renamed to Java. Java has become the standard for Internet applications.
Since the Internet consists of different types of computers and operating systems. A common
language needed to enable computers. To run programs that run on multiple plot forms.
Java is Object-Oriented language built on C and C++. It derives its syntax from C and its
Object-Oriented features are influenced by C++.
Java can be used to create two types of programs
Applications
Applets.
An application is a prg.that runs on the user‗s computers under the operating system.
An Applet is a small window based prg.that runs on HTML page using a java enabled web
browser like internet Explorer, Netscape Navigator or an Applet Viewer.
JDK provides tools in the bin directory of JDK and they are as follows:
Javac: Javac is the java compiler that translates the source code to byte codes. That is, it
converts the source file. Namely the .java file to .class file.
Java: The java interpreter which runs applets and Applications by reading and interpreting the
byte code files. That is, it executes the .class file.
Javadoc: Javadoc is the utility used to produce documentation for the classes from the java files.
JDB: JDB is a debugging tool.
The way these tools are applied to build and run application programs is as follows:
The source code file is created using a text editor and saved with a .java (with Extension). The
source code is compiled using the java compiler javac. This translates source code to byte
codes. The compiled code is executed using the java interpreter java.
UNIT-I
7. Multithreaded: Java was designed to meet the real-world requirement. To achieve this, java
supports multithreaded programming. It is the ability to run any things simultaneously.
8. Dynamic: That is run time. This makes it possible to dynamically link code in a safe and
secure manner.
9. Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the main
problems facing programmers is that no guarantee exists that if you write a program today, it will
run tomorrow—even on the same machine.
Operating system upgrades, processor upgrades, and changes in core system resources can all
combine to make a program malfunction. The Java Virtual Machine (JVM) in an attempt to alter
this situation. Their goal was ―write once; run anywhere, anytime, forever.
Comments: There are 3 types of comments defined by java. Those are Single line comment,
multilane comment and the third type is called documentation comment. This type of comment is
used to produce an HTML file that documents your prg.
// this is single line comment.
/* this multiple
line comment*/
/** this documentation comment */
Key words:
Keywords are the words. Those have specifics meaning in the compiler. Those are called
keywords. There are 49 reserved keywords currently defined in the java language. These
keywords cannot be used as names for a variable, class or method. Those are,
First, every variable has a type, every expression has a type, & every type is strictly defined.
Second, all assignments, whether explicit or via parameter passing in method calls, are checked
for type compatibility. There are no automatic coercions or conversions of conflicting types as in
some languages.
The Java compiler checks all expressions and parameters to ensure that the types are compatible.
Any type mismatches are errors that must be corrected before the compiler will finish compiling
the class.
For example, in C/C++ you can assign a floating-point value to an integer as shown below
int n=12.345;
where in the above case the integer variable holds only the round part of the assigned fraction
value as n=12.
In Java, you cannot. Also, in C there is not necessarily strong type-checking between a
parameter and an argument. In Java, there is.
DATA TYPES:
The data, which gives to the computer in different types, are called Data Types or Storage
representation of a variable is called Data Type. Java defines 8 types of data: byte, short, int,
long, float, double, char and Boolean.
These can be put in Four types:
Integer: this group includes byte, short, int & long, which are whole valued signed numbers.
Floating-point numbers: float & double, which represents numbers with fractional precision.
Character: This represents symbols in a character set, like letters and numbers.
Boolean: This is a special type for representing true / false values.
Examples of boolean
class BoolTest b = false;
{ if(b) {
public static void main(String args[]) System.out.println("This is not executed.");}
{ System.out.println("10 > 9 is " + (10 > 9));
boolean b; }
b = false; }
System.out.println("b is " + b); Output:
b = true; b is false
System.out.println("b is " + b); b is true
if(b){ This is executed.
System.out.println("This is executed."); } 10 > 9 is true
Variables:
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. In Java, all variables must be declared before
they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...];
Ex: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Constant identifiers:
Final keyword is used for constants. Constant identifiers consist of all capital letters. Internal
words are separated by an underscore (_).
Example: final double TAX_RATE = .05
} }
y = 100; // Error! y not known here }
// x is still known here. Output: x and y: 10 20 x is 40
System.out.print("\tx is " + x);
Types of variables: Java has 4 different kinds of variables
local variables
parameter variables
class variables
instance variables
Local variables:
A local variable will exists as long as the method in which they have been created is still running
As soon as the method terminates, all the local variables inside the method are destroyed.
Example: Scope of local variables:
class SomeClass class Scope2
{ {
public static void main(String args[]) public static void main(String args[ ]) {
{ void show(){
double x; double r;
…....................Local variables r=3.14;
int y; }
} System.out.println(r ); //Causes error is not
} } accessible outside the block
}
Non-overlapping (or disjoint) scopes:
It is possible to declare two variables with the same name in two different block scopes as shown
below
class Scope {
public static void main(String args[]) {
-------
{ double r;
{
String r;
} }
}
}
Parameter variables:
A parameter variable is used to store information that is being passed from the location of the
method call into the method that is called.
class ToolBox
{ a=1.0 b=2.0
public static double min(double a,double b) //Parameter variables
{ ……………….. }
}
class MyProgram
{
UNIT-I
Instance variables:
Non static variables that are declared inside a class are called as instance variables.
class StaticData
{
int a=10,b=20; //instance variables of StaticData class
}
Life and scope of Instance variables:
It is limited only the object specified upon the class
Literals
Integer Literals
Integers are probably the most commonly used type in the typical program. Any hole number
value is an integer literal. Examples are 1, 2, 3, and 42.
Decimal literals
These are all decimal values, meaning they are describing a base 10 number. There are two other
bases which can be used in integer literals
Example: int n=10;
UNIT-I
Octal literals
Octal (base eight). Octal values are denoted in Java by a leading zero. Normal decimal numbers
cannot have a leading zero.
Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of
octal‟s 0 to 7 range.
Example: int n=07;
Hexadecimal literals:
Hexadecimal (base 16), A more common base for numbers used by programmers is
hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits.
You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a
hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.
Example: int n=0xfff;
Example Program:
class Literal System.out.print("decimal literal is:"+dec);
{ System.out.println("octal literal is:"+oct);
public static void main(String args[]) System.out.println("hexadecimal is:"+hex);
{ }
int dec=10,oct=07,hex=0xff; }
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
Example: float f=12.346f (or) 12.346F;
double d=34.5678d (or) 34.5678D;
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The true literal in Java does not equal 1, nor does the false literal equal 0.
OPERATORS:
Operator is a Symbol. Java provides a rich set of operators as
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as:
variable x = (expression)? value if true : value if false
int x = (10>20)? 100 : 200
Operator Precedence:
Expressions:
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language that evaluates to a single value.
int a = 0; arr[0] =
100;
System.out.println("Element 1 at index 0: " + arr[0]); int
result = 1 + 2; // result is now 3
Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete
unit of execution. The following types of expressions can be made into a statement by terminating
the expression with a semicolon (;). Ex: System.out.print(A+B);
Type Conversion and Casting:
We can assign a value of one type to a variable of another type. If the two types are compatible,
then Java will perform the conversion automatically. For example, it is always possible to assign an
int value to a long variable. However, not all types are compatible, and thus, not all type conversions
are implicitly allowed. For instance, there is no conversion defined from double to byte.
But it is possible for conversion between incompatible types. To do so, you must use a cast,
which performs an explicit conversion between incompatible types.
Java„s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will take
place if the following two conditions are satisfied:
• The two types are compatible.
• The destination type is larger than the source type.
UNIT-I
When these two conditions are met, a widening conversion (Small data type to Big data type) takes
place. For example, the int type is always large enough to hold all valid byte values, so no explicit
cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, the numeric types are not compatible with char or
boolean. Also, char and boolean are not compatible with each other.
Java also performs an automatic type conversion when storing a literal integer constant into variables
of type byte, short, or long.
Casting Incompatible Types
The automatic type conversions are helpful, they will not fulfill all needs. For example, if we want
to assign an int value to a byte variable. This conversion will not be performed automatically,
because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion.
It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
Example:
int a; byte
b;
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation. As integers do not have fractional components so, when a floating-point value is
assigned to an integer type, the fractional component is lost.
Example Program: Conversion.java
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142; System.out.println("\nConversion of
int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int."); i =
(int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte."); b =
(byte) d;
System.out.println("d and b " + d + " " + b);
}
}
UNIT-I
Let‟s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float.
Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in d*s, the
value of s is promoted to double, and the type of the sub expression is double.
Control Statements or Control Flow:
IF Statement
The IF statement is Java‗s conditional branch statement. It can be used to route program execution
through two different paths.
The general form of the if statement:
if (condition) statement1;
Here, each statement may be a single statement or a compound statement enclosed in curly braces
(that is, a block). The condition is any expression that returns a Boolean value. If the condition is
true, then statement1 is executed.
IF –ELSE Statement
If the condition is true, then statement1 is executed. Otherwise statement2 is executed.
The general form of the if statement:
if (condition) statement1;
else statement2;
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to
false.
void ifClause()
{
int a, b; if(a
< b) a = 0;
else
b = 0;
}
UNIT-I
Nested ifs
A nested if is an if statement that is the target of another if or else. Here is an example: if(i
== 10)
{
if(j < 20) a =
b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
// Use a for-each style for on a 1D array. // Use for-each style for on a 2D array
class ForEach { class ForEach3 {
public static void main(String args[]) { public static void main(String args[]) { int
int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; sum = 0;
int sum = 0; int nums[ ][ ] = new int[3][5];
// use for-each style for to display and sum the // give nums some values
values for(int i = 0; i < 3; i++)
for(int x : nums) { for(int j=0; j < 5; j++)
System.out.println("Value is: " + x); sum nums[i][j] = (i+1)*(j+1);
+= x; // use for-each to display & sum the values
} for(int x[ ] : nums) {
System.out.println("Summation: " + sum); for(int y : x) { System.out.println("Value
} is: " + y); sum += y;
} }}
Output: System.out.println("Summation: " + sum);
Value is: 1 }}
Value is: 2 Output:
Value is: 3 Value is: 1 Value is: 2 Value is: 3
Value is: 4 Value is: 4 Value is: 5
Value is: 5
Value is: 2 Value is: 4 Value is: 6
Value is: 6
Value is: 8 Value is: 10
Value is: 7
Value is: 8 Value is: 3 Value is: 6 Value is: 9
Value is: 9 Value is: 12 Value is: 15
Value is: 10 Summation: 90
Summation: 55
Nested Loops
One loop may be inside another.
Ex: Nested.java
class Nested
{
public static void main(String args[])
{ Output:
int i, j; .........
for(i=1; i<10; i++) ........
{ .......
for(j=i; j<10; j++) ......
{ .....
System.out.print("."); ....
} ...
System.out.println(); ..
} .
}
}
UNIT-I
We can create a three-dimensional array where first index specifies the number of tables, second
one number o0f rows and the third number of columns.
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
For example, the following two declarations are equivalent: int al[ ]
= new int[3];
int[ ] a2 = new int[3];
Constructors:
Constructor is a special method of a class which is invoked automatically whenever an object is
created. It has same name that of a class. A constructor initializes an object immediately upon
creation. A constructor has no return type; not even void. It cannot be abstract, final, native
,static or synchronized. this keyword refers another constructor in same class. A super keyword
will call constructor of super class constructors are of two type
1.Default constructor
2.Parameterised constructor
1. Default constructor:
A constructor that accepts no parameters is called default constructor. If no constructor is defined for
a class java system automatically generates the default constructor. A default constructor is called
when an instance is created for a class. The default constructor automatically initializes all
instance variables to zero.
Example:
class demo
{
int x,y;
float z;
demo()
{ x=1;
y=2; z=3;
}
void display()
{
System.out.println("Values of x, y and z are:"+x+" "+y+" "+z);
}
}
class Demomain
{
public static void main(String args[])
{
demo d1=new demo( ); // this is a call for the above default constructor d1.display();
}
}
Output: Values of x,y and z are: 1 2 3.0
UNIT-I
In this example, we are going to copy the values of one object into another using java
constructor.
Example:
class Student6{ {
int id; String name; System.out.println(id+" "+name); }
Student6(int i,String n){ id = i; public static void main(String args[])
name = n; {
} Student6 s1 = new Student6(111,"Karan"); Student6 s2
Student6(Student6 s){ id = = new Student6(s1);
s.id; s1.display();
name =s.name; s2.display();
} }}
void display() Output: 111 Karan
111 Karan
Methods:
Method is an action required by an object. Methods allow the programmer to modularize the
program. All variables declared in method definitions are local variables. That means they are
known only in the method in which they are defined. Most methods have a list of parameters that
provide the means for communicating information between the methods. A methods parameters are
also local variables.
Access Specifiers:
There are 4 types of java access modifiers: private, public, protected and default
Access Specifiers are the keywords that alter the meaning and accessibility (scope) of a data
member of a class, method or constructor. They are, private, public, protected and default. There
are many non-access modifiers such as static, final, abstract, native, synchronized, transient and
volatile.
private:
It can be applied to variables and methods. Private members of a class are accessible from within
the class only. They cannot be accessed from outside the class and its subclass.
Ex: class A
{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A(); System.out.println(obj.data);//Compile
Time Error obj.msg();//Compile Time Error
}
}
Output: compile time error
Role of Private Constructor: If you make any class constructor private, you cannot create the
instance of that class from outside the class.
Ex: class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){ A
obj=new A();//Compile Time Error
} } Output: compile time error
Note: A class cannot be private or protected except nested class.
public:
It can be applied to variables (data members), methods and classes. Public member of class can be
accessed globally any other code. They can be accessed from outside the class and sub class. A
public class can be accessed from any package.
class Alpha
{
public int i;
UNIT-I
private Y Y N Y N N N
public Y Y Y Y Y Y Y
protected Y Y N Y Y Y N
default Y Y Y Y Y N N
static Y Y Y - - - -
final Y Y Y - - - -
this Keyword:
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked.
UNIT-I
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using
is int read( ) throws IOException. Each time that read( ) is called, it reads a character from the
input stream and returns it as an integer value. It returns – 1 when the end of the stream is
encountered. As you can see, it can throw an IOException.
Example Program: // Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do { // read characters
c = (char) br.read(); System.out.println(c);
} while(c != 'q');
}
}
UNIT-I
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
The following program demonstrates BufferedReader and the readLine() method; The
program reads and displays lines of text until you enter the word ―stop‖:
Example Program: // Read a string from console using a BufferedReader
import java.io.*; class
BRReadLines {
public static void main(String args[]) throws
IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String
str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit."); do
{
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
Java Scanner class
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
There is a list of commonly used Scanner class methods:
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as
a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public double nextDouble() it scans the next token as a double value.
public float nextDouble() it scans the next token as a float value.
UNIT-I
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome"; //will not create new instance
In the beside example only one object will
be created. Firstly JVM will not find any
string object with the value "Welcome" in
string constant pool, so it will create a new
object. After that it will find the string
with the value "Welcome" in the pool, it
will not create new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
Java has more memory efficient, because no new objects are created if it exists already in string constant
pool.
2) By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal char
ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e. not
thread safe. It means two threads can't thread safe. It means two threads can call the
call the methods of StringBuffer methods of StringBuilder simultaneously.
simultaneously.
2) StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.
UNIT-I
System.out.println(s); // Kalpana
System.out.println(s.trim()); //Kalpana
Java String startsWith() and endsWith() method
String s="Kalpana";
System.out.println(s.startsWith("Ka")); //true
System.out.println(s.endsWith("a")); //true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output:
S
h
Java String length() method
The string length() method returns length of the string.
String s="Kalpana ";
System.out.println(s.length());//7
Output:
7
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence
of character.
String s1="Java is a programming language. Java supports OOP features.";
String replaceString=s1.replace("Java","CPP"); //replaces all occurrences of "Java" to "CPP"
System.out.println(replaceString);
Output: CPP is a programming language. CPP supports OOP features.
II
UNIT-II
Inheritance
Inheritance can be defined as the process where one class acquires the properties methods and
fields of another. With the use of inheritance the information is made manageable in a hierarchical
order. The class which inherits the properties of other is known as subclass derived class, child
class and the class whose properties are inherited is known as super class base class, parent class.
Inheritance is the mechanism of deriving new class from old one, old class is known as super
class and new class is known as subclass. The subclass inherits all of its instances variables and
methods defined by the super class and it also adds its own unique elements. Thus we can say
that subclass is specialized version of superclass.
Benefits of Java’s Inheritance
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
Classes
Superclass(Base Class) Subclass(Child Class)
It is a class from which other classes It is a class that inherits some or all
can be derived. members from superclass.
extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.
class Super{
........... } Base Class
class Sub extends Super{
............ } Derived Class
Multiple inheritance:
Deriving one subclass from more than one super classes is called multiple inheritance.
Eg. class A { statements ; }
class B { statements ; }
class C extends A, B { statements ; }
Note: Java does not support multiple inheritance with classes. But, it supports multiple
inheritance using interfaces.
II
Hybrid Inheritance: It is a combination of multiple and hierarchical inheritance.
A
HIERARCHICAL INHERITANCE MULTIPLE
B C INHERITANCE
D
A sub class uses the keyword “extends” to inherit a base class.
Output:
0
1
2
II
Since class z is inheriting class y which is in turn a sub class of the class x, indirectly z can access the
members of class x. Hence the instance of class z can access the display () method in class x, the
show () method in class y.
Problems:
In java multiple level inheritance is not possible easily. We have to make use of a concept called
interfaces to achieve it.
Super Keyword:
Whenever a sub class needs to refer to its immediate super class, we can use the super keyword.
Super has two general forms
• The first calls the super class constructor.
• The second is used to access a member of the super class that has been hidden by a
member of a sub class
Syntax:
A sub class can call a constructor defined by its super class by use of the following form of
super.
super(arg-list);
here arg-list specifies any arguments needed by the constructor in the super class .
The second form of super acts like a”this” keyword. The difference between ―this‖ and ―super‖ is
that “this” is used to refer the current object where as the super is used to refer to the super
class.
The usage has the following general form:
super.member;
Example:
class x b=1;
{ }
int a; x( ) void display( )
{ {
a=0; super.display( );
} System.out.println(b);
void display( ) }
{ }
System.out.println(a); class super_main
} {
} public static void main(String args[ ])
class y extends x {
{ y y1=new y( ); y1.display(
int b; y( ) );
}
}
{ Output: 0 1
super( );
super is a reference variable that is used to refer immediate parent class object. Uses of super
keyword are as follows:
1. super() is used to invoke immediate parent class constructors
2. super is used to invoke immediate parent class method
3. super is used to refer immediate parent class variable
II
Example:
Output:
Output:
II
Preventing Inheritance:
Final Keyword: ( last / concluding )
Final keyword can be used in the following ways:
Final Variable: Once a variable is declared as final, its value cannot be changed during
the scope of the program
Final Method: Method declared as final cannot be overridden
Final Class: A final class cannot be inherited
Using final with inheritance:
The keyword final has three uses.
• First it can be used to create the equivalent of a named constant.
• To prevent overriding.
• To prevent inheritance.
final data members:
Data member with final modifier becomes a constant.
Using final to prevent overriding:
To disallow a method from being overridden, specify final as a modifier at the start of the
declaration.
Methods declared as final cannot be overridden.
Syntax: final <return type> <method name> (argument list); final
returntype funname()
{-----
}
Using final to prevent inheritance:
Some times we may want to prevent a class from being inherited. In order to do this we must
precede the class declaration with final keyword.
Declaring a class as final implicitly declares all its methods as final. The final class can’ t be
sub classed or derived. This means that we can‟ t create a sub class from a final class.
Example:
final class A { class B
extends A{
}}
The above code gives compile error. Because class A is a final class, which can‟ t be derived.
Example of Final Variable: Final variables work like const of C-language that can‟t be altered in the
whole program. That is, final variables once created can‟t be changed and they must be used as it is
by all the program code.
II
Output:
Generally, a super class method can be overridden by the subclass if it wants a different
functionality. If the super class desires that the subclass should not override its method, it declares
the method as final. ( it gives compilation error).
II
Output
Example of Final Class: If we want the class not be sub-classed(or extended) by any other class,
declare it final. Classes declared final can not be extended.
Difference between method overloading and method overriding in java There are
many differences between method overloading and method overriding in java. A list of differences
between method overloading and method overriding are given below:
No. Method Overloading Method Overriding
1) Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method that
is already provided by its super class.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Note1: It can be applied to methods and classes. It cannot be used with data members.
Note2: It needs to be extended and its method implemented. It cannot be instantiated.
Abstract class in Java
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).
Example abstract class
abstract class A{}
1. Abstract class is a class that cannot be instantiated. (no creation of object).
2. It can be / must be inherited.
3. It can act as only base class in inheritance hierarchy. (levels)
Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
1. It is a method, which has no body (definition) in the base class. The body should be
implemented in the sub class only.
2. Any class with at least one abstract method should be declared as abstract.
3. If the sub class is not implementing an abstract method, its sub class has to implement it.
Example abstract method
As shown in the figure given above, a class extends another class, an interface extends another
interface but a class implements an interface.
II
A programmer uses an abstract class when there are some common features shared by all the
objects. Interfaces are written when the programmer wants to leave the implementation to third party
vendors. An interface is a specification of method prototypes. All the methods in an interface are
abstract methods.
An interface is a specification of method prototypes.
An interface contains zero or more abstract methods.
All the methods of interface are public, abstract by default.
Once an interface is written any third party vendor can implement it.
All the methods of the interface should be implemented in its implementation classes.
If any one of the method is not implemented, then that implementation class should
be declared as abstract.
We cannot create an object to an interface.
We can create a reference variable to an interface.
An interface cannot implement another interface.
An interface can extend another interface.
A class can implement multiple interfaces.
Defining an interface:
An interface is defined much like a class.
This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list); return-
type method-name2(parameter-list); type final-
varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list); type
final-varnameN = value;
}
Here is an example of an interface definition. It declares a simple interface that contains one method
called callback() that takes a single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. The general
form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same method will be used by
clients of either interface. The methods that implement an interface must be declared public.
II
Following is an example: // One interface can extend one or more interfaces.. interface A
{
void meth1(); void
meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A { void
meth3();
}
// This class must implement all of A and B class
MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass(); ob.meth1();
ob.meth2();
ob.meth3();
}
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated. But there are many differences
between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only
abstractmethods. abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple
inheritance. inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final
and non-static variables. variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
II
Packages in JAVA:
Java provides a mechanism for partitioning the class name space into more manageable chunks.
This mechanism is the package. The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the same package.
A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times.
Defining a Package:
• Creating a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored.
Creating a Package:
• The general form of the package statement:
package pkg; //Here, pkg is the name of the package.
//save as Simple.java
package mypack; public
class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below: javac -
d directory javafilename
For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
II
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. 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.
Example of package that import the packagename.*
//save by A.java
package pack; public
class A{
public void msg(){System.out.println(" Hello");
}}
//save by B.java package javac -d . A.java
mypack; import pack.*; javac -d . B.java
class B{ java mypack.B
public static void main(String args[]){ A obj = new A();
obj.msg();
}
} Output: Hello
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 A.java //save by B.java package
package pack; public mypack; import pack.A;
class A{
public void msg(){System.out.println(" class B1{
Hello1"); public static void main(String args[]){ A obj
} = new A();
} obj.msg();
} javac -d . A.java
} javac -d . B1.java
java mypack.B1
Output: Hello1
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface. It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack; public
class A{
public void msg(){System.out.println("Hello2"); }
} javac -d . A.java
//save by B.java package javac -d . B2.java
mypack; class B2{ java mypack.B2
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
} Output: Hello
II
• packages are able to provide the following advantages.
• Modularity
• Abstraction
• Security
• Sharability
• Reusability
• The classes contained in the packages can be easily reused in any program.
• In packages, class name can be unique. That is, two classes in two different packages can have the same
name.
• Packages provide a way to hide classes thus preventing other programs or packages from accessing classes
that are meant for internal use only.
• Packages provide a way for separating designing from coding.
• Packages provide the reusability beyond the programs.
• With the package we can reuse the classes and interfaces, so it will reduce size and time.
Static import
Static import is a feature introduced in Java programming language (versions 5 and above) that allows
members (fields and methods) defined in a class as public static to be used in Java code without specifying the
class in which the field is defined.
Example:
import static java.lang.System.*;
class Test {
public static void main(String args[]) {
// We don't need to use 'System.out‘ as imported using static.
out.println(“WELCOME");
}
}
Example1:
Package packagel;
public class ClassA
{
public void displayA(){
System.out.println("Class A");
}}
Importing the above packagel in program PackageTest1.java:
Import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA();
objectA . displayA();
}
}
Output:
ClassA
Example2:
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}