0% found this document useful (0 votes)
2 views

Unit-I Java

Uploaded by

Prabhu B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-I Java

Uploaded by

Prabhu B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

IT T45- Java Programming

Unit: I
Creation of Java, importance of Java to internet, byte code, Java buzzwords, data types, declaring
variables, dynamic initialization, scope and life time of variables, arrays, operators, control statements,
type conversion and casting, compiling and running of simple Java program. Concepts of classes and
objects, class fundamentals Declaring objects, assigning object reference variables, introducing
methods, constructors, usage of static with data and methods, usage of final with data, access control,
this key word, garbage collection, overloading methods and constructors, parameter passing - call by
value, recursion, nested classes and inner classes, exploring the String class.

1.1 What is Java?

 Java is a programming language and a platform.


 Java is a high level, robust, object-oriented and secure programming language.
 Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

1.1.1 Creation of Java (History of Java):

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted and Dynamic".

James Gosling - Founder of java

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given the significant points that describe the history of Java.

Java History from Oak to Java

 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like set-top boxes.
 Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names. Java is an island of Indonesia
where first coffee was produced (called java coffee). Notice that Java is just a name, not an acronym.
Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995. In 1995, Time magazine called Java one of the Ten Best Products of
1995.JDK 1.0 released in (January 23, 1996)

SMVEC-Department of Information Technology Page 1


IT T45- Java Programming

Java Version History


Many java versions have been released till now. The current stable release of Java is Java SE 10.
 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)
 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)

1.2 Why java is important to the Internet

The reason why java has had an intense effect on the Internet is Java expands the universe of
objects that can move about freely in cyberspace. In a network, two very broad categories of objects are
transmitted between the server and your personal computer:
 Passive information
For example, when you read your e-mail, you are viewing passive data. Even when you download a
program, the program‟s code is still only passive data until you execute it.
 Dynamic, active programs.
A dynamic, self- executing program. Such a program is an active agent on the client computer,
yet is initiated by the server. For example, a program might be provided by the server to display
properly the data that the server is sending.
As desirable as dynamic, networked programs are, they also present serious problems in the areas
of security and portability.
1.2.1 Java Applets and Applications :

Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. When used to create
applications, java is a not much different from any other computer language.

An applet is an application designed to be transmitted over the Internet and executed by a java-
compatible Web browser. An applet is actually a tiny java program, dynamically downloaded across
the network, just like an image, sound file, or video clip. The important difference is that an applet is an
intelligent program, not just and animation or media file. In other words an applet is a program that can
react to user input and dynamically change not just run the same animation or sound over and over.

SMVEC-Department of Information Technology Page 2


IT T45- Java Programming

1.2.2 Security:

Prior to Java, most users did not download executable programs frequently, and those who
downloaded scan them for viruses prior to execution. When you use a Java-compatible Web browser,
you can safely download Java applets without fear of viral infection or malicious intent. Java achieves
this protection by confining a Java program to the Java execution environment and not allowing it
access to other parts of the computer.

1.2.3 Portability:

Many types of computers and operating systems are in use throughout the world - and many are
connected to the Internet. For programs to be dynamically downloaded to all the various types of
platforms connected to the Internet, some means of generating portable executable code is needed. The
same mechanism that helps ensure security also helps create portability.

1.3 What is Java Byte code?


Java byte code is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java byte code
is generated. The java byte code is the machine code in the form of a .class file. With the help of java
byte code we achieve platform independence in java.

How does it work?


When we write a program in Java, (Fig 1.1) firstly, the compiler compiles that program and a
byte code is generated for that piece of code. When we wish to run this .class file on any other platform,
we can able to run. After the first compilation, the byte code generated is now run by the Java Virtual
Machine and not the processor in consideration.

Fig 1.1 Byte Code Conversion

Advantage of Java Byte code

Byte code is essentially the machine level language which runs on the Java Virtual Machine.
Whenever a class is loaded, it gets a stream of byte code per method of the class. Whenever that
SMVEC-Department of Information Technology Page 3
IT T45- Java Programming

method is called during the execution of a program, the byte code for that method gets invoked. Javac
not only compiles the program but also generates the byte code for the program.

It is realized that the byte code implementation makes Java a platform-independent language.
This helps to add portability to Java which is lacking in languages like C or C++. Portability ensures
that Java can be implemented on a wide array of platforms like a desktop, mobile devices, severs and
many more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or
"WORA" in significance to the byte code interpretation.

Example Java Program

public static void main(String[ ] args)


{
int a = 1;
int b = 2;
int c = a + b;
}

In order to print the resulting byte code in the compiled class (assuming it is in a file Test.class), we can
run the javap tool:

javap -v Test.class
And we get:

public static void main(java.lang.String[]);


descriptor: ([Ljava/lang/String;)V
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=4, args_size=1
0: iconst_1
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: iadd
7: istore_3
8: return
...

1.4 Features of Java


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which play
an important role in the popularity of this language. The features of Java are also known as java
buzzwords. A list of most important features of Java language is given below.

SMVEC-Department of Information Technology Page 4


IT T45- Java Programming

 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic

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:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
 There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

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.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules. Basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 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.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform. The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:

 Runtime Environment
 API(Application Programming Interface)
SMVEC-Department of Information Technology Page 5
IT T45- Java Programming

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
 Java Programs run inside a virtual machine sandbox
 Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those that
are imported from network sources.
 Byte code Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
 Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust: Robust simply means strong. Java is robust because:

 It uses strong memory management.


 There is a lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
 There are exception handling and the type checking mechanism in Java. All these points make
Java robust.

Architecture-neutral: Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed. In C programming, int data type occupies 2
bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable: Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.

High-performance: Java is faster than other traditional interpreted programming languages because
Java byte code 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.
SMVEC-Department of Information Technology Page 6
IT T45- Java Programming

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: 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).

1.5 Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
 Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

1.5.1 Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. Java is a statically-typed programming language. It
means, all variables must be declared before its use. That is why we need to declare variable's type and
name. There are 8 types of primitive data types:
 boolean data type
 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type

Fig 1.2 Data Types in Java

SMVEC-Department of Information Technology Page 7


IT T45- Java Programming

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum
value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data
type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default
value is 0.The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000

int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum
value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default
value is 0. The long data type is used when you need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

SMVEC-Department of Information Technology Page 8


IT T45- Java Programming

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0d.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency.Its default value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letter = 'A'

1.6 Java Variables

A variable is a container which holds the value while the java program is executed. A variable is
assigned with a data type. Variable is name of reserved area allocated in memory. In other words, it is a
name of memory location.. There are three types of variables in java:

 Local
 Instance
 Static.

1.6.1 Variable Declaration in java


int i = 10; //Variable of int type
String str = "howtodoinjava.com"; //Variable of string type
Object obj = new Object( ); //Variable of object type
int[ ] scores = [1,2,3,4,5,6,7,8,9]; //Variable of int type

1.6.2Types of Variables

Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the variable
exists. A local variable cannot be defined with "static" keyword.

SMVEC-Department of Information Technology Page 9


IT T45- Java Programming

Instance Variable

A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static. It is called instance variable because its value is instance specific
and is not shared among instances.

Static variable

A variable which is declared as static is called static variable. It cannot be local. This can also
be called as the class variables. You can create a single copy of static variable and share among all
the instances of the class. Memory allocation for static variable happens only once when the class is
loaded in the memory.

Example
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

1.6.3 Difference between Instance variables and Class Variables

Static (class Variables) Instance Variables

Instance variables are declared


Class variables are declared with keyword static. without static keyword.

Class variables are common to all instances of a class. Instance variables are not shared between the
These variables are shared between the objects of a objects of a class. Each instance will have their
class. own copy of instance variables.

