Java Unit I Part II
Java Unit I Part II
505481
UNIT-I PART-II
UNIT-I
Java Classes
The java class is a template of an object. The class defines the blueprint of an object. Every
class in java forms a new data type. Once a class got created, we can generate as many
objects as we want. Every class defines the properties and behaviors of an object. All the
objects of a class have the same properties and behaviors that were defined in the class.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods. Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
● Declaration − this is the very first step of object creation. In this step, you need to
declare a variable with the class name as the data type.
● Instantiation − Next step is the instantiation where you need to use the ‘new’
keyword to create the object.
● Initialization − finally in the third step, you need to initialize the object by calling the
class constructor.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
said to be instantiated. All the objects that are created using a single class have the same
properties and methods. But the value of properties is different for every object. Following
is the syntax of class in the java.
Syntax
<ClassName> <objectName> = new <ClassName>( );
Example:
public class CseDemo{
public CseDemo() {
// Default Constructor
[Link]("This is a default constructor");
}
public CseDemo(String name) {
// This constructor has one parameter
[Link]("Hello: " + name );
[Link]("Welcome to II CSE Java Programming");
}
Java Methods
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code
re-usability (define the code once, and use it many times).
Creating a method
A method is created inside the class and it may be created with any access specifier.
However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
❖ The methodName must begin with an alphabet, and the Lower-case letter is preferred.
❖ The methodName must follow all naming rules.
❖ If you don't want to pass parameters, we ignore it.
❖ If a method defined with return type other than void, it must contain the return
statement; otherwise, it may be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a
dot operator. It may call directly if the method defined with the static modifier. Every
method call must be made, as to the method name with parentheses (), and it must terminate
Syntax
<objectName>.<methodName>( actualArguments );
Example:
import [Link];
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner([Link]);
void readData() {
[Link]("Enter Serial Number: ");
sNo = [Link]();
[Link]("Enter the Name: ");
name = [Link]();
}
Note:
❖ The objectName must begin with an alphabet, and a Lower-case letter is preferred.
❖ The objectName must follow all naming rules.
Syntax
<returnType> <methodName>(dataType...parameterName);
Example:
public class JavaMethodWithVariableArgs {
void diaplay(int...list) {
[Link]("\nNumber of arguments: " + [Link]);
for(int i : list) {
[Link](i + "\t");
}
}
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit
method call. A constructor may have parameters and access specifiers too. In java, if you do
not provide any constructor the compiler automatically creates a default constructor.
Example:
public class ConstructorExample {
ConstructorExample() {
[Link]("Object created!");
}
public static void main(String[] args) {
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}
Output:
Object created!
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 7
KARMNAGAR -
505481
The string created using a character array cannot be extended. It does not allow appending
more characters after its definition, but it can be modified.
Example
char[] name = {'v', 'a', 'r', 'u', 'n', ' ', 'j', 'o', 'e', 'l'};
//name[10] = '@'; //ArrayIndexOutOfBoundsException
name[6] = '-';
[Link] (name);
The String class defined in the package [Link] package. The String class implements
Serializable, Comparable, and Char Sequence interfaces.
The string created using the String class can be extended. It allows us to add more
characters after its definition, and also it can be modified.
Example
String siteName = "[Link]";
siteName = "[Link]
Example
String title = "Java Programming"; // Using literals
String siteName = new String("[Link]"); // Using constructor
Note:
The String class constructor accepts both string and character array as an argument.
The following table depicts all built-in methods of String class in java.
Return
Method Description
Value
charAt(int) Finds the character at given index char
length() Finds the length of given string int
compareTo(String) Compares two strings int
compareToIgnoreCase(String) Compares two strings, ignoring case int
Concatenates the object string with argument
concat(String) String
string.
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
Checks whether two strings are same, ignoring
equalsIgnoreCase(String) boolean
case
Checks whether a string starts with the
startsWith(String) boolean
specified string
Checks whether a string ends with the
endsWith(String) boolean
specified string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
Finds the first index of argument string in
indexOf(String) int
object string
Finds the last index of argument string in
lastIndexOf(String) int
object string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
Replaces the first string with second string at
replaceAll(String, String) String
all occurrences.
Extracts a sub-string from specified start and
substring(int, int) String
end index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String
Example:
public class JavaStringExample
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 9
KARMNAGAR -
505481
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in another
class. The inheritance provides a great advantage called code re-usability. With the help of
code re-usability, the commonly used code in an application need not be written again and
again.
“The inheritance is the process of acquiring the properties of one class to another class.”
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Child class is the class which receives features from another class. The child class is
also known as the Derived Class or Subclass.
Note:
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.
✔ Multiple Inheritance
✔ Multi-Level Inheritance
✔ Hierarchical Inheritance
✔ Hybrid Inheritance
The following picture illustrates how various inheritances are implemented.
Note:
The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.
Syntax
class <ChildClassName> extends <ParentClassName>
{
...
//Implementation of child class
...
}
Example:
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass!");
[Link]("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 14
KARMNAGAR -
505481
Let's look at the following example java code, which generates an error because a class does
not allow private access specifier unless it is an inner class.
Example
private class Sample{
...
}
In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.
Example:
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
[Link]("Inside ParentClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
void accessData() {
[Link]("Inside ChildClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
//[Link]("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
[Link]();
[Link]();
}
}
Output:
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20
● Constructors must have the same name as the class within which it is defined
while it is not necessary for the method in Java.
● Constructors do not return any type while method(s) have the return type
or void if does not return any value.
● Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.
Example:
class ParentClass{
int a;
ParentClass() {
[Link]("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{
ChildChildClass(){
[Link]("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
However, if the parent class contains both default and parameterized constructor, then only
the default constructor called automatically by the child class constructor.
Example:
class ParentClass{
int a;
ParentClass(int a){
[Link]("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
[Link]("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {
Note:
The parameterized constructor of parent class must be called explicitly using the super
keyword.
Note:
The super keyword is used inside the child class only.
super to refer parent class data members
When both parent class and child class have data members with the same name, then the
super keyword is used to refer to the parent class data member from child class.
Example:
class ParentClass{
int num = 10;
}
void showData() {
[Link]("Inside the ChildClass");
[Link]("ChildClass num = " + num);
[Link]("ParentClass num = " + [Link]);
}
}
[Link]();
void showData() {
[Link]("\nInside the ParentClass showData method");
[Link]("ChildClass num = " + num1);
}
}
void showData() {
[Link]("\nInside the ChildClass showData method");
[Link]("ChildClass num = " + num2);
[Link]();
}
}
[Link]();
//[Link](); // super can't be used here
}
}
Output:
Inside the ChildClass showData method
ChildClass num = 20
Example:
class ParentClass{
int num1;
ParentClass(){
[Link]("\nInside the ParentClass default constructor");
num1 = 10;
}
ParentClass(int value){
[Link]("\nInside the ParentClass parameterized constructor");
num1 = value;
}
}
int num2;
ChildClass(){
super(100);
[Link]("\nInside the ChildClass constructor");
num2 = 200;
}
}
Note:
To call the parameterized constructor of the parent class, the super keyword must be the
first statement inside the child class constructor, and we must pass the parameter values.
Example:
class ParentClass{
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
Example:
final class ParentClass{
int num = 10;
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}
Java Polymorphism
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded
with the respective overloaded method based on the arguments.
Note:
The ad hoc polymorphism implemented within the class only.
Example:
import [Link];
Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Example:
class ParentClass{
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
public class PurePolymorphism {
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
public class PurePolymorphism {
In java, an abstract class may contain abstract methods (methods without implementation)
and also non-abstract methods (methods with implementation).
Example:
import [Link].*;
Note:
An abstract class cannot be instantiated but can be referenced. That means we cannot
create an object of an abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden
abstract method. But we may also create base class reference and assign it with child class
instance to invoke the same. The main method of the above program can be written as
follows that produce the same output.
Example
public static void main(String[] args) {
Shape obj = new Rectangle(); //Base class reference to Child class instance
[Link]();
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java, it can refer to any type of object.
The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability. The substitutability means that when a child
class acquires properties from its parent class, the object of the parent class may be
substituted with the child class object. For example, if B is a child class of A, anywhere we
expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
● Specialization
● Specification
● Construction
● Extension
● Limitation
● Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent
class just specifies which methods should be available to the child class but doesn't
implement them. The java provides concepts like abstract and interfaces to support this form
Construction
This is another form of inheritance where the child class may change the behavior defined
by the parent class (overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It holds
the principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does not hold the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.
Benefits of Inheritance
● Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
● Inheritance can save time and effort as the main code need not be written again.
● Inheritance provides a clear model structure which is easy to understand.
● An inheritance leads to less development and maintenance costs.
● With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
● In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
Costs of Inheritance
● Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
● Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
● The changes made in the parent class will affect the behavior of child class too.
BufferedReader class
The BufferedReader class of Java is used to read the stream of characters from the specified
source (character-input stream). The constructor of this class accepts an InputStream object
as a parameter.
This class provides a method known as readLine() which reads and returns the next line
from the source and returns it in String format.
The BufferedReader class doesn’t provide any direct method to read an integer from the
user you need to rely on the readLine() method to read integers too. i.e. Initially you need to
read the integers in string format.
The parseInt() method of the Integer class accepts a String value, parses it as a signed
decimal integer and returns it.
Using this convert the read Sting value into integer and use. In short, to read integer
value-form user using BufferedReader class −
● Instantiate an InputStreamReader class bypassing your InputStream object as a
parameter.
● Then, create a BufferedReader, bypassing the above obtained InputStreamReader
object as a parameter.
● Now, read integer value from the current reader as String using
the readLine() method.
● Then parse the read String into an integer using the parseInt() method of the Integer
class.
Example:1
The following Java program demonstrates how to read integer data from the user using
the BufferedReader class.
import [Link];
import [Link];
import [Link];
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
[Link] = name;
[Link] = age;
[Link] = id;
}
public void displayDetails(){
[Link]("Name: "+[Link]);
[Link]("Age: "+[Link]);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 34
KARMNAGAR -
505481
Example:2
//import [Link];
//import [Link];
//import [Link];
import [Link].*;
If you read password using Console class, it will not be displayed to the user.
The [Link] class is attached with system console internally. The Console class is
introduced since 1.5.
Example:
//Write a java program to demonstrate the console class.
import [Link].*;
class Ex_Console
{
public static void main(String[] args)
{
Console kb=[Link]();
[Link]("Enter ur name:");
String name=[Link]();
[Link]("enter your address:");
String addr=[Link]();
[Link]("Your details are:");
[Link]("Name: "+name);
[Link]("Address: "+addr);
}
}
Output:
Enter ur name: venkywn
Enter your address: karimnagar
Your details are:
Name: venkywn
Address: karimnagar
Example:2
//Write a java program to illustrate readPassword method from console class?
import [Link];
class ReadPasswordTest
{
public static void main(String args[]){
Console c=[Link]();
[Link]("Enter password: ");
char[] ch=[Link]();
String pass=[Link](ch);//converting char array into string
[Link]("Password is: "+pass);
}
}
Output:
Enter password: