Unit I Java
Unit I Java
Review of object oriented programming - Objects and classes in Java – Defining classes –
Methods - Access specifiers – static members – static fields - static methods - static variables
– constructors -Default constructor - parameterized constructor – finalize method – Arrays –
Strings – Packages – user defined packages – Java Doc comments
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named Ravi is
an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
class Student {
int id;
String name;
public static void main(String args[])
{
Syntax
(or)
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
• Shared memory allocation: Static variables and methods are allocated memory space
only once during the execution of the program. This memory space is shared among all
instances of the class, which makes static members useful for maintaining global state
or shared functionality.
• Accessible without object instantiation: Static members can be accessed without the
need to create an instance of the class. This makes them useful for providing utility
functions and constants that can be used across the entire program.
• Associated with class, not objects: Static members are associated with the class, not
with individual objects. This means that changes to a static member are reflected in all
instances of the class, and that you can access static members using the class name
rather than an object reference.
• Cannot access non-static members: Static methods and variables cannot access non-
static members of a class, as they are not associated with any particular instance of the
class.
• Can be overloaded, but not overridden: Static methods can be overloaded, which
means that you can define multiple methods with the same name but different
parameters. However, they cannot be overridden, as they are associated with the class
rather than with a particular instance of the class.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we
are accessing static method m1() without creating any object of the Test class.
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
Output
from m1
Static blocks
If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating the use of static blocks.
class Test
{
// static variable
static int a = 10;
static int b;
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
Output
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static variables
When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global variables.
All instances of the class share the same static variable.
Important points for static variables:
• We can create static variables at the class level only.
• static block and static variables are executed in the order they are present in a program
class Test
{
// static variable
static int a = m1();
// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
Output
from m1
Inside static block
Value of a : 20
from main
Static methods
When a method is declared with the static keyword, it is known as the static method. The
most common example of a static method is the main( ) method. As discussed above, Any
static member can be accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Characteristics of a constructor:
• It has the same name as the class.
• A class can have more than one constructor.
• It can take zero, one or more parameters.
• It has no return value.
• It can be overloaded.
• It is always called with new operator.
Functions of a constructor:
• It can be used to initialize the fields.
• It allocates memory space too the fields
Rules for creating Java constructor
There are two rules defned for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, fnal, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
Syntax of default constructor:
[access-specifier] class name (arguments)
{
Statements;
}
Example of default constructor
E.G.: Constructor
import java.io.*;
class add
int a=0;
int b=0;
int c;
System.out.println("Parameterized constructor");
a=n1;
b=n2;
add()
System.out.println("Default constructor");
void addnum()
c=a+b;
void print()
System.out.println("value of A="+a);
System.out.println("value of B="+b);
System.out.println("Sum="+c);
class add1{
A.addnum();
A.print();
add B=new add();
finalize() Method
Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.
Syntax
Throw
Example 1:
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Output:
2018699554
end of garbage collection
finalize method called
Arrays in Java
Array in Java is a group of like-typed variables referred to by a common name.
• In Java, all arrays are dynamically allocated.
• Arrays may be stored in contiguous memory [consecutive memory locations].
• Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
• This storage of arrays helps us randomly access the elements of an array [Support
Random Access].
• The size of the array cannot be altered(once initialized). However, an array reference
can be made to point to another array.
One-Dimensional Arrays:
datatype var-name[];
OR
datatype[] var-name;
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
279
361
742
sum(arr);
}
Output
sum of array values : 15
Strings
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="Hello";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
1. By string literal
2. By new keyword
1) String Literal
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) By new keyword
Output:
java
strings
example
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
} OUTPUT:
true
true
false
The String class compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
The String concat() method concatenates the specified string to the end of current string.
Syntax:
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
Substring() method
A part of String is called substring. In other words, substring is a subset of another String.
Java String class provides the built-in substring() method that extract a substring from the
given string by using the index values passed as an argument. In case of substring() method
startIndex is inclusive and endIndex is exclusive.
o startIndex: inclusive
o endIndex: exclusive
1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin
}
} Output:
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Output:
SACHIN
sachin
Sachin
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative
code.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed
by Java.
Syntax:
Output:
10
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed
by Java.
Syntax:
/*
This
is
multi line
comment
*/
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments
are placed between /** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
javadoc tags
Calculate.java
import java.io.*;
/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author Anurati
* @version 16.0
* @since 2021-07-06
*/
Create Document
Java comments are not executed by the compiler or interpreter, however, before the lexical
transformation of code in compiler, contents of the code are encoded into ASCII in order to
make the processing easy.