JAVA PROGRAMMING
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and
Communities, messages and methods, Responsibilities, Classes and
Instances, Class Hierarchies- Inheritance, Method binding, Overriding and
Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An
Overview of Java, Data types, Variables and Arrays, operators, expressions,
control statements, Introducing classes, Methods and Classes, String
handling.
Inheritance– Inheritance concept, Inheritance basics, Member access,
Constructors, Creating Multilevel hierarchy, super uses, using final with
inheritance, Polymorphism-ad hoc polymorphism, pure polymorphism,
method overriding, abstract classes, Object class, forms of inheritance
specialization, specification, construction, extension, limitation, combination,
benefits of inheritance, costs of inheritance.
Introduction:
Java is an object-oriented programming language developed by james
goshling in the year 1996 at sun micro systems (which is now a subsidiary of
Oracle Corporation). Much of its syntax is taken from c and c++. Initially it
was called oak and later it is changed to java.
Actually it was designed for embedded application and later it was
changed to support web and enterprise applications.
We can download java software from www.java.sun.com from java1.6
java is open source.
As per Sun Microsystems (Oracle acquired Sun Microsystems in 2010)
java has three editions
J2SE/JavaSE Java 2 standard Edition
J2EE/JavaEE Java 2 Enterprize Edition
J2ME/JavaME Java 2 Micro Edition
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
J2SE/JAVASE:
J2SE is used to develop the standalone applications, desktop
application, console applications. ( Client-Side Applications)
Standalone Application: runs in the context of a local disk.
Ex: Notepad
Desktop Application: runs stand-alone in a desktop or laptop computer.
Ex: File Explorer, MS Office Applications
Console Application: run in consoles (the command prompt in Windows).
Ex: Bank ATM
For developing J2SE applications we need the java development kit
(jdk). Jdk contains the compile time environment and the runtime
environment. The compiler environment is provided by javac compiler and
the runtime environment is provided by java virtual machine(jvm)
J2EE/JAVAEE:
J2EE is used to develop web, distributed, enterprise applications.
(Server-Side Applications)
Web Application: able to access via internet.
Ex: Gmail, Shopping cart, Photo editing, File Conversion
Distributed Application: exists on multiple machines and at multiple
platforms.
Ex: Web Browsers.
Enterprise Application: use to assist the organization in
solving enterprise problems.
Ex: CRM (Customer Relationship Management), ERP (Enterprise
Resource planning)
Servlets and JSP are the technologies provided by the sun for
the development of web application and for developing distributed
applications we are having RMI and EJB technologies.
J2ME/JAVAME:
J2ME is used to develop mobile and embedded applications. (Mobile
Devices)
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Mobile Application: run on a mobile device, such as a smartphone or tablet
computer.
Ex: Downloaded from Google play store, App store(IOS).
Embedded Application: placed permanently inside some kind of device to
perform a very specific set of functions.
Ex: Video Game Consoles, GPS, Microwave Oven
Versions of JAVA:
Many java versions have been released till now. The current stable release of
Java is Java SE 13.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan 1996)
JDK 1.1 (19th Feb 1997)
J2SE 1.2 (8th Dec 1998)
J2SE 1.3 (8th May 2000)
J2SE 1.4 (6th Feb 2002)
J2SE 5.0 (30th Sep 2004) (J2SE 1.5)
Java SE 6 (11th Dec 2006)
Java SE 7 (28th July 2011)
Java SE 8 (18th March 2014)
Java SE 9 (21st Sep 2017)
Java SE 10 (20th March 2018)
Java SE 11 (25th Sep 2018)
Java SE 12 (19th March 2019)
Java SE 13 (17th Sep 2019)
Java SE 14 (March 2020)
Java SE 15 (Sep 2020)
Java SE 16 (March 2021)
Java SE 17 (Sep 2021
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Java features / Java BUZZ WORDS :
Object Oriented :
Java is a object oriented programming language as it supports the
object oriented features such as
Objects
Class
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Simple :
Java is a simple programming language, as the difficult concepts of C
and C++ such as
Pointers
operator overloading
unsigned data types
virtual functions
multiple inheritance through classes
structures & unions
Templates
variable aliases (typedef)
It also uses same syntax of C and C++, so it is easy for a programmer who is
familiar with C or C++.
Secured:
Security problems like eavesdropping, tampering, impersonation, and
virus threats can be eliminated or minimized by using Java on internet.
Virus: A program that can damage data, software or hardware of a
computer. Virus spreads fast through .dat, .exe, .com. Virus does not affects
the .txt.
Eaves dropping: Reads others data illegally.
Tampering: Not only reads data but also modifies it.
Impersonation: A person acting as another on internet.
JVM take cares of security.
Plat form independent :
Java is a platform independent language. A plat form is the hardware
and software environment on which a program executes.
Once java code compiled on one platform and will run on any platform
without making any changes i.e., write once run any where.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Platform independence is possible by making use of Java Virtual
Machine (JVM). When we compile a java program, the .class file is generated
which contains the byte code i.e., each instruction is expressed in the form of
bytes. Byte code is understandable by JVM not by the machine. JVM
interprets byte code into machine understandable format.
JVM is a platform dependent where as Java language is platform
independent.
The Java compilers and the JVM are platform dependent and .class file
is platform independent. Because of this feature, java is widely accepted as
internet language.
Architecture Neutral:
A language or technology is said to be Architecture Neutral if and only
if it can run on all processor irrespective of their architecture.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Portability ( platform independent+architecutural neutral):
A language or technology is said to be portable if and only if java
application runs on any kind of OS Architecture and processor architecture.
Robust : java is a robust i.e strong
The java programs are strong and they don’t crash easily like a c/c++
programs because of the following reasons.
Implicit memory management
Run Time Errors Handling (Exception Handling)
Implicit memory management :
In java the memory required for the program is allocated dynamically
and the unused objects are automatically garbage collected.
Allocation Deallocation
calloc()
C malloc() Free()
realloc()
C++ new Delete
Java new __
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Dynamic:
Java programs generate dynamic content. (Applets, dynamically
interacting programs on internet)
Interpreted:
Java programs are compiled to generate the byte code. This byte code
can be downloaded and interpreted by the interpreter in JVM. In Java, we use
both compiler and interpreter for the execution.
High Performance:
The problem with interpreter inside the JVM is that it is slow, By this
java programs used to run slow. To overcome this problem, along with the
interpreter, JIT (Just In Time) compiler was introduced which enhances the
speed of execution. So, now in JVM, both interpreter and JIT compiler work
together to run the program.
Multithreaded:
Multithreaded is a capability for a program to perform several tasks
simultaneously within a program.
A thread represents an individual process to execute group of
statements. JVM uses several treads to execute different blocks of code.
Creating multiple threads is called ‘multithreaded’.
Ex: Game software, which uses multiple threads simultaneously for
GUI display, Sound Effects, Timer Control, Score Updating.
In network programming, a sever can serve multiple clients at the same
time via multithreading.
Distributed:
Java introduces JAVA EE for distributed development. Using Java, we
can write programs, which capture information and distribute it to the clients
as java can handle the protocols such as TCP/IP and UDP.
A distributed application exists on different machines and at different
locations.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Java Identifiers :
An identifier is a name given to the variable, constant, method, class,
package, etc.,
Rules for constructing the identifiers
The first character of an identifier must be a letter, an underscore(_) or
a dollar sign($)
The rest of the characters in the identifier can be alphabet, digit,
underscore(_) or dollar($).
No special symbols are allowed in the identifier except underscore(_)
and dollar($).
Reserved words cannot be used as the identifiers
Java identifiers are case sensitive.
Java Naming Conventions:
Code conventions improve the readability of the software allowing
engineers to understand new code more quickly and thoroughly
Naming conventions for classes:
It starts with a uppercase letter and internal word also starts with
uppercase letter. Rest of the characters are lower case.
Ex: class Demo class MyFirstClass
{ {
------------ ------------
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
} }
Naming conventions for Interfaces:
It starts with a uppercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
Ex: interface Demo interface MyFirstClass
{ {
------------ ------------
} }
Predefined interfaces are : Runnable, Clonable, Serializable
Naming conventions for variables:
It begins with a lowercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
Ex: int x;
int age;
int myFirstSalary;
Naming conventions for Constants:
It consists of all uppercase letters.
Internal words are separated by an underscore (_)
Ex: flaot TAX_RATE =0.56f;
int MAX_VALUE=567;
Naming conventions for methods :
It start with a lowercase letter and internal word also starts with
uppercase letter. Rest of the characters are in lower case.
Ex : public void getData()
----------
Public void setData()
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
{ -----------}
Naming conventions for packages :
Packages names are written in lowercase letter.
Ex : java.lang
java.io
java.net
java.awt
animal
mypack
Reserved Words:
Reserved words are the words that have some specific meaning and
purpose. We cannot change them.
All java reserved words are written in lower case.
goto: goto is not defined or not used since the readability of the
application decreases or goes down as goto increases the
complexity of the application.
const: const is not defined since a powerful keyword final is
already available to define the constants.
Literal: A literal is a constant value which can be assigned to the
variable
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
int x=10;
int is a datatype, x is variable identifier & 10 is constant value
(literal).
true, false, null are reserved literals but can be considered as
reserved words.
Java Comment Lines:
Comments increase the readability of the application.
They are ignored by the compiler.
Java supports three types of comments:
1. Single Line Comment //-----comment-----
2. Multi-line Comment /* -----comment----- */
3. Document Comment /** ---Documentation--- */
The documentation comment is used to create documentation API. To create
documentation API, you need to use javadoc tool.
Use of Documentation Comment:
Suppose the java file is First.java then
Compile it by javac tool:
javac First.java
Create Documentation API by javadoc tool:
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
javadoc First.java
Now, there will be HTML files created for your Calculator class in the
current directory. Open the HTML files and see the explanation of Calculator
class provided through documentation comment.
Data Types:
Java supports eight data types out of which four are integral data types,
two are real floating data type, one is character data type and one boolean
type.
The difference between a float and double is float takes 7 digits after the
decimal point where as double takes 16 digits accurately after the decimal
point.
A Java character takes 2 bytes of memory since it supports all the
characters of world wide languages.
It supports the unicode character set i.e., it supports 65,536
characters. Unicode is a specification or standard to include alphabets of all
international languages into java character set. Unicode takes two bytes of
memory.
Except boolean and char, all the remaining datatypes are signed
datatypes.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
byte Literal: (-128 to 127)
byte b = -10; byte b1 = 120 Valid
byte b2 = 135; // gives compile time error as
Error: possible loss of precision
found : int
required : byte
byte b3 = ‘A’;
byte b4 = ‘AB’; //error
short Literal: (-32768 to 32767)
short s = 12610; short s1 = -30 Valid
short s2 = 32768; // gives compile time error as
Error: possible loss of precision
found : int
required : short
short s3 = ‘+’;
short s4 = ‘ ’;
int Literal: (-231 to 231-1(-2147483648 to 2147483647))
int x = -24712610; int y = 65674530 Valid
int z = 2147483648; // gives compile time error
int i = 10;
int j = 010; //Octal
int k = 0X10; //Hexa-Decimal
long Literal: (-263 to 263-1) explicitly suffixed with l/L
long x = 2147483648; // invalid
Error: integer number too long
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
long x = 2147483648L; // valid
float Literal: explicitly suffixed with f/F
float x = 17.21474; // invalid because we have to keep ‘f’ at the end
float x = 10.5f or 10.5F;
float x = 10;
float x = 010;
float x = 0X10;
float x = ‘A’;
float x = 11.2147483648F;
double Literal: explicitly suffixed with d/D
double d = 10.5d or 10.5D; // valid
char Literal: enclosed in single quotes
char ch = ‘A’;
char ch = ‘#’;
char ch=65; //A
char ch=48; //0
char ch=10234; //? Unicode character
For unicode values which are not supported by the system we get question
marks.
The unicode value may be represented in decimal, octal, hexadecimal.
char ch=075; char ch=0X234;
We can represent a character literal in unicode representation as ‘\uxxxx’
char ch=‘\uFACE’
Escape Characters:
char ch=‘\b’;
char ch=‘\n’;
char ch=‘\t’;
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
char ch=‘\f’;
char ch=‘\k’;
Escape sequence in unicode format
‘\u0008’ Backspace
‘\u0009’ Horizontal line
‘\u000a’ New line
‘\u000d’ Carriage return
‘\u000c’ Formfeed
‘\u00027’ Single quote
‘\u00022’ Double quote
boolean Literal:
boolean b = true;
boolean b = false;
boolean b = “true”; //invalid
boolean b = “false”; //invalid
String Literal:
String literal is enclosed in double quotes.
A string is a group of characters which is an object of String class
String s = “Hello”;
String s = “Hello! Welcome to Java Programming”;
String s = “Hello! \nWelcome to Java Programming\n”;
Requirements to Develop a Java Program:
1.To type your java program we need to use a editor
Editors: notepad, word pad, DOS editor , Edit plus etc
Or
We can use IDE { integrated Development Environment }
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Eclipse, Myeclipse , netbeans , etc.
2. software Requirements : jdk11/jdk12/jdk13 (any Java SE version)
From java1.6 the software is open source.
3. OS Requirements
Any OS like windows family, linux, sun solaris , MAC etc.
Simple Java Program:
import java.lang.*;
public class Demo
public static void main(String args[])
System.out.println(“ Hello ! Wel-come JAVA world “);
A java program is placed in a text file with an extension of .java
The name of the public class and the name of the java text file should be
same.
Here the above file is saved as Demo.java
The java libraries are available in the form of packages.
java.lang is the fundamental package that contains basic classes and
interfaces for the development of java applications.
java.lang is automatically available to every java program and there is no
need to import this package.
To develop a java program we need atleast one class. The allowed access
specifiers for the top level class are public or default.
If you are not specifying any access specifier it is treated as default.
Output:
Compilation-
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
javac Demo.java
Execution-
java Demo
Hello ! Wel-come JAVA World.
Variables:
A variable is a identifier whose value is not fixed.
Local variable
Instance variable
Static variable
Local variable: A variable declared inside a method is called local variable.
A local variable must be initialized before its usage
Default values are not applicable to the local variables.
Scope of the variables is within the method only. It cannot be used
outside the method.
The only modifier that is applied to the local variable is final
import java.lang.*;
public class Demo2
{
public static void main(String args[])
{
int x=10;
int y=20;
int z;
System.out.println(x);
System.out.println(y);
System.out.println(" sum is : "+x+y); // sum is : 1020
System.out.println("sum is : "+(x+y)); // sum is : 30
System.out.println(x+y+ " is sum "); // 30 is sum
// System.out.println(z): // Error: local variable Z might not have been
initialized.
}
}
Output:
10
20
sum is : 1020
sum is : 30
30 is sum
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Encapsulation:
Encapsulation is a mechanism where the data (variables) and the code
(methods) that act on the data will bind together.
Class:
A class is declared by using the keyword class. A class is a blue print
of a object.
Declaration:
<access specifier> <access modifier> class <class_name>
instance variable
static variable
instance methods
static methods
A class contains set of variables and methods and are integrated into a
single unit.
For a class Access specifiers must be public and <default>
For a class access modifier must be final, abstract, strictfp
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Object:
Object is an instance of a class. Every object will have state and
behavior. The state is maintained using variables and behavior is changed
using methods.
Creating an object:
Syntax: Class_name Object_name = new Class_name();
(or)
Class_name Object_name;
Object_name = new Class_name();
Ex: Demo d = new Demo();
(or)
Demo d;
d = new Demo();
d is reference to the Demo class object. Using new operator we can allocate
the memory dynamically. In java every memory allocation is dynamic. We can
access the instance variables using the reference name i.e., object name.
Accessing Members of a Class:
Syntax: Object_name.variablename;
Object_name.method_name();
Ex: d.x
d.setData();
Instance variable:
A variable declared inside the class and outside a method is called
instance variable.
The memory will be allocated when we construct a object.
Separate memory will be allocated for instance variables for every
creation of objects.
Default values are applied to the instance variables , a instance variable
is accessed w.r.t the object name i.e. reference name.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
The allowed access modifiers for instance variable are final, transient,
volatile and static.
The allowed access specifier are private, public , protected, default.
import java.lang.*;
public class Demo2
{
int x,y,z;
public static void main(String args[])
{
Demo2 d = new Demo2();
System.out.println(d.x+"\t"+d.y+"\t"+d.z);
d.x=100;
d.y=200;
d.z=678;
System.out.println(d.x+"\t"+d.y+"\t"+d.z);
Demo2 d1 = new Demo2();
System.out.println(d1.x+"\t"+d1.y+"\t"+d1.z);
d1.x=10;
d1.y=20;
d1.z=67;
System.out.println(d1.x+"\t"+d1.y+"\t"+d1.z);
}
}
Output:
0 0 0
100 200 678
0 0 0
10 20 67
Static variable : (class variable)
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
A static variable is declared inside the class with static keyword.
For a static variable the memory will be allocated as soon as .class file
loaded into the JVM.
Only once the memory will be allocated for static variable and it is
shared by every object.
Defaults are applied to the static variables. A static variable can be
accessed in three ways
Directly
w.r.t to object name
w.r.t to class name
if a static variable is accessed outside the class there are only two ways
w.r.t to object name
w.r.t to class name
public class S1
{
static int a=9;
int x,y;
public static void main(String args[])
{
System.out.println(" static variable using class name : "+S1.a);
S1 d=new S1();
S1 d1=new S1();
System.out.println("Static variable using object : " );
System.out.println(d.a);
System.out.println(d1.a);
d.a=89;
System.out.println(d.a);
System.out.println(d1.a);
}}
Output:
static variable using class name : 9
Static variable using object :
9
9
89
89
Method:
A method is a block of statements which performs some task.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
In java a method is defined inside the class.
Syntax:
<access specifier> <access modifier> <return type> method name(
datatype para1, datatype para2,….)
return;
Different types of methods
1. instance method
2. static method
3. factory method
4. abstract method
instance method :
It is defined inside a class without any modifier. Instance method act
upon instance variables. Instance method can be called w.r.t object i.e.
objectname.methodname;
from one instance method we can call other instance method directly.
A instance method can access a instance variables and static variables.
class Demo2
{
int x, y, z;
void increment()
{
x++;
y++;
z++;
}
void display()
{
System.out.println(x+"\t"+y+"\t"+z);
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public static void main(String args[])
{
Demo2 d= new Demo2();
d.display();
d.increment();
d.display();
Demo2 d1= new Demo2();
d1.display();
d.increment();
d1.display();
d.display();
}
}
Output:
0 0 0
1 1 1
0 0 0
0 0 0
2 2 2
this:
it is a keyword
this variable always refers to the current object
this is used to differentiate a local and instance variable.
this is can be used w.r.t instance variable and instance method and can
be used inside the constructors.
this cannot be used inside main method and static method.
class Demo9
{
int a,b,c;
void initialize(int a, int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
this.display();
}
void display()
{
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
System.out.println(a+"\t"+b+"\t"+c);
}
public static void main(String args[])
{
Demo9 d = new Demo9();
d.initialize(10,20,30);
Demo9 d1 = new Demo9();
d1.initialize(100,200,100);
}
}
Output:
10 20 30
100 200 100
Static method:
A static method is defined by using static keyword. A static method
can access only static variables but instance method can access both instance
and static variables.
A static method can be called in three ways.
Directly
w.r.t object
w.r.t class name
A static method outside the class can be called in two ways
w.r.t object
w.r.t class name.
public class Demo1
{
static int x,y,z;
int a=10;
public static void display()
{
System.out.println(x+"\t"+y+"\t"+z);
// System.out.println(a);//error because a non -static
//context cannot be referred from static content
}
public void show()
{
System.out.println(x+"\t"+y+"\t"+z);
System.out.println(a);
}
public static void main(String args[])
{
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Demo1 d=new Demo1();
display();
d.show();
}
}
Output:
0 0 0
0 0 0
10
which of the following are valid
1. public static void main(String args[])
2. public void static main(String args[])
3. Static public void main(String args[])
4. Static public void main(String args[])
5. Static public void main()
Answer : 1,3,4
Blocks: A block is a group of statements
There are two types of blocks: Instance block and static block
Instance block :
Instance blocks are declared inside the class. Instance block is called as
soon as object is created. Any number of instance can be placed inside the
java class.
The order of execution of instance block is from top to bottom.
A instance block can access instance variables , static variables, instance
methods and static methods.
class Demo2
{
int x,y,z;
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
static int a=100;
{
System.out.println(" Instance Block 1 ");
display();
}
{
System.out.println(" Instance Block 2 ");
x=100; y=200;z=300;
this.display();
m1();
}
public void display()
{
System.out.println(" Display method ");
System.out.println(x+"\t"+y+"\t"+z);
System.out.println("Static Variable : "+a);
}
public static void m1()
{
System.out.println("m1 method Static Variable : "+a);
}
public static void main(String args[])
{
Demo2 d= new Demo2();
}
}
Instance Block 1
Display method
0 0 0
Static Variable : 100
Instance Block 2
Display method
100 200 300
Static Variable : 100
m1 method Static Variable : 100
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Static block :
A static block is declared inside the java class with static keyword.
A static block is called as soon as .class file is loaded into the JVM.
Any number of static blocks can be placed inside the java class.the order
of execution of static block is from top to bottom
A block can access static variables and static methods.
Java program execution starts from main but static blocks are executed
before the main() method.
Source declaration rules:
A java program is placed in a text file with a extension of java.
The name of the publc class and the name of the text file must be same.
A java text file can have any number of default classes but only one public
class.
If a java text file contains only default classes the name of the text file can
be any name.
The no. of .class file is equal to the number of class available in the java
text file.
If java text file contains two public classes then at compile time it gives
error. No two public classes defined. A java program must contain only one
public class.
A java text file can have only one main method.(not a rule)
Java source file structures
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Package statements; // only one
Import statements; // any number
Class/interface declaration //any number
The order of above statements is to preserved otherwise we will get a
compile time error.
API : { Application Programming Interface }
Java API is organized in different packages using java API we can
develop the java applications
It is an html help file to the programmer to know the number
of packages to know the no. of classes and interfaces in a package and
methods , fields in a class or interface. We can download the API from www.
java.sun.com
Java tools
Javac : javac is a java compiler which is used to compile the java
source code. It translates the .java file to .class file.
C:\> javac -help // we get all options
C:\>javac –version // we get version of java
Javac 1.6.0 –rc
To compile a java program with previous versions of java.
C:\> javac –source 1.4 Demo.java
Java : java is a interpreter which is used to run the .class files.
C:\>java Demo
Javap : javap is java deassembler. It is used to convert bytecode (.class) into
a java program description.
C:\>javap java.lang.String (fully qualified class name)
Applet viewer : it is used to execute the applets within the browser.
JDB : it is used for java debugging mostly it is used in IDEs.
Javadoc : it is used to create the documentation for our applications
/**
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
This class is created by sakr */
Javah : it is used to provide header files of other languages such c , c++
Jar : it is used to generate archieve files. It is used to generate jar,war, rar
files
Type casting:
Conversion of one data type into another data type is known as type
casting.
There are two types of type casting: implicit type casting and explicit type
casting.
Implicit type casting : it is automatically done by the compiler. A lower
dataype is converted into higher data type. It is also called as WIDENING. No
loss of data
Explicit type casting : it is done by the programmer a higher data type is
converted to lower datatype. There is no loss of information. It is called as
NARROWING.
Syntax: (target_data_type)operand;
Ex: float f = 17.24;
int i = (float)f;
class Demo
{
public static void main(String args[])
{
int x;
float y=100.36f; // Explicit type casting
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
x = (int)y;
System.out.println(x);
System.out.println(y);
int i=67; //Explicit type casting
char ch=(char)i;
System.out.println(ch);
System.out.println(i);
}
}
Output:
100
100.36
C
67
Constructors:
A Constructor is having the same name that of a class. Constructor is
automatically called as soon as object is created. The purpose of a constructor
is to initialize the object. Constructors are not members of a class.
Java supports two types of constructors
Default constructor
Parameterized Constructor
If a contructor is not taking no parameters then it is called Default
constructor. A java class can have the maximum of one default constructor.
If a constructor is taking a parameter then it is called parameterized
constructor.
A java class can have more than one parameterized constructor but they
should differ in the number of parameters or type of parameters or order
of parameters.
If a java class is not having any constructor then the java compiler will
generate the default constructor.
The allowed access specifiers to the constructors are private, protected,
public and <default>.
If a class is having a private constructor then we cannot create the object
outside the class.
A constructor will not have a return type not even a void. If we place a
return type then it is treated as a method.
Using constructors there is no need of explicit method calls.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public class Demo1
{
int x,y;
float z;
Demo1()
{
System.out.println("Default Constructor ");
x=5;
y=10;
}
Demo1(int a,int b)
{
System.out.println("Two Parameterized Constructor ");
x=a;
y=b;
}
Demo1(int a, int b, int c)
{
System.out.println("Three Parameterized Constructor ");
x=a;
y=b;
z=c;
}
void display()
{
System.out.println(x+" "+y+" "+z);
}
}
class D
{
public static void main(String args[])
{
Demo1 d= new Demo1();
d.display();
Demo1 d1= new Demo1(10,20);
d1.display();
Demo1 d2 =new Demo1(1,2,3);
d2.display();
}
}
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Default Constructor
5 10 0.0
Two Parameterized Constructor
10 20 0.0
Three Parameterized Constructor
1 2 3.0
Constructor overloading:
Two or more parameterized constructors can exist with different
signatures i.e. the constructors are differed in either number of parameters ,
type of parameters or order of parameters.
class A
{
A()
{
System.out.println("dc");
A(int i)
{
System.out.println(i);
}
A(int i, float j)
{
System.out.println(i+"\t"+j);
}
A(int i, int j)
{
System.out.println(i+"\t"+j);
}
A(float j, int i)
{
System.out.println(i+"\t"+j);
}
}
public class Demo5
{
public static void main(String args[])
{
A a = new A();
A a1 = new A(10);
A a2 = new A(10,20);
A a3 = new A(10.3f,200);
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
A a4 = new A(100,20.5f);
}
}
dc
10
10 20
200 10.3
100 20.5
this():
this() is used to communicate from one constructor to another constructor.
this() must be the first statement inside a constructor.
this() must be used only inside a constructor.
class A
{
A()
{
this(10);
System.out.println("dc");
A(int i)
{
this(10,5.3f);
System.out.println(i);
}
A(int i, float j)
{
this(100,200);
System.out.println(i);
}
A(int i, int j)
{
this(10.5f,10);
System.out.println(i+"\t"+j);
}
A(float j, int i)
{
System.out.println(i+"\t"+j);
}
}
public class Demo
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
{
public static void main(String args[])
{
A a = new A();
}
}
10 10.5
100 200
10
10
dc
Difference between this and this():
Arrays :
An array is a collection of fixed number of Homogeneous elements.
Arrays are fixed in size. The array index start from zero
Types of arrays:
Single-dimensional
Multi-dimensional
Two-dimensional
Three-dimensional
Single Dimensional Arrays :
Declaration: int x[]; or int []x; or int[] x;
int is datatype and x is array name and [] is dimension.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
At declaration the dimension can be prefix or sufix
We should not specify the size at the time of declaration, if we specify the
size it gives compile time error.
int x[3]; means gives an error.
Construction of an array:
int x[];
x=new int[];
Or
int x[]=new int[5];
In java arrays are objects. So, we can allocate the memory dynamically by
using new operator.
At the construction we should specify the size of the array. When we
construct an array initially it contains default values.
In java it is legal to have size of the array is 0.
int x=new int[0]; -------- valid
The array size is always excepted as integer.
int x =new int[-5]; ------valid at compile time but an runtime error
Error: exception in thread “main”
java.lang.NegativeArraySizeException
The allowed data types to mention various size of array are byte, short, int,
char because all can be converted into int.
int x=new int[10.5f];---invalid gives compile time error :PLP
int x[]=new int[a];----valid
int x[]=new int[‘a’];---valid
int x[]=new int[“a”];-----invalid gives CTE : INC TYPES
Length:
Length is variable only used w.r.t arrays.
Arrayname.length returns the size of the array.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
int x[] = new int[5];
System.out.println(x.length); //prints 5
int x[]=new int[‘a’];--97
The maximum size of the array is maximum integer value (i.e.,
2147483647)
Initialization:
int x[]=new int[3];
x[0]=10;x[1]=20; x[2]=30;
Declaration , construction , initialization in a single line:
int x[]= {10,20,40};
flaot x[]={10.2f,1.4f};
double x[]=new {10.5,1.45};
If we specify the size we get an compile time error.
Multidimensional Arrays:
In java multi-dimensional arrays are array of arrays
Two Dimensional Array
Three Dimensional Array
Two Dimensional Arrays:
Declaration: int x[][]; Or int [][]x; Or int[][] x; Or int []x[];
int x[3][4]; ------- invalid
At the declaration we should not specify the size because gives an compile
time error.
String s[][];
float y[][];
byte [][]b;
Construction of 2D Array :
int x[][];
X=new int[2][3];
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Specifying the first dimension is mandatory.
int x[][]=new int [2][];
System.out.println(x[0]); //null
System.out.println(x[1]); //null
There is no memory wastage in java multidimensional arrays.
int x[][]=new int [][3]; // invalid
int x[][]=new int[2][3];
System.out.println(x.length); //2
System.out.println(x[0].length);//3
Which of the following are valid
1. String[][] s;
2. String s[][];
3. String []s[];
4. String [][]s;
5. Object [][o;
Three Dimensional Array Declaration:
int[][][] a; or
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
int [][][]a; or
int[][] a[]; or
int a[][][]; or
int [] a[][];
Construction of 3D Array
int [][][] a =new int [2][2][3];
Inheritance:
Inheritance is a concept where new classes can be produced from
existing classes. The newly created class acquires all features of existing class
from where it is derived. Inheritance provides the idea of reusability.
A class which is derived from another class is called a sub class or
derived class or extended class or child class.
The class from which the subclass is derived is called a super class or
base class or parent class.
A subclass inherits all members(fields, methods, nested classes) from
its super class. To link between two classes we use extends keyword
class A // super class
----------
---------
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
class B extends A // sub or derived class
-----------
-----------
A java class cannot extend more than one class so multiple inheritance is
not achieved through classes and it is possible by using interfaces.
Constructors are not inherited since they are not members of the class.
public, default, protected members are inherited where as private
members are not inherited
Object is the super class of all classes i.e., every class directly or
indirectly inherited from object class
Programmer’s code compiler code
class Demo class Demo extends Object
{ {
------------ Demo()
------------ {
} }
The following are the various types of inheritance
Single Inheritance
Multiple Inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid Inheritance.
Single Inheritance: Producing a subclass from a single super class is called
single inheritance.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Multiple Inheritance :
Producing sub classes from multiple super class is called Multiple
inheritance. In this case there will more than one super class and there can
be one or more sub classes.
Multiple inheritance leads to confusion for the programmer. For
example class A has got a member x and class B has also contain member x.
when another class C extends both the classes, then there is a confusion
regarding which copy of x is available in C.
Multiple inheritance is available in C++, which is not available in Java,
but java programmer wishes to use multiple inheritance in some cases.
Fortunately javasoft people have provided interface concept so that multiple
inheritance is achieved by using multiple interfaces.
class MyClass implements interface1, interface2,…….
Hierarchical Inheritance: In this type, there is only one super class but
many subclasses. These subclasses are derived from only one super class.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Subclass: A class which is derived from another class by using extends
keyword is called a sub class or derived class or extended class or child class.
Substitutability: Substitutability means the type of a variable can differ from
the type of value stored in a variable.
The various forms of Inheritance:
Specialization
Specification
Construction
Extension
Limitation
Combinations
Specialization: A child class or new class is a specialized form of the parent
class and it conforms all specifications of the parent.
public class MyFrame extends Frame
------
----------
The MyFrame class inheritance all the properties of parent class Frame.
MyApplet is specialized form of Frame class.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Specification: The parent class defines the methods without or with
implementations. The methods which are not implemented in parent class
must be defined in child class. Such kind of parent class is called
specification.
The parent class may be abstract class or interface. If the parent class
is abstract class then we need extends that abstract class. If the parent class
is interface then we need implement the interface as follows:
Case1: If the parent class is abstract
public abstract class Number
abstract double doubleValue();
abstract float floatValue() ;
-----------------------------------
-------------------------------------
class Demo extends Number
Now Demo class has to take responsibility to implement all methods of
Number class otherwise the Demo class also becomes abstract class.
Case2: if the parent class is interface
public interface MouseListener
void mouseClicked(MouseEvent e) ;
void mouseEntered(MouseEvent e) ;
void mouseExited(MouseEvent e) ;
void mousePressed(MouseEvent e) ;
void mouseReleased(MouseEvent e);
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public class MouseDemo implements MouseListener
Now MouseDemo class has to implement all methods of MouseListener
interface otherwise the MouseDemo becomes abstract class.
Construction:
The child class inherits all the properties of its parent class even though there
is no common functionality between parent and child class.
class Stack extends FileWriter
Extension:
The child class adds some more additional behavior (methods) to the parent
class without modifying the attributes(variables) that are inherited from
parent class.
For example let us consider the following code:
class MyClass extends Thread
MyClass is a user defined class in which MyClass contains thread class
behavior also.
Limitation:
Whenever a new class is derived from any class then the sub class restricts
few behaviors to be used that are inherited from the parent class.
Combinations:
Java doesn’t allow creating a class from more than one class. We can create
a class by implementing more than one interface.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
interface A
void m1();
void m2();
interface B
void m3();
void m4();
class Demo1
class Demo extends Demo1 implements A,B
-------------------
Now Demo takes responsibility to provide the implementation for methods of
interfaces A, B.
Benefits of Inheritance:
The Benefits of Inheritance are
Increased Reliability
Reusability
Polymorphism
Extending the Behavior
Member Access Rules:
Access means visibility. Permitting one class to access another class of
different package is called access control.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
An access specifier is a keyword that is used to specify how to access a
member of a class or the class itself. We can use access specifiers with the
members of the class or with class also. Java allows you to control access to
classes, methods and fields called access specifiers.
Java offers four access specifiers: Public , protected , default ,
private.
Public: Public class members i.e methods and field can be accessed in the
classes of same package and also the classes of other packages. Public means
every where.
Protected: Protected members of the class can be accessed by the classes of
same package and also the subclasses of other packages.
Default: if we are not specifying any access specifier then it is treated as
default. The default members of a class can be accessed by the classes of
same package only i.e. they cannot accessed by the classes of other packages.
Private: Private members of a class can be accessed within the class only i.e.,
they cannot be accessed by the classes of same package and also the classes
of other packages.
In the following figure we are taking three classes class A, class B and
class C. whereas class A and class B exists in the same package, class C is
from other package. Let us assume that there are four members with private,
public, protected and default specifiers in class A.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Private members of class A are not available to class B or class C. This
means, any private members scope is limited only to that class where it is
defined.
Public members of class A are available to class B and also class C. This
means, public members are available everywhere and their scope is global
scope.
Protected members of class A are available to class B, but not in class C.
if class C is a sub class of class A, then the protected members of class A
are available to class C, so protected access specifier acts as public with
respect to sub class.
When no access specifier is used, it is taken as default specifier. Default
members of class A are accessible to class B which is within the same
package. They are not available to class C. This means, the scope of default
members is package scope.
super Uses:
We can create an object of super class, we can access only the super class
members but not the sub class members. If we create sub class object, all the
members of both super and sub classes are available to it. Some times the
super members and sub class members may have same names.
Let us consider the following program:
class P
int a=60,b=0;
void m1()
System.out.println("m1 in P");
System.out.println("sum :"+(a+b));
class C extends P
int a=10,b=56;
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
void m1()
System.out.println("m1 in C");
System.out.println("mul : "+(a*b));
class SDemo
public static void main(String args[])
C c1=new C();
c1.m1();
In the above program a method m1() is called w.r.t child class object, hence
this m1() present in both child class as well as parent class. So w.r.t child
class object we are calling m1() method so the method that present in the
child class is called. In this case if we want to access the members of super
class from sub class super keyword is used. super is a keyword. Super is used
to access super class members from sub class. super can be used w.r.t
methods and variables
super.variable;
super.methods();
class P
int a=60,b=0;
void m1()
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
System.out.println("m1 in P");
System.out.println("sum :"+(a+b));
class C extends P
int a=10,b=56;
void m1()
System.out.println("m1 in C");
System.out.println("a: "+a+"b : "+b);
System.out.println("a: "+super.a+"b : "+super.b);
super.m1();
class SDemo
public static void main(String args[])
C c1=new C();
c1.m1();
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
super():
It is used to call super class constructors from sub class constructors.
It must be the first statement inside a constructor
this() and super() cannot be used at a time since both must be used
as a first statements.
super() cannot be used inside the method only in constructor.
this() is used to call constructors of same class but super is used call
the super class constructors from sub class.
If there is no this() statement inside the sub class constructor then by
default the java compiler takes the super() as a first statement .
Programmers code compiler code
Class Demo class Demo extends Object
{ {
Demo()
} {
Super();
class P
P()
System.out.println("default p ");
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
class C extends P
C()
System.out.println("default C ");
class SF
public static void main(String args[])
C c1=new C();
class Demo
Demo(int a)
this(40,20);
System.out.println("a: "+a);
Demo(int a,int b)
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
System.out.println("a: "+a+"b : "+b);
class Demo1 extends Demo
Demo1()
super(1);
System.out.println(" default constructor of Demo1 ");
class SF
public static void main(String args[])
Demo1 d = new Demo1();
}}
final : final is a keyword and is used w.r.t variable , method and classes. A
final variable cannot be modified i.e. it is used to define a constant. Final
methods cannot be overridden in sub class. Final classes cannot be
extended. If we try to change the value of variable that is declared by using
final keyword then the java compiler gives an error. If we try to override the
final methods in sub classes then java compiler gives an error.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
If we try to extend the final classed then java compiler gives an error. Let us
consider the following program:
final class P
final void m1()
System.out.println("final method");
class C extends P
void m1()
System.out.println("m1 in C");
class FDemo
public static void main(String args[])
final int x=90;
System.out.println(x);
System.out.println(x++);
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Polymorphism:
Polymorphism is an important Object oriented concept and widely used in
Java and other programming language. Polymorphism in java is
supported along with other concept like Abstraction, Encapsulation and
Inheritance.
Polymorphism word comes from ancient Greek where poly means many so
polymorphic are something which can take many form. In this Java
Polymorphism tutorial we will see what is Polymorphism in Java , How
Polymorphism is implemented in Java e.g method overloading and
overriding,
Method Overridding: Writing two or more methods in super and sub classes
such that methods have same name and same signature is called method
overriding. Overriding exists for only instance methods not for static methods.
Even return type must be same up to java1.4 version. We cannot assign weak
access specifier to the overridden method. Final methods cannot be
overridden. Method overriding is an example of run-time polymorphism. At
the execution time it decides which method is called based on the type of the
object.
class P
public void display()
System.out.println(" display of class P ");
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
class C extends P
public void display()
System.out.println(" display of class C ");
class Demo
public static void main(String args[])
P p1=new P();
p1.display();
C c1=new C();
c1.display();
P p2= new C();
p2.display();
/* C c2 = new P(); // error
c2.display();*/
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
We cannot assign a weaker access specifier to the child class method.
Case 1 class P
Public void m1()
Class C extends P {
Public void m1()
{ valid
Case 2 class P
Public void m1() { ---------------------}
Class C extends P
Void m1() {---------------------------}
Error: because of weak access privilages.
Error: m1 in c cannot override m1 in p; attempting to assign weaker access
privilages.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Accessibility varies as follows
Super class sub class
Public public
Protected protected, public
<default> public , protected, <default>
Private public , protected , <default>,
private
No overriding for private methods since they cannot be accessed outside the
class.
Method Hidding: If a sub class defines a static methods with the same
signature as a static method in the super class the method in the sub class
hides the method of super class. Method hiding takes for static methods
where as overriding takes for instance methods. Method hiding is an
example of compile time polymorphisms i.e, the type of the object is not
important only the type of the reference is important.
class P
static void m1()
System.out.println(" parent class ");
class C extends P
static void m1()
System.out.println(" CHILD class ");
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
}}
class MH
public static void main(String args[])
P p1 =new P();
p1.m1();
C c1 = new C();
c1.m1();
P p2 =new C();
p2.m1();
Output:
with static keyword without static keyword
parent class parent
child class child
parent class child
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Method Overloading: Two or more methods having the same method name
with different signatures is called method overloading. In case of method
overloading the number of parameters or the type of parameters or the order
of parameters must be differed. Return type may or may not be same.
Method overloading is an example of compile time polymorphism i.e., the
method call is decided at the compile time based on the parameters or
parameter types or order of parameters. Method overloading exists within
the same class where as overriding exists in between the classes. Method
overloading exists for instance and static methods.
class MO
public void display()
System.out.println(" hello ");
public void display(int i)
System.out.println(i);
public void display(float m)
System.out.println(m);
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public void display(int x, float m)
System.out.println(x+"\t"+m);
public void display(float m, int x)
System.out.println(x+"\t"+m);
public static void main(String args[])
MO d = new MO();
d.display();
d.display(10);
d.display(100,200.5f);
d.display(11.12f,222);
d.display(10.99f);
}}
Differences between overloading and overriding.
Method Overloading Method Overridding
Same method name and different Same method name and same
signature signature
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Overloading exists for instance and Overriding exists only for instance
static methods methods
Return type may or may not be Return type must be same upto
same java1.4 version
Overloading exists within class Overriding exists in between the
classes
Example of compile time Example of run-time polymorphism
polymorphism
Abstract Methods & Classes:
Abstract Method: A method which has no body/def is called abstract. A
incomplete method is called abstract method. A method without
implementation is called abstract method. Abstract method is declared by
using the keyword abstract.
abstract void display();
abstract int add(int x, int y);
Void display()
} // concrete method
Abstract method cannot be static & final. For abstract method the
implementation is provided in the sub class Abstract classes:
1. Abstract class is a class which contains abstract and concrete
methods. A abstract class can contain zero or more abstract
methods. A abstract class can contain all abstract methods or all
concrete methods or a set abstract and concrete methods.
2. Abstract class is declared by using the keyword abstract. If a class
contains at least one abstract method the class must be declared as
abstract class otherwise it is compile time error.
3. For abstract method the implementation is provided in the sub class
otherwise the class must be declared as abstract
4. For abstract class we cannot create object only we can create
references.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
5. A abstract class reference can be assigned to the implementation
class object.
6. Abstract says what to do but not how to do. How to do is done by the
sub classes. w.r.t the abstract class reference we can call the child
class methods in a unique way.
7. A abstract class can contain constructors but they are called when
sub class objects are created.
8. A abstract class can have instance variables and static variables.
When we created sub class object the memory is allocated for
abstract class variables.
abstract class Shape
public abstract void display();
class Circle extends Shape
public void display()
System.out.println(" circle ");
class Rectangle extends Shape
public void display()
System.out.println(" rectangle ");
class Triangle extends Shape
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public void display()
System.out.println(" Triangle ");
class AbstractDemo2
public static void main(String args[])
Circle cir = new Circle();
Rectangle rect=new Rectangle();
Triangle tri=new Triangle();
cir.display();
rect.display();
tri.display();
System.out.println(" ============");
Shape s;
s=cir;
s.display();
s=rect;
s.display();
s=tri;
s.display();
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
abstract class A
public static final int x=100;
abstract class B
public static final int y= 2001;
class AbstractDemo5
public static void main(String args[])
System.out.println(A.x);
System.out.println(B.y);
Java.lang-package: It is the default package available to every class
automatically. There is no need to import this package. It contains the
fundamental classes and interfaces to develop the programs.
Interfaces: Clonaeable , Comparable, Runnable
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
Classes:
Object
Wrapper Classes
String
StringBuffer
System
Runtime
Thread
Reflection
Math
Exception,Error, Throwable
Process
Object: It is the class from java.lang package. Object is the super class of all
classes i.e. Every class directly or indirectly inherited from object class.
Programmers code
compiler code
class A class A
extends java.lang.Object
{ {
} }
All objects including arrays inherit the methods of Object class.
toString(): it returns the String representation of the Object
equals(): compares the object references
hashCode(): returns the address of the Object/ returns distinct integers for
distinct Object
finalize(): this method is called by the Garbage Collector before removing
the Object from the memory. finalize() should contain the clean up code
wait() , notify(), notifyAll() all are used in Thread Mechanism.
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
class Demo extends Object
public static void main(String args[])
Demo d = new Demo();
Demo d1 =new Demo();
System.out.println(d.toString());
System.out.println(d); // same output : internally d taken as d.toString()
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
System.out.println(d.equals(d1));
d=d1;
System.out.println(d.equals(d1)); // compares hashCode() internally
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
public class Demo1 extends Object
public String toString() {
return "abc";
Department of Computer Science and Engineering S KRANTHI REDDY
JAVA PROGRAMMING
public int hashCode() {
return 420;
public static void main(String args[])
Demo1 d = new Demo1();
Demo1 d1=new Demo1();
System.out.println(d.toString());
System.out.println(d);
System.out.println(d.hashCode());
System.out.println(d1.hashCode());
System.out.println(d.equals(d1));
Department of Computer Science and Engineering S KRANTHI REDDY