As each object will have its own copy of instance


As class variables are common to all objects of a variables, changes made to these variables
class, changes made to these variables through one through one object will not reflect in another
object will reflect in another. object.

Class variables can be accessed using either class Instance variables can be accessed only through
name or object reference.( ClassName.VariableName) object reference(Objectname.VariableName).

SMVEC-Department of Information Technology Page 10


IT T45- Java Programming

Example : Instance Variables


class Marks
{
int m1;
int m2;
}
class MarksDemo
{
public static void main(String args[])
{
Marks obj1 = new Marks();
obj1.m1 = 90;
obj1.m2=100;
System.out.println(“Marks are”+obj1.m1+obj1.m2);
}
}

Example: Class Variables


class Emp
{

public static double salary;


public static String name = "Harsh";
}

public class EmpDemo


{
public static void main(String args[])
{
Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}

1.6.4 Dynamic Initialization of Variable:

Initialization is the process of providing value to a variable at declaration time. A variable is


initialized once in its life time. Any attempt of setting a variable's value after its declaration is called
assignment. To use a local variable you have to either initialize or assign it before the variable is first
used. But for class members, the compulsion is not so strict. If you don't initialize them then compiler
takes care of the initialization process and set class members to default values.

Java allows its programmers to initialize a variable at run time also. Initializing a variable at
run time is called dynamic initialization.

SMVEC-Department of Information Technology Page 11


IT T45- Java Programming

Example:
public class Dynamic
{
public static void main(String[] args)
{
double dynSqrt = Math.sqrt (16);
System.out.println("sqrt of 16 is : " + dynSqrt);
}
}

OUTPUT
sqrt of 16 is : 4.0

1.6.7 Scope and Life time of Variable:


Scope of a variable refers to in which areas or sections of a program can the variable be
accessed and lifetime of a variable refers to how long the variable stays alive in memory. General
convention for a variable‟s scope is, it is accessible only within the block in which it is declared. A
block begins with a left curly brace { and ends with a right curly brace }.

Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance
variable. General scope of an instance variable is throughout the class except in static
methods. Lifetime of an instance variable is until the object stays in memory.

Class Variables

A variable which is declared inside a class, outside all the blocks and is marked static is known
as a class variable. General scope of a class variable is throughout the class and the lifetime of a
class variable is until the end of the program or as long as the class is loaded in memory.
SMVEC-Department of Information Technology Page 12
IT T45- Java Programming

Local Variables
All other variables which are not instance and class variables are treated as local variables including
the parameters in a method.Scope of a local variable is within the block in which it is declared and
the lifetime of a local variable is until the control leaves the block in which it is declared.

1.6.7.1 Comparison of the Scope and Lifetime Variable

SMVEC-Department of Information Technology Page 13


IT T45- Java Programming

1.7 Arrays in Java


Java Array
An array is a collection of similar type of elements that have a contiguous memory location.
Java array is an object which contains elements of a similar data type. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array. Array in java is
index-based; the first element of the array is stored at the 0 index.

Advantages

 Code Optimization: It makes the code optimized; we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Types of Array in java

 Single Dimensional Array


 Multidimensional Array

1.7.1 Single Dimensional Array in Java

Syntax to Declare an Array in Java

dataType []arr; (or)


dataType arr[];
1.7.2 Instantiation of an Array in Java
arr=new datatype[size];

1.7.3 Declaration, Instantiation and Initialization of Java Array:

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Example:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
SMVEC-Department of Information Technology Page 14
IT T45- Java Programming

for(int i=0;i<a.length;i++) //length is the property of array


{
System.out.println(a[i]);
}
}
}

Output:

10
20
70
40
50

1.7.4 Passing Array to Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.
class Testarray2
{
//creating a method which receives an array as a parameter
static void minimum(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}
System.out.println(min);
}
public static void main(String args[])
{
int a[ ]={33,3,4,5};
minimum(a);//passing array to method
}
}
Output:
3

1.7.5 Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.

SMVEC-Department of Information Technology Page 15


IT T45- Java Programming

public class AnonymousArray


{
static void printArray(int arr[ ])
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
public static void main(String args[])
{
printArray(new int[ ]{10,22,44,66});//passing anonymous array to method
}
}
Output:
10
22
44
66

1.7.6 Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;

Example:

