Java Unit - 1
Java Unit - 1
Unit 1
Core Java Fundamentals: Java Virtual Machine, data types, variables, keywords, operators,
expressions, control statements, classes, objects, constructors, access control, method
overloading, static members, Arrays, Strings, Inheritance: types, constructors in inheritance,
method overriding, use of super, abstract classes – interfaces, dynamic method dispatch.
Packages and exception handling.
History of Java:
The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc. For the green team members, it was an advance concept at that time.
But, it was suited for internet programming. Later, Java technology as incorporated by
Netscape. Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java. 1) James
Gosling, Mike Sheridan, and Patrick Naught on initiated the Java language project in June
1991. The small team of sun engineers called Green Team. 2) Originally designed for small,
embedded systems in electronic appliances like set- top boxes. 3) Firstly, it was called "Green
talk" by James Gosling and file extension [Link]. 4) After that, it was called Oak and was
developed as a part of the Green project.
There are many java versions that has been released. Current stable release of Java is Java SE
8. 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan, 1996) 3. JDK 1.1 (19th Feb, 1997) 4.
J2SE 1.2 (8th Dec, 1998) 5. J2SE 1.3 (8th May, 2000) 6. J2SE 1.4 (6th Feb, 2002) 7. J2SE
5.0 (30th Sep,2004) 8. Java SE 6 (11th Dec,2006) 9. Java SE 7 (28th July, 2011) [Link] SE
8 (18th March,2014)
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java
Features given below are simple and easy to understand.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance:
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed:
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic:
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
3 Department of MCA
Definition: JVM is an abstract computing machine that enables Java bytecode to be executed
on any platform without modification.
Role:
o Converts Java bytecode into machine code.
o Provides platform independence.
Architecture:
4 Department of MCA
JVM is a engine that provides runtime environment to drive the Java Code or applications. It
converts Java bytecode into machines language. JVM is a part of JRE(Java Run
Environment). It stands for Java Virtual Machine
1. First, Java code is compiled into bytecode. This bytecode gets interpreted
on different machines
2. Between host system and Java source, bytecode is an intermediary language.
3. JVM is responsible for allocating memory space.
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are
optional.
Import This line indicates that if you want to use a class of another package, then
statements you can do this by importing it directly into your program.
Example:
import [Link].*;
Interface Interfaces are like a class that includes a group of method declarations.
statement It's an optional section and can be used when programmers want to
implement multiple inheritances within a program.
5 Department of MCA
Class A Java program may contain several class definitions. Classes are the
Definition main and essential elements of any Java program.
Main Method Every Java stand-alone program requires the main method as the starting
Class point of the program. This is an essential part of a Java program. There
may be many classes in a Java program, and only one class defines the
main method. Methods contain data type declaration and executable
statements
Data types represent the different values to be stored in the variable. In java, there are two
types of data types:
Primitive datatypes
Non-primitive datatypes
A primitive data type in Java is a basic, built-in data type that stores simple values directly,
rather than objects or more complex structures. These are predefined by the language and are
used to represent raw data efficiently in memory.
Key Characteristics:
Description
Data Type Size
Byte 8 bits Stores small integers
short 16 bits Stores larger integers
int 32 bits Default integer type
long 64 bits Stores very large integers
float 32 bits Stores floating-point numbers
double 64 bits Stores high precision floating-point numbers
char 16 bits Stores single characters
boolean 1 bit Stores true or false
6 Department of MCA
Non-primitive data types (also called reference types) in Java are types that refer to
objects rather than storing the actual data directly. These are more complex structures and can
hold multiple values, methods, and behaviours.(Class, Array & Interface)
They store references – The variable holds the memory address where the object is
stored.
Can be used to create objects – These types are built from classes and interfaces.
More memory overhead – They have extra data like methods and metadata.
Class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
}}
Output:20
} }}
Example: Interface
interface Printable {
void print();
}
class Document implements Printable {
public void print() {
[Link]("Printing the document");
}}
public class SimpleInterface {
public static void main(String[] args) {
7 Department of MCA
1.3 Variables
Variable is a name of memory location. There are three types of variables in java
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
} }//end of class
1.4 Keywords
Reserved words with special meaning. Examples: class, public, static, void, if, else,
for, while, return, this, super, new.
1.5 Operators
Operators in Java are special symbols or keywords that are used to perform operations on
variables and values. They help manipulate data by performing arithmetic, comparisons,
logical operations, and more.
Types of operators:
Arithmetic: +, -, *, /, %
Relational: ==, !=, >, <, >=, <=
Logical: &&, ||, !
Assignment: =, +=, -=, *=, /=
Unary: ++, --, -, +
Bitwise: &, |, ^, ~, <<, >>
Example:
int a = 10;
int b = 5;
8 Department of MCA
1.6 Expressions
Expressions are essential building blocks of any Java program, usually created to produce a
new value, although sometimes an expression simply assigns a value to a variable.
Expressions are built using values, variables, operators and method calls. (Combinations of
operators and operands).
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
• Those that have no result but might have a "side effect" because an expression can include a
wide range of elements such as method invocations or increment operators that modify the
state (i.e. memory) of a program.
Example:
int a = 10;
int b = 20;
int c = a + b * 2;
Control statements in Java are used to manage the flow of execution based on conditions or
loops. They decide which part of the code should be executed and how many times.
Decision-making:
o if, if-else, if-else if-else, switch
Looping:
Branching:
9 Department of MCA
If statement
if (number > 5) {
If-else statement
int number = 3;
if (number > 5) {
} else {
[Link]("5 or less");
Switch statement
int day = 3;
switch(day) {
case 1:
[Link]("Monday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Another day");
Looping Statement
10 Department of MCA
For loop
While loop
int i = 1;
while (i <= 3) {
i++;
Do-while loop
int i = 1;
do {
i++;
Branching statements:
Break
if (i == 3) break;
[Link](i);
continue
if (i == 3) continue;
11 Department of MCA
[Link](i);
Return
[Link]("Hello!");
return;
Classes
12 Department of MCA
Fileds or Data
members; Methods or
member functions;
}
Class classname
{
Datatype
variablename
1; Datatype
variablename2
;
.
Returntype methodname(ArgumentsList)
{
Method body;
}
Object:
An entity that has state and behaviour is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical.
An object has three characteristics:
State : Represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used internally
by the JVM to identify each object uniquely.
13 Department of MCA
Example:
class Car {
String color;
int speed;
class Test {
[Link] = "Red";
[Link] = 100;
1.9 Constructors
14 Department of MCA
Example:
class Car {
String model;
Car(String model) {
[Link] = model;
}
void display() {
[Link]("Car model: " + model);
}
}
Access Modifiers:
Example:
class AccessExample {
private int privateVar = 1;
int defaultVar = 2; // default access
protected int protectedVar = 3;
public int publicVar = 4;
15 Department of MCA
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.(Defining multiple methods with the same
name but different parameters).
Example:
class MathOperations {
return a + b;
return a + b;
A static member in Java is a field (variable) or method that belongs to the class rather than
any particular instance (object) of the class. This means all objects of the class share the same
static members.
16 Department of MCA
Example:
class Counter {
static int count = 0; // static variable
Counter() {
count++;
}
static void showCount() {
[Link]("Count is: " + count);
}
}
1. 13. Arrays
An array in Java is a container that holds a fixed number of values of the same type. It
allows you to store multiple values in a single variable and access them using an index.
Declaration
int[] numbers;
Initialization
17 Department of MCA
Example
Output:
First element: 10
Third element: 30
All elements:
10
20
30
40
50
1.14 Strings
In Java, a String is an object that represents a sequence of characters. The String class,
defined in the [Link] package, provides constructors and methods to create, manipulate,
and inspect sequences of characters. Strings are immutable, meaning once a String object is
created, its value cannot be changed.
Example:
18 Department of MCA
1.15 Inheritance
Inheritance is the process by which one class acquires the properties (data members) and
behaviors (methods) of another class. The class that inherits is called the subclass or derived
class, and the class from which it inherits is called the superclass or base class.
Types:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
Single Inheritance
In this type, a class inherits the properties and behaviors of one parent class.
Class A → Class B
B inherits from A
Example:
class Animal {
void eat() {
[Link]("Eating...");
void bark() {
[Link]("Barking...");
19 Department of MCA
Multilevel Inheritance
In this type, a class is derived from a child class, and this chain continues further. The
properties are passed from one class to the next.
Example:
class Animal {
void eat() {
[Link]("Eating...");
}}
void walk() {
[Link]("Walking...");
}}
void bark() {
[Link]("Barking...");
}}
3. Hierarchical Inheritance
In this type, multiple classes inherit from a single parent class. This allows different classes to
share the common properties of the base class.
Example:
Class A → Class B
class Animal {
void eat() {
20 Department of MCA
void bark() {
void meow() {
When a class inherits from a parent class, the constructor of the parent class is not inherited
by the child class, but it is automatically invoked when an object of the child class is created.
This ensures that the parent’s attributes are properly initialized before the child class adds its
own attributes or behaviors.
Constructors are not inherited-Even though methods and variables are inherited,
constructors are not inherited.
Parent constructor is called first-When a child class object is created, the constructor of
the parent class is invoked before the constructor of the child class.
Use of super()-The child class can explicitly call the parent class’s constructor using the
super() keyword. If super() is not called explicitly, Java automatically inserts a call to the
no-argument constructor of the parent class.
Parameter Passing-If the parent class constructor requires arguments, the child class
must explicitly call it using super(arguments).
Example:
class Animal {
Animal() {
21 Department of MCA
Dog() {
Output:
Method overriding is the process in which a subclass provides its own implementation of a
method that is already defined in its parent class. The method in the subclass must have the
same name, return type, and parameters as the method in the parent class. Overriding is used
to provide specific behavior to the subclass while still keeping the method’s general structure.
Example:
// Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
22 Department of MCA
// Child class
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
// Main class
public class TestOverriding {
public static void main(String[] args) {
Animal a = new Animal();
[Link](); // Calls parent class method
The super() keyword is used to invoke the constructor of the parent class from the child
class. It ensures that the parent class is properly initialized before the child class’s constructor
executes its own code. The call to super() must be the first statement in the child class’s
constructor.
Uses of super():
3. It can pass parameters to the parent’s constructor-If the parent class constructor
requires arguments, super(arguments) is used to pass them.
4. Automatic call if not written-If you don’t explicitly call super(), Java
automatically inserts a call to the parent’s no-argument constructor.
Example:
// Parent class
class Animal {
Animal() {
23 Department of MCA
// Main class
public class TestSuper {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]("-----");
Dog dog2 = new Dog("Tommy");
}
}
Output:
Example
24 Department of MCA
Output:
Dog barks
This animal eats food.
Interfaces
Key Points:
4. Interfaces are used to define a contract for what a class should do.
Example
interface Printable {
void print();
}
interface Showable {
void show();
25 Department of MCA
}
class Demo implements Printable, Showable {
public void print() {
[Link]("Printing...");
}
public void show() {
[Link]("Showing...");
}
}
public class TestInterface {
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
[Link]();
}
}
Output:
Printing...
Showing...
Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
26 Department of MCA
1.21 Packages
A package is a collection of related classes and interfaces grouped together under a common
name. Packages are used to organize classes, avoid name conflicts, and control access. By
using packages, programmers can manage large software projects by grouping similar
functionality into separate modules.
Creating Packages:
The package keyword is used at the beginning of a source file to declare its package.
Classes and interfaces within the same package can access each other’s default and
protected members.
Importing Packages:
Example:
Create a package
// File: mypack/[Link]
package mypack;
public class Hello {
public void display() {
[Link]("Hello from mypack!");
}
}
// File: [Link]
import [Link];
}
}
Output:
Hello from mypack!
Exception handling is a mechanism in Java to handle runtime errors, so that the normal flow
of the application is maintained. An exception is an abnormal condition that occurs during the
execution of a program, such as division by zero, invalid input, or file not found. Java
provides built-in classes and keywords to catch, handle, and throw exceptions to prevent
abrupt termination of the program.
Exception – An abnormal event that disrupts the normal flow of the program.
try block – Contains code that might throw an exception.
catch block – Handles the exception and defines how to respond to it.
finally block – Contains code that will be executed whether or not an exception
occurs.
throw – Used to explicitly throw an exception.
throws – Declares exceptions that a method might throw to be handled by the caller.
Example
Output:
28 Department of MCA