class Testarray5
{
public static void main(String args[])
{
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];

SMVEC-Department of Information Technology Page 16


IT T45- Java Programming

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
Output:
268
6 8 10

1.7.7 Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
Example:
class TestJaggedArray
{
public static void main(String[] args)
{
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
{
for(int j=0; j<arr[i].length; j++)
{
arr[i][j] = count++;
}
}
//printing the data of a jagged array
for (int i=0; i<arr.length; i++)
{
for (int j=0; j<arr[i].length; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
SMVEC-Department of Information Technology Page 17
IT T45- Java Programming

Output:
012
3456
78

1.7.8 Displaying the Class Name of Array

In Java, an array is an object. For array object, a proxy class is created whose name can be
obtained by getClass( ).getName( ) method on the object.

Getting the class name of Java array

Class c=arr.getClass();
String name=c.getName();

Printing the class name of Java array

System.out.println(name);

1.8 Operators in Java

Operators are special symbols (characters) that carry out operations on operands (variables and values)
1.8.1 Assignment Operator

Assignment operators are used in Java to assign values to variables.The assignment operator assigns the
value on its right to the variable on its left. Here, 5 is assigned to the variable age using = operator

Example : Assignment Operator


class AssignmentOperator
{
public static void main(String[] args)
{

int number1, number2;

// Assigning 5 to number1
number1 = 5;
System.out.println(number1);

// Assigning value of variable number2 to number1


number2 = number1;
System.out.println(number2);
}
}

SMVEC-Department of Information Technology Page 18


IT T45- Java Programming

1.8.2 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.

Operator Meaning

+ Addition (also used for string concatenation)

- Subtraction Operator

* Multiplication Operator

/ Division Operator

% Remainder Operator

Example 2: Arithmetic Operator


class ArithmeticOperator
{
public static void main(String[] args)
{
double number1 = 12.5, number2 = 3.5, result;
// Using addition operator
result = number1 + number2;
System.out.println("number1 + number2 = " + result);

// Using division operator


result = number1 / number2;
System.out.println("number1 / number2 = " + result);

// Using remainder operator


result = number1 % number2;
System.out.println("number1 % number2 = " + result);
}
}

1.8.3 Unary Operators


Unary operator performs operation on only one operand.

Operator Meaning

+ Unary plus (not necessary to use since numbers are positive without using it)

- Unary minus; inverts the sign of an expression

SMVEC-Department of Information Technology Page 19


IT T45- Java Programming

Operator Meaning

++ Increment operator; increments value by 1

-- decrement operator; decrements value by 1

! Logical complement operator; inverts the value of a boolean

Example : Unary Operator


class UnaryOperator
{
public static void main(String[] args)
{
double number = 5.2, resultNumber;
boolean flag = false;

System.out.println("+number = " + +number);


// number is equal to 5.2 here.

System.out.println("-number = " + -number);


// number is equal to 5.2 here.

// ++number is equivalent to number = number + 1


System.out.println("number = " + ++number);
// number is equal to 6.2 here.

// -- number is equivalent to number = number - 1


System.out.println("number = " + --number);
// number is equal to 5.2 here.

System.out.println("!flag = " + !flag);


// flag is still false.
}
}

Output:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true

1.8.4 Relational Operators

The equality and relational operators determines the relationship between two operands. It
checks if an operand is greater than, less than, equal to, not equal to and so on. Depending on the
relationship, it results to either true or false.
SMVEC-Department of Information Technology Page 20
IT T45- Java Programming

Operator Description Example

== equal to 5 == 3 is evaluated to false

!= not equal to 5 != 3 is evaluated to true

> greater than 5 > 3 is evaluated to true

< less than 5 < 3 is evaluated to false

>= greater than or equal to 5 >= 5 is evaluated to true

<= less then or equal to 5 <= 5 is evaluated to true

Example: Relational Operator


class RelationalOperator {
public static void main(String[] args) {

int number1 = 5, number2 = 6;

if (number1 > number2)


{
System.out.println("number1 is greater than number2.");
}
else
{
System.out.println("number2 is greater than number1.");
}
}
}

1.8.5 instanceof Operator


A type of comparison operator which compares an object to a specified type.
Example:
class instanceofOperator {
public static void main(String[] args) {

String test = "asdf";


boolean result;

result = test instanceof String;


System.out.println(result);
}
}
When we run the program, the output will be true. It's because test is the instance of String class

SMVEC-Department of Information Technology Page 21


IT T45- Java Programming

1.8.6 Logical Operators

Operator Description Example

conditional-OR; true if either of the boolean expression


|| false || true is evaluated to true
is true

false && true is evaluated to


&& conditional-AND; true if all boolean expressions are true
false

Example : Logical Operators


class LogicalOperator
{
public static void main(String[] args)
{

int number1 = 1, number2 = 2, number3 = 9;


boolean result;

// At least one expression needs to be true for result to be true


result = (number1 > number2) || (number3 > number1);

// result will be true because (number1 > number2) is true


System.out.println(result);

// All expression must be true from result to be true


result = (number1 > number2) && (number3 > number1);

// result will be false because (number3 > number1) is false


System.out.println(result);
}
}
Output:
true
false

1.8.7 Ternary Operator


The conditional operator or ternary operator ?: is shorthand for if-then-else statement. The syntax of
conditional operator is:

variable = Expression ? expression1 : expression2

 If the Expression is true, expression1 is assigned to variable.


 If the Expression is false, expression2 is assigned to variable.

SMVEC-Department of Information Technology Page 22


IT T45- Java Programming

Example : Ternary Operator


class ConditionalOperator
{
publicstaticvoid main(String[] args)
{
int februaryDays =29;
String result;

result =(februaryDays ==28)?"Not a leap year":"Leap year";


System.out.println(result);
}
}
Output:
Not a leap year

1.8.8 Bitwise and Bit Shift Operators


To perform bitwise and bit shift operators in Java, these operators are used.

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

| Bitwise inclusive OR

1.9 Control Statements


A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before execut
body.

for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

SMVEC-Department of Information Technology Page 23


IT T45- Java Programming

do...while loop
Like a while statement, except that it tests the condition at the end of the loop body.

1.9.1 Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.

break statement
Terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.

continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.

1.9.2 Enhanced for loop in Java


Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides
a simpler way to iterate through the elements of a collection or array. It is inflexible and should be
used only when there is a need to iterate through the elements in sequential manner without knowing
the index of currently processed element.
SMVEC-Department of Information Technology Page 24
IT T45- Java Programming

Syntax
for(declaration : expression)
{
// Statements
}
 Declaration − It, is of a type compatible with the elements of the array we are accessing. The
variable will be available within the for block and its value would be the same as the current
array element.
 Expression − The expression can be an array variable or method call that returns an array.

Example
public class Test
{

public static void main(String args[])


{
int[ ] numbers ={10,20,30,40,50};

for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String[] names ={"James","Larry","Tom","Lacy"};

for(String name : names )


{
System.out.print( name );
System.out.print(",");
}
}
}
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

1.10 Type Conversion and casting in Java

Converting a value from one type to another type (data type) is known as type conversion.
Type conversion is of two types based on how the conversion is performed:
 Implicit conversion (also known as automatic conversion or coercion),
 Explicit conversion (also known as type casting).

SMVEC-Department of Information Technology Page 25


IT T45- Java Programming

1.6.4 Java Variable: Widening

When a small primitive type value is automatically accommodated in a bigger/wider


primitive data type, this is called widening of the variable. In given example, int type variable is
assigned to long type variable without any data loss or error.

Example:
class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0

1.6.5 Java Variable: Narrowing


When a larger primitive type value is assigned in a smaller size primitive data type, this is
called narrowing of the variable. It can cause some data loss due to less number of bits available to
store the data. It requires explicit type-casting to required data type.

Example:

class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10

SMVEC-Department of Information Technology Page 26


IT T45- Java Programming

1.7 Compiling and running of simple Java program.


1.7.1 Getting User Input
While Java provides many different methods for getting user input, the Scanner object is the
most common, and perhaps the easiest to implement. Import the Scanner class to use the Scanner
object,:import java.util.Scanner;
In order to use the Scanner class, create an instance of the class by using the following syntax:

Scanner myVar = new Scanner(System.in);

We can now read in different kinds of input data that the user enters.

Here are some methods that are available through the Scanner class:

 Read a byte - nextByte()


 Read a short - nextShort()
 Read an int - nextInt()
 Read a long - nextLong()
 Read a float - nextFloat()
 Read a double - nextDouble()
 Read a boolean - nextBoolean()
 Read a complete line - nextLine()
 Read a word - next()

Example program used to get user input:

import java.util.Scanner;
import java.io.*;
class MyClass
{
public static void main(String[ ] args)
{
System.out.println(“Enter a Line”);
Scanner myVar = new Scanner(System.in);
String str1=myvar.nextLine( );
System.out.println(“Entered String is: “+str1);
}
}
Output:
Enter a line: Welcome Program
Entered String is: Welcome program

The Keywords used in the program:

 class keyword is used to declare a class in java.


 public keyword is an access modifier which represents visibility. It means it is visible to all.

SMVEC-Department of Information Technology Page 27


IT T45- Java Programming

 static is a keyword. If we declare any method as static, it is known as the static method. The
core advantage of the static method is that there is no need to create an object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create an
object to invoke the main method. So it saves memory. Thismethod can be run without creating
an instance of the class containing the main method.
 void is the return type of the method. It means it doesn't return any value.
 main represents the starting point of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

The main method can be represented by different ways:

 public static void main(String[] args)


 public static void main(String []args)
 public static void main(String args[])

1.7.2 Compiling the Program

A program has to be converted to a form the JVM can understand so any computer with a JVM
can interpret and run the program. Compiling a Java program means taking the programmer-readable
text in your program file (also called source code) and converting it to byte codes, which are platform-
independent instructions for the JVM.

The Java compiler is invoked at the command line on DOS shell operating systems as follows:

C:\mywork> javac MyClass.java


This runs javac.exe, the compiler. If any error in the program will be displayed else it displays
the command prompt.
C:\mywork>

Note: Part of the configuration process for setting up the Java platform is setting the class path. The
class path can be set using either the -classpath option with the javac compiler command and java
interpreter command, or by setting the CLASSPATH environment variable. You need to set the class
path to point to the directory where the MyClass class is so the compiler and interpreter commands can
find it.

SMVEC-Department of Information Technology Page 28


IT T45- Java Programming

1.7.3 Interpreting and Running the Program

Once our program successfully compiles into Java bytecodes, we can interpret and run
applications on any JVM, which converts the Java byte codes to platform-dependent machine codes so
your computer can understand and run the program.The Java interpreter is invoked at the command line
on DOS shell operating systems as follows:

C:\mywork> java MyClass

This runs the Java interpreter and displays the output as follows

Enter a line: Welcome Program


Entered String is: Welcome program

1.8 Concepts of classes and objects

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real
life entities.

1.8.1 Class Fundamentals

A class is a user defined blueprint or prototype from which objects are created. It is also an
entity that determines how an object will behave and what the object will contain. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations can
include these components:

Syntax
Modifier class <class_name>
{
Data members(fields);
constructors
Methods;
}
Modifiers: A class can be public or has default access
class: Keyword used to represent the class
Class name: The name should begin with an initial letter (capitalized by convention).
Body: The class body surrounded by braces, { }.
Fields: Variables that provides the state of the class and its objects
Methods: are used to implement the behavior of the class and its objects.

SMVEC-Department of Information Technology Page 29


IT T45- Java Programming

Modifiers in Java:
The access modifiers in Java helps to restrict the scope of a class, constructor , variable , method
or data member.
For classes, the available modifiers are public or default (left blank), as described below:

public: The class is accessible by any other class.


default: The class is accessible only by classes in the same package.
The following choices are available for attributes (fields) and methods:

 default: A variable or method declared with no access control modifier is available to any other
class in the same package.
 public: Accessible from any other class.
 protected: Provides the same access as the default access modifier, with the addition that
subclasses can access protected methods and variables of the superclass (Subclasses and
superclasses are covered in upcoming lessons).
 private: Accessible only within the declared class itself.

Example:
public class MyClass
{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
1.8.3 Declaring Objects in Java
An object in Java is the physical as well as logical entity whereas a class in Java is a logical
entity only. An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
SMVEC-Department of Information Technology Page 30
IT T45- Java Programming

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.

Fig Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.

 Declaring Objects (Also called instantiating a class)


Example: MyClass obj;
 When an object of a class is created, the class is said to be instantiated. All the instances share
the attributes and the behavior of the class. But the values of those attributes, i.e. the state are
unique for each object. A single class may have any number of instances(objects).

1.8.4 Initializing Objects in Java

The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.

Example : MyClass obj= new MyClass( );

There are three ways to initialize object in java.


 By reference variable
 By method
 By constructor

SMVEC-Department of Information Technology Page 31


IT T45- Java Programming

1.8.5 Accessing the instance variables (object reference variables ) and methods using objects:
Instance variables and methods are accessed via created objects. To access an instance variable,
following is the fully qualified path:

MyClass obj = new Myclass( ); // Initializing the object


obj.variableName =”Initial value” ; // Initializing the reference variable
obj.MethodName( ); // Accessing the method

Example
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea( )
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:

55
45

SMVEC-Department of Information Technology Page 32


IT T45- Java Programming

1.9 Methods in Java


A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us to reuse
the code without retyping the code. In Java, every method must be part of some class.

Types of Java methods


Depending on whether a method is defined by the user, or available in standard library, there are
two types of methods:
 Standard Library Methods
 User-defined Methods

1.9.1 Standard Library Methods


The standard library methods are built-in methods in Java that are readily available for use.
These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with
JVM and JRE.

print( ) - is a method of java.io.PrintSteam. The print("...") prints the string inside quotation marks.
sqrt( ) - is a method of Math class. It returns square root of a number.

public class Numbers


{
public static void main(String[] args)
{
System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}
Output:
Square root of 4 is: 2.0

1.9.2 User-defined Method


We can also define methods inside a class , such methods are called user-defined methods.
Before calling the method the method must be declared:

1.9.2.1 Method Declaration


In general, method declarations have six components:

modifier static returnType Methodname (Parameter List)


{
// method body
}

 Modifier: Defines access type of the method i.e. from where it can be accessed in your
application.

SMVEC-Department of Information Technology Page 33


IT T45- Java Programming

 public: accessible in all class in your application.


 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
 The return type: The data type of the value returned by the method or void if does not return a
value.
 Method Name: the name of the method.
 Parameter list: Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
 Exception list : The exceptions you expect by the method can throw
 Method body: it is enclosed between braces. The code you need to be executed to perform our
intended operations.

1.9.2.2 Calling a Method:


To execute a method, a call should be made to the method.

myMethod( );
This statement calls the myMethod() method that was declared earlier.

SMVEC-Department of Information Technology Page 34


IT T45- Java Programming

Example:
public class MyClass
{
int age;
String breed;
String color;
String name;
void getinput( )
{
Scanner input = new Scanner (System.in);
System.out.println(“Enter the age ,breed and name”);
age=input.nextInt( );
breed=input.next( );
color=input.next( );
}
void display( )
{
System.out.println(“The Age:”+age);
System.out.println(“The Breed:”+name);
System.out.println(“The Color:”+breed);
System.out.println(“The Name:”+name);
}
void bark( )
{
System.out.println(“The Dog barks”);
}

public static void main(String[ ] args)


{
Myclass obj= new MyClass( );
obj.name=”Morris”;
obj.getinput( );
obj.display( );
obj.bark( );
}
}
Output:
Enter the age ,breed and name:
5
German shepherd
brown
The Age:5
The Breed: German shepherd
The Color:brown
The Name:Morris
The Dog barks

SMVEC-Department of Information Technology Page 35


IT T45- Java Programming

1.10 Constructor
It is a special type of method which is used to initialize the object. It is called when an
instance of the object is created, and memory is allocated for the object. It has the same name as its
class and is syntactically similar to a method. However, constructors have no explicit return type.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero.

1.10.1 Rules for creating Java constructor.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Syntax:
class ClassName
{
ClassName()
{
}
}
1.10.2 Types of Java constructors
There are two types of constructors in Java:
 Default constructor (No-argument constructor)
 Parameterized constructor
1.10.2.1 Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.It will be
invoked at the time of object creation.
Syntax :
<class_name>( ){ }
class Demo
{
int value1;
int value2;
Demo( )
{
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}

SMVEC-Department of Information Technology Page 36


IT T45- Java Programming

public void display()


{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[])
{
Demo d1 = new Demo();
d1.display();
}
}
Output:
Inside Constructor
Value1 === 10
Value2 === 20

1.10.2.2 Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.The parameterized constructor is used to provide different values to the distinct objects.
However, we can provide the same values also.
class Student1
{
int Sno;
String Sname;
public Student1( int no, String name)
{
Sno = no ;
Sname = name ;
}
public void display()
{
System.out.println(Sno);
System.out.println(Sname);
}

public static void main(String args[])


{
Student1 S1 = new Student1( 101 , "Aravind" );
Student1 S2 = new Student1( 102 , "Arun" );
S1.display();
S2.display( );
}
}

SMVEC-Department of Information Technology Page 37


IT T45- Java Programming

Output:
101
Aravind
102
Arun

1.10.2.3 Copy Constructor


There is no copy constructor in java. However, we can copy the values from one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
Student(Student s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan

SMVEC-Department of Information Technology Page 38


IT T45- Java Programming

Difference between constructor and method in Java

Java Constructor Java Method


A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as
name. class name.

1.11 Usage of static with data and methods


The static is a non-access modifier in Java. The static keyword in Java is used for memory
management mainly. We can apply java static keyword with variables, methods, blocks and nested
class. The static keyword belongs to the class than an instance of the class(object).
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class

To create a static member (block, variable, method, nested class), precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.

1.11.1 static variable


If you declare any variable as static, it is known as a static variable.The static variable can be used
to refer to the common property of all objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.The static variable gets memory only once
in the class area at the time of class loading.
Syntax
[access_specifier] static data_type field_name;
Example:
import java.io.*;
class Staticvar
{
static int count=0;
public void increment()
{
count++;
}

SMVEC-Department of Information Technology Page 39


IT T45- Java Programming

public static void main(String args[])


{
Staticvar obj1=new Staticvar();
Staticvar obj2=new Staticvar();
Staticvar obj3=new Staticvar();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is= "+obj1.count);
System.out.println("Obj2: count is= "+obj2.count);
obj3.increment();
System.out.println("Obj3: count is= "+obj3.count);
}
}

Output:
Obj1: count is= 1
Obj2: count is= 2
Obj3: count is= 3

1.11.2 static Method

Static methods are the methods in Java that can be called without creating an object of class.
They are referenced by the class name itself or reference to the Object of that class.

 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it

Need of static methods:


 When you have code that can be shared across all instances of the same class, put that portion of
code into static method.
 They are basically used to access static field(s) of the class.
Syntax
[access_specifier] static return_type method_name(arguments)
{
//statements;
}
Example:
class Student
{
int rollno;
String name;
static String company = "TCS";
static void change( )
{
company = "CTS";
}

SMVEC-Department of Information Technology Page 40


IT T45- Java Programming

Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+company);
}
}
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method

Student s1 = new Student(111,"Karan");


Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan CTS
222 Aryan CTS
333 Sonoo CTS

Difference between the Instance method and Static method


 Instance method can access the instance methods and instance variables directly.
 Instance method can access static variables and static methods directly.
 Static methods can access the static variables and static methods directly.
 Static methods can‟t access instance methods and instance variables directly. They must use
reference to object. And static method can‟t use this keyword as there is no instance for „this‟ to
refer to.

1.11.3 static block


 Is used to initialize the static data member.
 It is executed before the main method at the time of class loading.
class A2
{
static
{
System.out.println("static block is invoked");
}

SMVEC-Department of Information Technology Page 41


IT T45- Java Programming

public static void main(String args[])


{
System.out.println("Hello main");
}
}
Output:
Hello main

1.12 Usage of final with data


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
 variable- To create constant variables
 method- To prevent Method overriding
 class- To Prevent Inheritance

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static block only.

1.12.1 Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example :
class Bike
{
final int speedlimit=90; //final variable
void speed()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.speed();
}
}

Output:Compile Time Error

1.12.2 Java final method


A final method cannot be overridden by any subclasses. The main intention of making a method
final would be that the content of the method should not be changed by any outsider.

SMVEC-Department of Information Technology Page 42


IT T45- Java Programming

Example :
public class Test
{
public final void changeName()
{
// body of method
}
}

1.12.3 Final Classes


The main purpose of using a class being declared as final is to prevent the class from being sub
classed. If a class is marked as final then no class can inherit any feature from the final class.
Example
public final class Test
{
// body of class
}

1.12.4 Uninitialized final variable:


A final variable that is not initialized at the time of declaration is known as blank final
variable.It can be initialized only in constructor.
For example PAN CARD number of an employee.
class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
}
1.12.5 static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.
Example:
class A
{
static final int data; //static blank final variable
static
{
data=50;
}
public static void main(String args[])
{
System.out.println(A.data);
}
}

SMVEC-Department of Information Technology Page 43


IT T45- Java Programming

Static Final: Attributes whose value remains same throughout all its instances , But cannot be changed
by Any instance.

Difference between static and final


Static Keyword:
 Static keyword is used to do better memory management.
 You can use static keyword with variable, method, class.
 If you declare method using static keyword then you don't need to create an object to call that
method.
 If you declare variable as a static then only once memory is created for that variable in class
area and not every time when object is created. e.g. in student database you can declare "college
name" as because it common for all students.

Final Keyword:
 Final Keyword is used to restrict the user. It means:
 If you declare variable as static then you cannot change its value.
 If you declare method as static then you cannot override that method.
 If you make any class as final, you cannot extend it.

1.13 Access Control in java


Java provides a number of access modifiers to set access levels (scope) for classes, variables,
methods, and constructors.
There are two types of modifiers in java:
 Access modifiers
 Non-access modifiers.
There are four types of java access modifiers:
 private
 default
 protected
 public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc.
1.13.1 private access modifier
Methods, variables, and constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
Example:
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
SMVEC-Department of Information Technology Page 44
IT T45- Java Programming

public class Simple


{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

1.13.2 default access modifier


If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
Example :
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.
A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

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
}
}

1.13.3 protected access modifier


Variables, methods, and constructors, which are declared protected in a super class can be
accessed only by the subclasses in other package or any class within the package of the protected
members' class. The protected access modifier cannot be applied to class and interfaces.

SMVEC-Department of Information Technology Page 45


IT T45- Java Programming

Example
A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:Hello

1.13.4 public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello

SMVEC-Department of Information Technology Page 46


IT T45- Java Programming

1.13.5 Understanding all java access modifiers


Access Modifier Within class Within package Outside package Outside package
by subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

1.14 This keyword in java


In java, this is a reference variable that refers to the current object. It can also be used for some
other purposes such as:
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this( ) can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

1.14.1 this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee) Output:
{
this.rollno=rollno; 111 ankit 5000
this.name=name;
this.fee=fee; 112 sumit 6000
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

SMVEC-Department of Information Technology Page 47


IT T45- Java Programming

1.14.2 this: to invoke current class method


We invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method.
class A
{
void m( )
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
this.m( );
}
}
class TestThis
{ Output:
public static void main(String args[])
hello n
{
A a=new A(); hello m
a.n();
}
}

1.15 Java Garbage Collection


In java, garbage means unreferenced objects.Garbage Collection is process of retrieving the
runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

1.15.1 Automatic Garbage Collection:


Automatic garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced
object, means that some part of your program still maintains a pointer to that object. An unused object,
or unreferenced object, is no longer referenced by any part of your program. So the memory used by an
unreferenced object can be reclaimed.

1.15.2 Advantage of Garbage Collection


 It makes java memory efficient, because garbage collector removes the unreferenced objects
from heap memory.
 It is automatically done by the garbage collector (a part of JVM) so we don't need to make extra
efforts.

There are many ways by which garbage collection is performed:


 By nulling the reference
 By assigning a reference to another
 By anonymous object etc.

SMVEC-Department of Information Technology Page 48


IT T45- Java Programming

1.15.3 By nulling a reference:


Employee e=new Employee();
e=null;

1.15.4 By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2; //now the first object referred by e1 is available for garbage collection

1.15.5 By anonymous object:


new Employee();

1.15.6 Usage of finalize ( ) and gc ( ) in garbage collection:


finalize() method -The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){ }
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if
you have created any object without new, you can use finalize method to perform cleanup processing
(destroying remaining objects).

gc( ) method- The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.

public static void gc(){}


Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread
calls the finalize() method before object is garbage collected.
Example:
public class TestGarbage
{
public void finalize( )
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc( );
}
}
Output:
object is garbage collected
object is garbage collected

SMVEC-Department of Information Technology Page 49


IT T45- Java Programming

1.16 Overloading methods and constructors


1.16.1 Method Overloading
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. Method overloading increases the readability of the program.
We can also overload two or more static methods with same name, but differences in input
parameters.
1.16.2 Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
import java.io.*;
import java.util.Scanner;
class Add
{
public void sum(int a,int b)
{
System.out.println("Sum is : "+(a+b));
}
public void sum(int a,int b,int c)
{
System.out.println("Sum is : "+(a+b+c));
}
public static void main(String args[])
{
int ch,a,b,c;
Add a1= new Add();
Scanner s=new Scanner(System.in);
System.out.println("Enter the choice of addition (2 or 3)");
ch=s.nextInt();
System.out.print("Enter the inputs : ");
switch(ch)
{
case 1:
a=s.nextInt();
b=s.nextInt();
a1.sum(a,b);
break;
case 3:
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
a1.sum(a,b,c);
break;
default:
System.out.println("Enter valid choice");
}
}
}
SMVEC-Department of Information Technology Page 50
IT T45- Java Programming

Output:
Enter the inputs: 10 20
Sum is:30
Enter the inputs: 10 20 30
Sum is:60

1.16.3 Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods. Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types.
class Demo
{
int value1;
int value2;
Demo( )
{
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a)
{
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a, int b)
{
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display( )
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[])
{
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display( );
d2.display( );
d3.display( );
}
}

SMVEC-Department of Information Technology Page 51


IT T45- Java Programming

Output:
Inside 1st Constructor
Value1 === 10
Value2 === 20
Inside 2nd Constructor
Value1 === 30
Value2 === 0
Inside 3rd Constructor
Value1 === 30
Value2 === 40

1.17 Parameter Passing


In Java, Primitive variables store the actual values, whereas Non-Primitives store the reference
variables which point to the addresses of the objects they‟re referring to. Both values and references are
stored in the stack memory.

Arguments in Java are always passed-by-value. During method invocation, a copy of each
argument, whether its a value or reference, is created in stack memory which is then passed to the
method. In case of primitives, the value is simply copied inside stack memory which is then passed to
the callee method; in case of non-primitives, a reference in stack memory points to the actual data
which resides in the heap. When we pass an object, the reference in stack memory is copied and the
new reference is passed to the method.

1.17.1 Call by Value:


Primitive variables are directly stored in stack memory. Whenever any variable of primitive
data type is passed as an argument, the actual parameters are copied to formal arguments and these
formal arguments accumulate their own space in stack memory.
public class Tester
{
public static void main(String[ ] args)
{
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swap(a, b);
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swap(int a, int b)
{
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

SMVEC-Department of Information Technology Page 52


IT T45- Java Programming

Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
After swapping, a = 30 and b is 45

1.18 Recursion in Java


Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method. It makes the code compact but complex to understand.
Syntax:
returntype method name( )
{
//code to be executed
methodname( );//calling same method
}
public class Recursion
{
static int factorial(int n)
{
if (n == 1)
{
return 1;
}
else
{
return(n * factorial(n-1));
}
}
public static void main(String[] args)
{
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output:
Factorial of 5 is: 120
Working of above program:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

SMVEC-Department of Information Technology Page 53


IT T45- Java Programming

1.19 Nested Class


In java, it is possible to define a class within another class, such classes are known as nested
classes. They enable to logically group classes that are only used in one place, thus this increases the
use of encapsulation, and create more readable and maintainable code.

 The scope of a nested class is bounded by the scope of its enclosing class.
 A nested class has access to the members, including private members, of the class in which it is
nested. However, reverse is not true i.e. the enclosing class does not have access to the members
of the nested class.
 A nested class is also a member of its enclosing class.
 As a member of its enclosing class, a nested class can be declared private, public, protected, or
package private (default).

Nested classes are divided into two categories:


 static nested class : Nested classes that are declared static are called static nested classes.
 inner class : An inner class is a non-static nested class.

Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}

1.19.1 Static nested classes


As with class methods and variables, a static nested class is associated with its outer class. And
like static class methods, a static nested class cannot refer directly to instance variables or methods
defined in its enclosing class: it can use them only through an object reference.
They are accessed using the enclosing class name.

SMVEC-Department of Information Technology Page 54


IT T45- Java Programming

OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass obj = new OuterClass.StaticNestedClass( );

Example:
class OuterClass
{
// static member
static int outer_x = 10;
int outer_y = 20;
private static int outer_private = 30;

// static nested class


static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access display private static member of outer class


System.out.println("outer_private = " + outer_private);

// The following statement will give compilation error


// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);

}
}
}
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

nestedObject.display( );

}
}
Output:

outer_x = 10
outer_private = 30

SMVEC-Department of Information Technology Page 55


IT T45- Java Programming

1.19.2 Accessing the Private Members with inner class:


The inner classes are also used to access the private members of a class. Suppose, a class is
having private members to access them. Write an inner class in it, return the private members from a
method within the inner class, say, getValue( ), and finally from another class (from which you want to
access the private members) call the getValue( ) method of the inner class.

To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the
object of the outer class, following is the way in which you can instantiate the inner class.

Outer_Demo outer = new Outer_Demo();


Outer_Demo.Inner_Demo inner = outer.new Inner_Demo( );

Example:
class Outer_Demo
{

private int num = 175;


// inner class
public class Inner_Demo
{
public int getNum()
{
System.out.println("This is the method of the inner class");
return num;
}
}
}

public class My_class2


{
public static void main(String args[])
{
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Instantiating the inner class


Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}

Output

This is the method of the inner class: 175

SMVEC-Department of Information Technology Page 56


IT T45- Java Programming

1.20 Exploring the String class

In Java programming, strings are a sequence of characters. In Java programming language,


strings are treated as objects.Handling character strings in Java is supported through two final classes:

 String
 StringBuffer
The String class implements immutable character strings, which are read-only once the string
has been created and initialized, whereas the StringBuffer class implements dynamic character strings.

1.20.1 Creating a String

There are two ways to create string in Java:


String literal
String s = “Welcome Java”;
Using new keyword
String s = new String (“Welcome Java”);

1.20.2 Constructors of String Class:


Constructor & Description
String()
This initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
This constructs a new String by decoding the specified array of bytes using the platform's default
charset.
String(byte[] bytes, Charset charset)
This constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] bytes, int offset, int length)
This constructs a new String by decoding the specified subarray of bytes using the platform's
default charset
String(byte[] bytes, int offset, int length, Charset charset)
This constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] bytes, int offset, int length, String charsetName)
This constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] bytes, String charsetName)
This constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
This allocates a new String so that it represents the sequence of characters currently contained in
the character array argument.

SMVEC-Department of Information Technology Page 57


IT T45- Java Programming

String(char[] value, int offset, int count)


This allocates a new String that contains characters from a subarray of the character array
argument.
String(int[] codePoints, int offset, int count)
This allocates a new String that contains characters from a subarray of the Unicode code point
array argument.
String(String original)
This initializes a newly created String object so that it represents the same sequence of characters
as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
This allocates a new string that contains the sequence of characters currently contained in the
string buffer argument.
String(StringBuilder builder)
This allocates a new string that contains the sequence of characters currently contained in the
string builder argument.

1.20.3 Methods for Comparing and Concatenation of Strings:


 Strings in java can be compared using the = operator and equals( ) method.
 In java Strings can be concatenated using “+” operator and concat( ) method.
Example :The following code performs comparison and concatenation of strings
class Example1
{
public static void main(String args[])
{
String s1=”Java”;
String s2=”Java”;
String s3=”C++”;
String obj=new String(“Java”);
if(s1==s2)
{
System.out.println(“s1 and s2 are Equal”);
}
else
{
System.out.println(“s1 and s2 are not Equal”);
}
if(s1==obj)
{
System.out.println(“s1 and obj are Equal”);
}
else
{
System.out.println(“s1 and obj are not Equal”);
}

SMVEC-Department of Information Technology Page 58


IT T45- Java Programming

if(s1.equals(obj))
{
System.out.println(“Now !! s1 and obj are Equal”);
}
else
{
System.out.println(“s1 and obj are not equal”);
}
System.out.println(“s1 + s3 =”+s1+s3);
System.out.println(“s2 + s3 =”+s2.concat(s3));
}
}
Output
s1 and s2 are Equal
s1 and obj are not Equal
Now !! s1 and obj are Equal
s1 + s3 =JavaC++
s2 + s3 =JavaC++

1.20.4 Methods for Handling Individual Characters:

Method Purpose

charAt(int index) Returns the character at the specified index.

getChars(int srcBegin, int srcEnd, Copies characters from this string into the destination character
char[ ] dst, int dstBegin) array.
indexOf(int ch) Returns the index within this string of the
first occurrence of the specified character
indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified
index.
lastIndexOf(int ch) Returns the index within this string of the last occurrence of
the specified character.
replace(char oldChar,char newChar) Returns a new string resulting from replacing
all occurrences of oldChar in this string
with newChar

Example:
class Example2
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“4th Character “+str.charAt(4));
System.out.println(“Index of Character U is “+str.indexOf(„U‟));

SMVEC-Department of Information Technology Page 59


IT T45- Java Programming

System.out.println(“Last Index of Character i is “+str.lastIndexOf(„i‟));


char m[]=new char[10];
str.getChars(6,10,m,0);
System.out.println(“The String is “+new String(m));
System.out.println(“When U Changed to Y “+str.replace(„U‟,‟Y‟));
}
}
Output:
4th Character n
Index of Character U is 1
Last Index of Character i is 10
The String is vers
When U Changed to Y PY Yniversity

1.20.5 Methods for Searching Strings


Method Purpose
startsWith(String prefix) Tests if this string starts with the specified
prefix.
startsWith(String prefix, int toffset) Tests if this string starts with the specified
prefix beginning a specified index
endsWith(String suffix) Tests if this string ends with the specified suffix

Example: Performs searches for a pattern in the given string.

class Example3
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“String Starts with Anna : “+str.startsWith(“PU”));
System.out.println(“Ends With Anna : “+str.endsWith(“PU”));
}
}

Output :
String Starts with Anna : true
Ends With Anna : false

1.20.6 Methods for Extracting Substrings


Method Purpose
substring(int beginIndex) Returns a new string that is a substring of this
string.
substring(int beginIndex, int endIndex) Returns a new string that is a substring of this
string.

SMVEC-Department of Information Technology Page 60


IT T45- Java Programming

Example : extracts a substring from the given string


class Example4
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“Substring from 6th position : “+str.substring(3));
System.out.println(“Substring from 6th to 10th position : “+str.substring(3,6));
}
}

Output :
Substring from 6th position : University
Substring from 6th to 10th position : Univ

1.20.7 Methods for Case Conversion:

Method Purpose
toLowerCase() Converts all of the characters in this
String to lower case
toUpperCase() Converts all of the characters in this
String to upper case

Example: performs case conversion.

class Example5
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“ LowerCase “+str.toLowerCase());
System.out.println(“ UpperCase “+str.toUpperCase());
}
}
Output :
LowerCase pu university
UpperCase PU UNIVERSITY

1.20.8 Methods for Type Conversion


Method Purpose
valueOf(type) Returns the string representation of the type
argument.
getBytes(String enc) Convert this String into bytes according to the
specified character encoding, storing the result
into a new byte array

SMVEC-Department of Information Technology Page 61


IT T45- Java Programming

Example: performs type conversion

class Example6
{
public static void main(String args[])
{
String str=”This is a test”;
int i=100;
System.out.println(“Bytes Representation “+str.getBytes());
System.out.println(“String value of integer 100 : “+String.valueOf(i));
}
}

Output :
Bytes Representation [B@10b62c9
String value of integer 100 : 100

1.20.9 Miscellaneous methods

Method Purpose
trim() This method removes white space from the front
and the end of a String.
length() Returns length of the String.

Example: finds the length of the string an eliminates white space from the front and the end of a String.

class Example7
{
public static void main(String args[])
{
String str=”JAVA “;
str=str.trim();
System.out.println(“Length of the String is “+str.length());
}
}

Output :
Length of the String is 4

1.20.10 StringBuffers:

 StringBuffer class is a mutable class unlike the String class which is immutable.
 Both the size and character string of a StringBuffer can be changed dynamically.
 String buffers are preferred when frequent modification of character strings is involved like
appending, inserting, deleting, modifying etc.

SMVEC-Department of Information Technology Page 62


IT T45- Java Programming

Creation of StringBuffer:

A StringBuffer in Java can be created using the following three constructors.


StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
StringBuffer strBuf1 = new StringBuffer(“Computer”); // Capacity is 24
Explanation:
 The first constructor creates a StringBuffer that has the storage capacity to store 100 characters.
 The second constructor creates a StringBuffer that has the default storage capacity to store 16
characters.
 The last constructer creates a StringBuffer with a String parameter, it creates a StringBuffer
with a capacity 24 i.e default capacity + 8 (the length of String parameter).
Methods in StringBuffer
StringBuffer supports many methods that are available in String Class, apart from that StringBuffer
supports some unique methods.
Method Purpose
capacity() Returns the current capacity of the Stringbuffer.
length() Returns the length (character count) of this string buffer.
toString() Converts to a string representing the data in this string
buffer
insert(int offset, char c) Inserts the string representation of the char argument into
the StringBuffer
delete(int start, int end) Removes the characters in a substring of this
StringBuffer
replace(int start, int end, String str) Replaces the characters in a substring of this
StringBuffer with characters in the specified String.
reverse() The character sequence contained in this string buffer is
replaced by the reverse of the
sequence.
append(String str) Appends the string to this string buffer.

SMVEC-Department of Information Technology Page 63


IT T45- Java Programming

Example:
public class StringMethods
{
public static void main(String[] args)
{
//Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer(“APPLE”);
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
//Print the Capacity of StringBuffers
System.out.println(“strBuf1 capacity : “+strBuf1.capacity());
System.out.println(“strBuf2 capacity : “+strBuf2.capacity());
System.out.println(“strBuf3 capacity : “+strBuf3.capacity());
//toString Method
System.out.println(“strBuf1 toString() is : “+strBuf1.toString());
//append Method
strBuf2.append(“HandBook”);
System.out.println(“ strBuf2 is appended with :“+strBuf2.toString());
//insert Method
strBuf2.insert(1, „A);
System.out.println(“strBuf2 when A is inserted at 1 : “+strBuf2.toString());
strBuf2.insert(2, „n);
System.out.println(“strBuf2 when n is inserted at 2 :“+strBuf2.toString());
//delete Method
strBuf2.delete(2, „n‟);
System.out.println(“strBuf2 when n is deleted at 2 :“+strBuf2.toString());
//reverse Method
strBuf2.reverse();
System.out.println(“Reversed strBuf2 : “+strBuf2);
}
}

SMVEC-Department of Information Technology Page 64


IT T45- Java Programming

Output :
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 toString() is : APPLE
strBuf2 is appended with :HandBook
strBuf2 when A is inserted at 1 : HAandBook
strBuf2 when n is inserted at 2 : HAnandBook
strBuf2 when n is deleted at 2 : HA
Reversed strBuf2 : AH

SMVEC-Department of Information Technology Page 65


IT T45- Java Programming

1.List the Features of Java (or) java Buzzwords


The features of Java are also known as java buzzwords. A list of most important features of
Java language is given below.
 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic

2.What is Java Byte code?


Java byte code is the instruction set for the Java Virtual Machine. The java byte code is the
machine code in the form of a .class file. With the help of java byte code we achieve platform
independence in java.

3.Why java is important to the Internet


 Passive information
For example, when you read your e-mail, you are viewing passive data. Even when you download a
program, the program‟s code is still only passive data until you execute it.
 Dynamic, active programs.
A dynamic, self- executing program. Such a program is an active agent on the client computer,
yet is initiated by the server. For example, a program might be provided by the server to display
properly the data that the server is sending.

SMVEC-Department of Information Technology Page 66


IT T45- Java Programming

4.Why java is known as Platform-independent language?


Java is called Platform independent because the programs in java can be executed on variety of
systems. This feature is based on the goal “write once, run anywhere and at anytime, forever”.

5.Why is main() method static?


To access the static method the object of the class is not needed. The method can be access
directly with the help of ClassName. So when a program is started the jvm search for the class
with main method and calls it without creating an object of the class.

6.How will you find length of the array


 Size of an array is accessed by using the length attribute.
 Syntax
 Array_name.length;
 Eg:mark.length;
7.Define class.
 The class forms the basis for object oriented programming in java.
 A class is a template for an object and an object is an instance of a class.
 A class is declares by use of the class keyword.
 Methods and variables defined within a class are called members of the class.

8.Define Methods
 Functions defined inside the class definition are called as methods.
 It is used to manipulate the data variables.
 They can be defined only inside the appropriate classes.
 It defines behavior of the object.
Syntax
[access_specifier] return_type method_name(formal_argument_list)
{
//method body
[return value]
}
9.What are different types of access modifiers (Access specifiers)?
 Access specifiers are keywords that determine the type of access to the member of a class.
 These keywords are for allowing privileges to parts of a program such as functions and
variables.
 public: Anything declared as public can be accessed from anywhere.
 private: Anything declared as private can‟t be seen outside of its class.
 protected: Anything declared as protected can be accessed by classes in the same package
and subclasses in the other packages.

10.How will you declare Objects in java


The new operator dynamically allocates memory for an object and returns a reference to it. This
reference is then stored in the variable.

SMVEC-Department of Information Technology Page 67


IT T45- Java Programming

Syntax
Classname class-var = new classname( );
Eg
Box mybox = new Box();

11.List out features of constructor


 A constructor has the same name as the class.
 A class can have more than one constructor.
 A constructor may take zero, one, or more parameters.
 A constructor has no return value.
 A constructor is always called with the new operator.

12.Define this keyword


 “this” Keyword this can be used inside any method to refer to the current object.
 This keyword has two meanings:
 to denote a reference to the implicit parameter.
 to call another constructor of the same class.

13.Define Garbage Collection


 The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused.
 A Java object is subject to garbage collection when it becomes unreachable to the program
in which it is used.

14.What is Garbage Collection and how to call it explicitly?


 When an object is no longer referred to by any variable, java automatically reclaims
memory used by that object. This is known as garbage collection.
 System. gc() method may be used to call it explicitly

15.What is the difference between this() and super()?


 this() can be used to invoke a constructor of the same class.
 super() can be used to invoke a super class constructor.

16.What is finalize() method?


finalize () method is used just before an object is destroyed and can be called just prior to
garbage collection.

17.Explain working of Java Virtual Machine (JVM)?


JVM is an abstract computing machine like any other real computing machine which first
converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and
Interpreter reads byte codes.

18.Under which context we use final and finally keyword?


final: final is a keyword. The variable declared as final should be initialized only once and cannot
be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be
overridden.
finally: finally is a block. The finally block always executes when the try block exits. This ensures
that the finally block is executed even if an unexpected exception occurs. But finally is useful for
SMVEC-Department of Information Technology Page 68
IT T45- Java Programming

more than just exception handling - it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break.

19.Write about the Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
 Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

20.Write about the Boolean Data Type in java

The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.

Example: Boolean one = false;

21.Difference between Instance variables and Class Variables

Static (class Variables) Instance Variables

Instance variables are declared


Class variables are declared with keyword static. without static keyword.

Class variables are common to all instances of a class. Instance variables are not shared between the
These variables are shared between the objects of a objects of a class. Each instance will have their
class. own copy of instance variables.

As each object will have its own copy of instance


As class variables are common to all objects of a variables, changes made to these variables
class, changes made to these variables through one through one object will not reflect in another
object will reflect in another. object.

Class variables can be accessed using either class Instance variables can be accessed only through
name or object reference.( ClassName.VariableName) object reference(Objectname.VariableName).

22.Define Java Variables

A variable is a container which holds the value while the java program is executed. A variable is
assigned with a data type.

 Local- A variable declared inside the body of the method is called local variable
 Instance - A variable declared inside the class but outside the body of the method, is called
instance variable.

SMVEC-Department of Information Technology Page 69


IT T45- Java Programming

 Static-A variable which is declared as static is called static variable


This can also be called as the class variables. You can create a single copy of static variable and
share among all the instances of the class

23.How can we Dynamically Initialize the Variable in java?

Java allows its programmers to initialize a variable at run time also. Initializing a variable at run
time is called dynamic initialization

public class Dynamic


{
public static void main(String[] args)
{
double dynSqrt = Math.sqrt (16);
System.out.println("sqrt of 16 is : " + dynSqrt);
}
}

24.What is the Usage of finalize ( ) and gc ( ) in garbage collection:


finalize() method -The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method is defined in Object
class as:
protected void finalize(){ }
gc( ) method- The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.

public static void gc(){}

25.How does achieves Automatic Garbage Collection?


Automatic garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects.
There are many ways by which garbage collection is performed:
 By nulling the reference
 By assigning a reference to another
 By anonymous object etc.

26.Difference between constructor and method in Java

Java Constructor Java Method


A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

SMVEC-Department of Information Technology Page 70


IT T45- Java Programming

A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as
name. class name.

27.Write about the Type Conversion and casting in Java

Converting a value from one type to another type (data type) is known as type conversion.
Type conversion is of two types based on how the conversion is performed:
 Implicit conversion (also known as automatic conversion or coercion),
 Explicit conversion (also known as type casting).
Widening

When a small primitive type value is automatically accommodated in a bigger/wider


primitive data type, this is called widening of the variable.

Narrowing
When a larger primitive type value is assigned in a smaller size primitive data type, this is
called narrowing of the variable. It requires explicit type-casting to required data type.

28.Write about the Enhanced for loop in Java

Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides
a simpler way to iterate through the elements of a collection or array.

Syntax
for(declaration : expression)
{
// Statements
}
for(int x : numbers )
{
System.out.print( x );

29.What is Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
Declaring a 2D array with odd columns
SMVEC-Department of Information Technology Page 71
IT T45- Java Programming

int arr[][] = new int[3][];


arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];

30.What do you mean by Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.

printArray(new int[ ]{10,22,44,66});//passing anonymous array to method

31.Write short notes about Arrays in java


An array is a collection of similar type of elements that have a contiguous memory location.
Java array is an object which contains elements of a similar data type.

Types of Array in java

 Single Dimensional Array


 Multidimensional Array

Syntax to Declare an Array in Java

dataType []arr; (or)


dataType arr[];

32.Comparison the Scope and Lifetime of different Variables in java

33.Define Constructor Overloading in Java

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types

34.Write about how Parameters are passed in java?


In Java, Primitive variables store the actual values, whereas Non-Primitives store the reference
variables which point to the addresses of the objects they‟re referring to. Both values and references are
stored in the stack memory.

SMVEC-Department of Information Technology Page 72


IT T45- Java Programming

Arguments in Java are always passed-by-value. During method invocation, a copy of each argument,
whether its a value or reference, is created in stack memory which is then passed to the method.

35.What is Recursion in Java


Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method. It makes the code compact but complex to understand.
Syntax:
returntype method name( )
{
//code to be executed
methodname( );//calling same method
}

36.Define Nested Class in java?


In java, it is possible to define a class within another class, such classes are known as nested
classes. They enable to logically group classes that are only used in one place, thus this increases the
use of encapsulation, and create more readable and maintainable code.
Nested classes are divided into two categories:
 static nested class : Nested classes that are declared static are called static nested classes.
 inner class : An inner class is a non-static nested class.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
37.How can we access the Private Members with inner class:
The inner classes are also used to access the private members of a class. Suppose, a class is
having private members to access them. Write an inner class in it, return the private members from a
method within the inner class, say, getValue( ), and finally from another class (from which you want to
access the private members) call the getValue( ) method of the inner class.

38.Write about String in java?(or) What is the difference between String and StringBuffer

In Java programming language, strings are treated as objects.Handling character strings in Java
is supported through two final classes:

 String
 StringBuffer
The String class implements immutable character strings, which are read-only once the string
has been created and initialized, whereas the StringBuffer class implements dynamic character strings.
SMVEC-Department of Information Technology Page 73

You might also like