You are on page 1of 71

CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Declarations and Access Control

The scope of local variables will be only within the given method or class.

In Java, we have variables, methods, classes, packages, and interfaces as identifiers.

A Java file can have only one public class. If one source file contains a public class, the java
filename should be the public class name.

Source File Declaration:

A Java file can have only one public class. If one source file contains a public class, the
java filename should be the public class name.

Also, a Java source file can only have one package statement and unlimited import statements.

Identifiers Declaration:

Identifiers in Java can begin with a letter, an underscore, or a currency character. Other types of
naming are not allowed. They can be of any length.

In Java, we have variables, methods, classes, packages, and interfaces as identifiers.

Local Variables:

The scope of local variables will be only within the given method or class.

These variables should be initialized during declaration.

Access modifiers cannot be applied to local variables. A local variable declaration will be as
shown below:

public static void main(String[] args)


{
String helloMessage;
helloMessage = “Hello, World!”;
System.out.println(helloMessage);
}

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Instance Variables:
Instance variables are values that can be defined inside the class but outside the methods
and begin to live when the class is defined.

Here,unlike local variables, we don’t need to assign initial values.


It can be defined as public, private and protected.

 It can be defined as a final.


 It cannot be defined as abstract and static.

An example can be shown as below:


class Page {
public String pageName;
// instance variable with public access
private int pageNumber;
// instance variable with private access
}

Constructors:

We use the constructor to create new objects. Each class is built by the compiler, even if
we do not create a constructor defined in itself.

Constructors can take arguments, including methods and variable arguments. They must have the
same name as the name of the class in which it is defined.

They can be defined as public, protected, private.

Static:

It allows invoking the variable and method that it defines without the need for any object.
Abstract and static cannot be defined together, because the method presented as static can be
called without creating objects and by giving parameters directly.

The abstract is called to override a method. Abstract and static cannot be used together because
static has different purposes in this respect.
BCA
2
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

ENUM:

It is a structure that allows a variable to be constrained to be predefined by one value.

With Enum’s getValues method, we can reach all values of enums. This is the most elegant way
to define and use constants in our Java program.

Class Modifiers ( non-access):

1. Classes can be defined as final, abstract or strictfp.


2. Classes cannot be defined as both final and abstract.
3. Sub classes of the final classes cannot be created.
4. Instances of abstract classes are not created.
5. Even if there is one abstract method in a class, this class should also be defined as
abstract.
6. The abstract class can contain both the non-abstract method and abstract method, or it
may not contain any abstract method.
7. All abstract methods should be overridden by the first concrete (non-abstract) class that
extends the abstract class.

Class Access Modifiers:


Access modifiers stay an important part of a declaration that can be accessed outside the
class or package in which it is made.

Access modifiers enable you to decide whether a declaration is limited to a particular class, a
class including its subclasses, a package, or if it is freely accessible. Java language has three
access modifiers: public, protected and private.

 public: Enables a class or interface to be located outside of its package. It also permits a
variable, method, or constructor to be located anywhere its class may be accessed.
 protected: Enables a variable, method, or constructor to be accessed by classes or
interfaces of the same package or by subclasses of the class in which it is declared.

3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

 private: Prevents a variable, method, or constructor from being accessed outside of the
class in which it is declared.

Identifiers and Keywords

Identifiers in Java

Identifiers in Java are symbolic names used for identification. They can be a class name,
variable name, method name, package name, constant name, and more. However, In Java, There
are some reserved words that can not be used as an identifier.

For every identifier there are some conventions that should be used before declaring
them. Let's understand it with a simple Java program:

public class HelloJava


{
public static void main(String[] args)
{
System.out.println("Hello JavaTpoint");
}
}
From the above example, we have the following Java identifiers:
1. HelloJava (Class name)
2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)

4 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Rules for Identifiers in Java

There are some rules and conventions for declaring the identifiers in Java. If the identifiers
are not properly declared, we may get a compile-time error. Following are some rules and
conventions for declaring identifiers:

o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore(_) or a dollar sign ($). for example, @javatpoint is not a valid identifier
because it contains a special character which is @.
o There should not be any space in an identifier. For example, java tpoint is an invalid
identifier.

o An identifier should not contain a number at the starting. For example, 123javatpoint is
an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no limit on its
length. But, it is good to follow the standard conventions.

o We can't use the Java reserved keywords as an identifier such as int, float, double, char,
etc. For example, int double is an invalid identifier in Java.

Java Reserved Keywords

Java reserved keywords are predefined words, which are reserved for any functionality or
meaning. We can not use these keywords as our identifier names, such as class name or method
name. These keywords are used by the syntax of Java for some functionality. If we use a
reserved word as our variable name, it will throw an error.

In Java, every reserved word has a unique meaning and functionality.

Consider the below syntax:

double marks;

5 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

In the above statement, double is a reserved word while marks is a valid identifier.

Bstract continue for protected transient

Assert Default Goto public Try

Boolean Do If Static throws

break double implements strictfp Package

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

class finally long throw Date

const float Native This while

Oracle‘s Java Code Conventions


Code conventions are important to programmers for a number of reasons:
• 80% of the lifetime cost of a piece of software goes to maintenance.
• Hardly any software is maintained for its whole life by the original author.
• Code conventions improve the readability of the software, allowing engineers to
understand new code more quickly and thoroughly.
• If you ship your source code as a product, you need to make sure it is as well packaged
and clean as any other product you create.
File Names
This section lists commonly used file suffixes and names.
Java Source Files Each Java source file contains a single public class or interface.

6 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

When private classes and interfaces are associated with a public class, you can put them in the same
source file as the public class.
The public class should be the first class or interface in the file. Java source files have the
following ordering:

• Beginning comments
• Package and Import statements;
for example:
import java.applet.Applet;
import java.awt.*;
import java.net.*;

 Class and interface declarations

Beginning Comments

All source files should begin with a c-style comment that lists the programmer(s), the date, a
copyright notice, and also a brief description of the purpose of the program.
For example:
/* *
Classname
*
* Version info
*
* Copyright notice
*/

Package and Import Statements


The first non-comment line of most Java source files is a package statement.
After that, import statements can follow.

7 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

For example:
package java.awt;
Define Classes

Import Statements and the Java API

 A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.
 A class in Java is a logical template to create objects that share common properties and
methods.
 Hence, all objects in a given class will have the same methods or properties.
 For example: in the real world, a specific cat is an object of the “cats” class. All cats in the
world share some characteristics from the same template such as being a feline, having a tail,
or being the coolest of all animals.
 In Java, the “Cat” class is the blueprint from which all individual cats can be generated that
includes all cat characteristics, such as race, fur color, tail length, eyes shape, etc.
 So, for example, you cannot create a house from the cat class, because a house must have
certain characteristics — such as having a door, windows and a roof — and none of these
object properties can be found in the cat class.

A class declaration is made up of the following parts:

 Modifiers
 Class name
 Superclass (the name of a class’ parent, if available)
 Implemented Interfaces (if any)
 Appropriate Keywords depending on whether the class extends from a Superclass and/or
implements one or more interface
 Class body within curly brackets {}

Syntax to declare a class:

class <class_name>{

8 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

field;
method;
}
Import Statements
 An import statement tells Java which class you mean when you use a short name (like
List ). It tells Java where to find the definition of that class.
 In Java, the import statement is used to bring certain classes or the entire packages, into
visibility. As soon as imported, a class can be referred to directly by using only its name.
 The import statement is a convenience to the programmer and is not technically needed to
write complete Java program. If you are going to refer to some few dozen classes into your
application, the import statement will save a lot of time and typing also.
 In a Java source file, the import statements occur immediately following
the package statement (if exists) and before any class definitions.

Below is the general form of the import statement :

import pkg1[.pkg2].(classname|*);

example:
import java.lang.*;
Java API

An application programming interface (API), in the context of Java, is a collection of


prewritten packages, classes, and interfaces with their respective methods, fields and
constructors. Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.

In Java, most basic programming tasks are performed by the API’s classes and packages, which
are helpful in minimizing the number of lines written within pieces of code.

JDK

 The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment

9 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation


generator (javadoc) and other tools needed in Java development.

 People new to Java may be confused about whether to use the JRE or the JDK. To run
Java applications and applets, simply download the JRE. However, to develop Java
applications and applets as well as run them, the JDK is needed.

 Java developers are initially presented with two JDK tools, java and javac. Both are run
from the command prompt. Java source files are simple text files saved with an extension
of .java. After writing and saving Java source code, the javac compiler is invoked to
create .class files. Once the .class files are created, the 'java' command can be used to run
the java program.

 For developers who wish to work in an integrated development environment (IDE), a


JDK bundled with Netbeans can be downloaded from the Oracle website. Such IDEs
speed up the development process by introducing point-and-click and drag-and-drop
features for creating an application.

 There are different JDKs for various platforms. The supported platforms include
Windows, Linux and Solaris. Mac users need a different software development kit, which
includes adaptations of some tools found in the JDK.

Java Development Kit (JDK) is comprised of three basic components, as follows:

 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)

The Java API, included with the JDK, describes the function of each of its components.

In Java programming, many of these components are pre-created and commonly used. Thus, the
programmer is able to apply prewritten code via the Java API. After referring to the available
API classes and packages, the programmer easily invokes the necessary code classes and
packages for implementation.

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Variables

A variable is the name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before they can be used.
Declare variables
We can declare variables in java as follows:

Datatype - Type of data that can be stored in this variable.


variable_name - Name given to the variable.
value - It is the initial value stored in the variable.
Literals

Literals in java are a sequence of characters(digits, letters and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals.
They are

 Interger literals

 Floating point literals

 Character literals

 String literals

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

 Boolean literals

Data types

Data types represent the different values to be stored in the variable. In java, there are two
types of data types:

 Primitive data types


 Non-primitive data types

Primitive Data Types


There are eight primitive datatypes supported by Java. Primitive datatypes are predefined
by the language and named by a keyword.

byte

 Byte data type is an 8-bit signed two's complement integer

 Minimum value is -128 (-2^7)

 Maximum value is 127 (inclusive)(2^7 -1)

 Default value is 0
1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an integer.

 Example: byte a = 100, byte b = -50

short

 Short data type is a 16-bit signed two's complement integer

 Minimum value is -32,768 (-2^15)

 Maximum value is 32,767 (inclusive) (2^15 -1)

 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer

 Default value is 0.

 Example: short s = 10000, short r = -20000

int

 Int data type is a 32-bit signed two's complement integer.

 Minimum value is - 2,147,483,648 (-2^31)

 Maximum value is 2,147,483,647(inclusive) (2^31 -1)

 Integer is generally used as the default data type for integral values unless there is a
concern about memory.

 The default value is 0

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

long

 Long data type is a 64-bit signed two's complement integer

 Minimum value is -9,223,372,036,854,775,808(-2^63)

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)

 This type is used when a wider range than int is needed

 Default value is 0L

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

float

 Float data type is a single-precision 32-bit IEEE 754 floating point

 Float is mainly used to save memory in large arrays of floating point numbers

 Default value is 0.0f

 Float data type is never used for precise values such as currency

 Example: float f1 = 234.5f

double

 double data type is a double-precision 64-bit IEEE 754 floating point

 This data type is generally used as the default data type for decimal values, generally the
default choice

 Double data type should never be used for precise values such as currency

 Default value is 0.0d

Boolean

 boolean data type represents one bit of information

 There are only two possible values: true and false

 This data type is used for simple flags that track true/false conditions

 Default value is false

 Example: boolean one = true

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

char

 char data type is a single 16-bit Unicode character

 Minimum value is '\u0000' (or 0)

 Maximum value is '\uffff' (or 65,535 inclusive)

 Char data type is used to store any character

 Example: char letterA = 'A'

String class
 The java.lang.String class provides a lot of methods to work on string. By the help of
these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

 Java String is a powerful concept because everything is treated as a string if you submit
any form in window based, web based or mobile application.
Important methods of String class
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

Program:
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)

Output
SACHIN
sachin
Sachin

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Static Import Statements

Static import is a feature introduced in the Java programming language that allows
members (fields and methods) which have been scoped within their container class as public
static , to be used in Java code without specifying the class in which the field has been defined.

With the help of static import, we can access the static members of a class directly without
class name or any object.

For Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(),
but by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.

Java Program to illustrate


// calling of predefined methods
// with static import
import static java.lang.Math.*;
class Test2 {
public static void main(String[] args)
{
System.out.println(sqrt(4));
System.out.println(pow(2, 2));
System.out.println(abs(6.3));
}
}
Output:

2.0

4.0

6.3

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a class
without the class qualification.

The import provides accessibility to classes and interface whereas static import provides
accessibility to static members of the class.

Use Interfaces: Declaring an Interface- Declaring Interface Constants.

Interface in Java

 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Declaring An Interface

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the fields are
public, static and final by default.

A class that implements an interface must implement all the methods declared in the interface.

Syntax

interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.

1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

Java interface example:


interface printable{
void print();
}
class A6 implements printable
{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}

Output:
Hello

BCA
1
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Declaring Interface Constants

 It's possible to place widely used constants in an interface. If a class implements such an
interface, then the class can refer to those constants without a qualifying class name.

 Placing constants in an interface was a popular technique in the early days of Java, but now
many consider it a distasteful use of interfaces, since interfaces should deal with
the services provided by an object, not its data.
 As well, the constants used by a class are typically an implementation detail, but placing
them in an interface promotes them to the public API of the class.

Example:
public interface Constants
{

double PI = 3.14159;
double PLANCK_CONSTANT = 6.62606896e-34;
}
public class Calculations implements Constants
{

public double getReducedPlanckConstant()


{
return PLANCK_CONSTANT / (2 * PI);
}
}
Declare Class Members
The components of a class, such as its instance variables or methods are called the members of a
class or class members. A class member is declared with an access modifier to specify how it is
accessed by the other classes in Java. A Java class member can take any of the access modifiers,
such as - public, protected, default and private

19 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Acccess Modifiers

As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor, variable, method, or data member. There are four types of access modifiers
available in java:

1. Default – No keyword required


2. Private
3. Protected
4. Public

 Default: When no access modifier is specified for a class, method, or data member – It is
said to be having the default access modifier by default.
 The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
 Private: The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the
class in which they are declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any
subclasses”
 protected: The protected access modifier is specified using the keyword protected.
 The methods or data members declared as protected are accessible within the
same package or subclasses in different packages.
 public: The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access
modifiers.

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

 Classes, methods, or data members that are declared as public are accessible
from everywhere in the program. There is no restriction on the scope of public
data members.
Example:
public class Logger {
private String format;

public String getFormat() {


return this.format;
}

public void setFormat(String format) {


this.format = format;
}
}

Non Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionalities.

 The static modifier for creating class methods and variables.

 The final modifier for finalizing the implementations of classes, methods, and variables.

 The abstract modifier for creating abstract classes and methods.

The Static Modifier

Static Variables

The static keyword is used to create variables that will exist independently of any instances
created for the class. Only one copy of the static variable exists regardless of the number of
instances of the class.

Static Methods

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

The static keyword is used to create methods that will exist independently of any instances
created for the class.

Example

public class InstanceCounter

private static int numInstances = 0;

protected static int getCount() {

return numInstances;

private static void addInstance()

numInstances++;

} InstanceCounter() {

InstanceCounter.addInstance();

public static void main(String[] arguments) {

System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

for (int i = 0; i < 500; ++i) {

new InstanceCounter();

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

System.out.println("Created " + InstanceCounter.getCount() + " instances");

Output:

Started with 0 instances


Created 500 instances
The Final Modifier

Final Variables

A final variable can be explicitly initialized only once. A reference variable declared final can
never be reassigned to refer to an different object.

However, the data within the object can be changed. So, the state of the object can be changed
but not the reference.

The Final Modifier

Final Variables

A final variable can be explicitly initialized only once. A reference variable declared final can
never be reassigned to refer to an different object.

However, the data within the object can be changed. So, the state of the object can be changed
but not the reference.

The abstract Modifier

Abstract Class

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

An abstract class can never be instantiated. If a class is declared as abstract then the sole
purpose is for the class to be extended.

Abstract Methods

An abstract method is a method declared without any implementation. The methods body
(implementation) is provided by the subclass. Abstract methods can never be final or strict.

Any class that extends an abstract class must implement all the abstract methods of the super
class, unless the subclass is also an abstract class.

EXAMPLE

public abstract class SuperClass {

abstract void m(); // abstract method

}class SubClass extends SuperClass {

// implements the abstract method

void m() {

The Synchronized Modifier

The synchronized keyword used to indicate that a method can be accessed by only one thread at
a time. The synchronized modifier can be applied with any of the four access level modifiers.

Constructor Declarations - Variable Declarations

Constructors are used to initialize the object’s state. Like methods, a constructor also contains
a collection of statements(i.e. instructions) that are executed at the time of Object creation.

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes:

A constructor is invoked at the time of object or instance creation. For Example:

class Geek

.......

// A Constructor

new Geek() {}

.......

// We can create an object of the above class

// using the below statement. This statement

// calls above constructor.

Geek obj = new Geek();

Rules for writing Constructor:

 Constructor(s) of a class must have the same name as the class name in which it resides.
 A constructor in Java can not be abstract, final, static and Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Variable Declarations

A variable is a name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before use.
How to initialize variables?
It can be perceived with the help of 3 components that are as follows:

 datatype: Type of data that can be stored in this variable.


 variable_name: Name given to the variable.
 value: It is the initial value stored in the variable.

Now let us discuss different types of variables which are listed as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
Local Variable
A variable defined within a block or method or constructor is called a local variable.

 These variables are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access these variables only within that block.

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Instance Variable

Instance variables are non-static variables and are declared in a class outside any method,
constructor,or block.

 As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.

Static Variables
Static variables are also known as Class variables.

 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
Example:
float simpleInterest;

// Declaring float variable

int time = 10, speed = 20;

// Declaring and Initializing integer variable

char var = 'h';

Declare and Use enums

The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW,
BLUE, GREEN, WHITE, and BLACK) etc.

According to the Java naming conventions, we should have all constants in capital letters. So, we
have enum constants in capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a variable that does
not change). The Java enum constants are static and final implicitly. It is available since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.

To create an enum, use the enum keyword (instead of class or interface), and separate the constants
with a comma. Note that they should be in uppercase letters:
Declaring Enums:
Syntax
enum Level {
LOW,
MEDIUM,
HIGH
}
Enum inside a Class
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}

public static void main(String[] args) {


Level myVar = Level.MEDIUM;

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

System.out.println(myVar);
}
}

Features Of Enum
o Enum improves type safety
o Enum can be easily used in switch
o Enum can be traversed
o Enum can have fields, constructors and methods

Example:

class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL

Object Orientation: Encapsulation

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:

2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.

To achieve encapsulation in Java −

 Declare the variables of a class as private.

 Provide public setter and getter methods to modify and view the variables values.

Example:

/* File name : EncapTest.java */

public class EncapTest {

private String name;

private String idNum;

private int age;

public int getAge() {

3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

return age;

public String getName() {

return name;

public String getIdNum() {

return idNum;

public void setAge( int newAge) {

age = newAge;

public void setName(String newName) {

name = newName;

public void setIdNum( String newId)

{ idNum = newId;

3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Benefits of Encapsulation

 The fields of a class can be made read-only or write-only.

 A class can have total control over what is stored in its fields.

Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

Example

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

Output:

running safely with 60 km

Overridding and Overloading Methods.

Overridding Methods Usage of

Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which is


already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method are the same, and
there is IS-A relationship between the classes, so there is method overriding.

/Java Program to illustrate the use of Java Method Overriding

3
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

//Creating a parent class.


class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.

3
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

Overloaded Methods

When more than one method of the same name is created in a Class, this type of method is
called Overloaded Method. If it is possible that a programmer has to take only one name and the
program itself decides which method to use for which type of value, then it will be easier for the
programmer to get the same.

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

3
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

3
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

2.1 Object Orientation

.1 Casting

Assigning one data type to another or one object to another is known as casting. Java supports
two types of casting – data type casting and object casting.

Conditions For Casting

1. Same class objects can be assigned one to another.


2. Subclass object can be assigned to a super class object and this casting is done implicitly. This is
known as Upcasting (upwards in the hierarchy from subclass to super class).
3. Java does not permit to assign a super class object to a subclass object (implicitly) and still to do
so, we need explicit casting. This is known as downcasting (super class to
subclass). Downcasting requires explicit conversion.

Example:

class Flower
{
public void smell()
{
System.out.println("All flowers give smell, if you can smell");
}
}
public class Rose extends Flower
{
public void smell()
{
System.out.println("Rose gives rosy smell");
}
public static void main(String args[])
{

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Flower f = new
Flower(); Rose r = new
Rose(); f.smell();
r.smell();
f = r; // subclass to super class, it is
valid f.smell();
// r = f; // super class to subclass, not
valid r = (Rose) f; // explicit casting
f.smell();
}
}

Output:
All flowers give smell, if you can
smell Rose gives rosy smell
Rose gives rosy
smell Rose gives
rosy smell

2.1.2 Implementing an Interface

 To declare a class that implements an interface, you include an implements clause in the
class declaration.
 Your class can implement more than one interface, so the implements keyword is followed by a
comma-separated list of the interfaces implemented by the class.

By convention, the implements clause follows the extends clause, if there is one.

Declare An Interface?

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public, static

2 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

and final by default. A class that implements an interface must implement all the methods declared in
the interface.

Syntax:
interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}

A Sample Interface, Relatable

Consider an interface that defines how to compare the size of

objects. public interface Relatable {

// this (object calling isLargerThan)


// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other
public int isLargerThan(Relatable other);
}

In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.

3 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Interface: Example

In this example, the Printable interface has only one method, and its implementation is provided in
the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){

4 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

A6 obj = new
A6(); obj.print();
}
}
Output:

Hello

Legal Return Types: Return Type Declarations - Returning a Value

Legal Return Types

A return statement causes the program control to transfer back to the caller of a method.
Every method in Java is declared with a return type and it is mandatory for all java methods.

A return type may be a primitive type like int, float, double, a reference type or void
type(returns nothing).

There are a few important things to understand about returning the values

 The type of data returned by a method must be compatible with the return type specified
by the method. For instance, if the return type of some method is boolean, we can not return
an integer.

 The variable receiving the value returned by a method must also be compatible with the
return type specified for the method.

 The parameters can be passed in a sequence and they must be accepted by the method in the
same sequence.

Example:

public class ReturnTypeTest1 {

public int add() { // without

arguments int x = 30;

5 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

int y = 70;

int z =

x+y; return

z;

public static void main(String args[]) {

ReturnTypeTest1 test = new

ReturnTypeTest1(); int add = test.add();

System.out.println("The sum of x and y is: " + add);

Output:

The sum of x and y is: 100

Return Type Declarations

 A method is a function declared inside a class that contains a group of statements.

 It is used to perform certain tasks or processing of data in the program to yield the
expected results.

 A method can accept data from outside and can also return the results. To return the result,
a return statement is used inside a method to come out of it to the calling method.

 Return type may be a primitive data type like int, float, double, a reference type, or void
type which represents “return nothing”. i.e, they don’t give anything back.

 When a method is called, the method may return a value to the caller method.

6 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Example :

Here, we will write a program to return the square of a number from a method. Look at the following
source code.

public class Test

int square(int num){

return num * num; // return a square value.

public static void main(String[] args)

// Create an obejct of class

Test. Test t = new Test();

int squareOfNumber = t.square(20);

// Displaying the result.

System.out.println("Square of 20: " +squareOfNumber);

Output:

Square of 20: 400

7 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Returning A Value

return is a reserved keyword in Java i.e, we can’t use it as an identifier. It is used to exit from a
method, with or without a value.

return can be used with methods in two ways:

1. Methods returning a value : For methods that define a return type, return statement must
be immediately followed by return value.

Example:
Java program to illustrate usage of return keyword

class A {

// Since return type of RR method is double


// so this method should return double
value double RR(double a, double b)
{
double sum = 0;
sum = (a + b) / 2.0;
// return statement
below: return sum;
}
public static void main(String[] args)
{
System.out.println(new A().RR(5.5, 6.5));
}
}
Output
:
6.0

8 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Constructors and Instantiation

 Instantiation is an immense word to define a universal and straightforward concept in


Java programming, creating new instances of objects.

 In other words, creating an object of the class is called instantiation.

 It occupies the initial memory for the object and returns a reference. An object instantiation
in Java provides the blueprint for the class.

Syntax for Instantiation


ClassName objName = new

ClassName(); Creating Instances

There are two ways to create instances:

o Using the new Keyword


o Using Static Factory Method

Overloaded Constructors

 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.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id; String name;
int age;
//creating two arg
constructor Student5(int
i,String n){
id = i;

9 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:

FDDFAryan 25
111 Karan 0

222 Aryan 25

Initialization Blocks

The initialization of the instance variable can be done directly but there can be performed
extra operations while initializing the instance variable in the instance initializer block.

Why use instance initializer block?

Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill
complex array or error handling etc.

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Example:

lass Bike7{
int speed;
Bike7(){System.out.println("speed is "+speed);}
{speed=100;}

public static void main(String args[])


{ Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
OUTPUT:
SPEED IS100
SPEED IS 100

Statics: Static Variables and Methods

 The static keyword in Java is used for memory management mainly.


 We can apply static keyword with variables, methods, blocks and nested classes.
 The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

STATIC VARIABLE

If you declare any variable as static, it is known as a static variable.

o 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.

o The static variable gets memory only once in the class area at the time of class loading.

EXAMPLE

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance
variable String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{ rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

s2.display();
}
}

OUTPUT

111 KARAN ITS

222 ARYAN ITS

Java static method

If you apply static keyword with any method, it is known as static method.

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

//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x)
{ return x*x*x;
}

public static void main(String args[])


{ int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:

125

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Assignments: Stack and Heap

In Java, memory management is a vital process. It is managed by Java automatically. The


JVM divides the memory into two parts: stack memory and heap memory.

From the perspective of Java, both are important memory areas but both are used for different
purposes.

The major difference between Stack memory and heap memory is that the stack is used to store
the order of method execution and local variables while the heap memory stores the objects and it
uses dynamic memory allocation and deallocation.

Stack Memory

The stack memory is a physical space (in RAM) allocated to each thread at run time. It is
created when a thread creates. Memory management in the stack follows LIFO (Last-In-First-Out)
order because it is accessible globally. It stores the variables, references to objects, and partial results.
Memory allocated to stack lives until the function returns.

Heap Memory

It is created when the JVM starts up and used by the application as long as the application
runs. It stores objects and JRE classes. Whenever we create objects it occupies space in the heap
memory while the reference of that object creates in the stack.

It does not follow any order like the stack. It dynamically handles the memory blocks. It
means, we need not to handle the memory manually.

For managing the memory automatically, Java provides the garbage collector that deletes the
objects which are no longer being used.

Difference Between Stack and Heap Memory

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

The following table summarizes all the major differences between stack memory and heap space.

Literals

1. Boolean Literals. In Java, boolean literals are used to initialize boolean data types.
2. Integer Literals. An integer literal is a numeric value(associated with numbers) without any
fractional or exponential part. ...
3. Floating-point Literals.
4. Character Literals.
5. String literals.
Literals, Assignments, and Variables

There are 4 types of variables in Java programming language:

 Instanceare
Literals Variables
data used(Non-Static Fields)fixed values. They can be used directly in the code.
for representing

 Class Variables (Static Fields)


Types of Literals:
 Local Variables
Boolean Literals. In Java, boolean literals are used to initialize boolean data types.
6.
 Parameters
7. Integer Literals. An integer literal is a numeric value(associated with numbers) without any

fractional or exponential part. ...


8. Floating-point Literals.
9. Character Literals.
10. String literals.
1. Boolean
Literals

1
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

In Java, boolean literals are used to initialize boolean data types. They can store two values: true and
false.

For example

boolean flag1 = false;

boolean flag2 = true;

Here false and true are Boolean literals

2. Integer Literals

An integer literal is a numeric value(associated with numbers) without any fractional or exponential
part. There are 4 types of integer literals in Java:

1. binary (base 2)
2. decimal (base 10)
3. octal (base 8)
4. hexadecimal (base 16)

3. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponential form.

4. Character Literals

Character literals are unicode character enclosed inside single quotes.

5. String literals

A string literal is a sequence of characters enclosed inside double-quotes. For

example, String str1 = "Java Programming";

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

String str2 = "Programiz";

Here, Java Programming and Programiz are two string literals.

Variables

2.6.1 Literal Values for All Primitive Types

A literal is a specific value stored in the computer in a specific format. We can store numbers, text,
specific characters, a list of values like a shopping list, and many other things. Each one has its own
format and size. Depending on the literal there is a set of operations we can perform on it.

Primitive Values

Primitive types should be written in lowercase (Your first grammar rule). And they are, byte, char,
boolean, short, int, long, double, and float.

Integer Primitive Types

The following types were designed to work with numbers. Though exist a little exception with char,
it stores numbers but those numbers are used to represent symbols, letters, and digits to be displayed
as a text on your screen.

byte:

 It uses 8 bits (1 byte).

 It is used to represent numbers in the range [-128, +127].

 It is pretty fast to processed addition, subtraction, etc.

charIt uses 16 bits (12 bytes).

 It is used to represent numbers in the range [0, 65535].

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

 It is used to represent Unicode Characters

 A Unicode character is a number that represents a symbol, letter or digit

 It can be used as a number but was created to be a character and display the corresponding
symbol on the screen.

short:It uses 16 bits (2 bytes).

 It is used to represent numbers in the range [-32 768, +32 767].

 This is converted to a character easily whenever you want it.

 It is pretty fast to processed addition, subtraction, etc.

intIt uses 32 bits (4 bytes).

 It is used to represent numbers in the range [-2,147,483,648, +2,147,483,6487].

 This is one of the common primitive types to represent numbers.

longIt uses 64 bits (8 bytes).

 It is used to represent a huge range of numbers the range is

[-9,223,372,036,854,775,808, +9,223,372,036,854,775,807].

 You should use this type carefully. It can slow down your computer.

Decimal Primitive Types

Float and double were created to work with decimal numbers. In programming, they are known
as floating-point numbers.

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

double

 It uses 32 bits (4 bytes)

 It is used to represent decimal numbers and perform operations like division, the square root of
a number.

float

 It uses 64 bits (8 bytes)

 It is used to represent decimal numbers and perform operations like division, the square root of
a number.

Two special primitive

type boolean

 It uses 8 bits (1 byte).

 It was created to answer yes-no questions.

 Though it has 8 bits, it only stores 2 values, true or false.

 Internally 00000000 is the same as false.

 Internally 11111111 is the same as true.

void

 It is a type to express that there is no value to store at all.

 We cannot use it in our variable definitions.

1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Scope - Variable Initialization

Scope is that area of the program where the variable is visible to a program and can be used
(accessible). i.e. the scope of variable determines its accessibility for other parts of program.

Java allows declaring variables within any block. A block defines a scope that starts with an opening
curly brace and ends with a closing curly brace.

There are three types of variables in java, depending on their scope:


 local variables
 instance variables
 class variables (static variables).

Scope of Local Variables in Java

1. When the local variable is created inside a method, constructor, or block, their scope only
remains within the method, block, or constructor.

Scope of Instance variables in Java

The scope of instance variables is inside the class. They are visible inside all the
methods, constructors, and from the beginning of its program block to the end of program block in
the class.

Syntax

ObjectReference.VariableName;

Scope of Static variables

The scope of a static variable is within the class. All the methods, constructors, and blocks
inside the class can access static variables by using the class name. It has the following general form:
Syntax:

ClassName.VariableName;

Example program:

package staticVariable;

2
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

public class StaticTest

// Declaration of static

variable. static int a = 20;

void m1()

int a = 30;

System.out.println("a: "

+a);

System.out.println("a: " +StaticTest.a); // Accessing static variable using class name within
instance method.

public static void main(String[] args)

StaticTest st = new

StaticTest(); st.m1();

Output:

a:3

a:2

2
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Passing Variables into Methods

 Information can be passed to methods as parameter. Parameters act as variables inside the
method.
 Parameters are specified after the method name, inside the parentheses.
 You can add as many parameters as you want, just separate them with a comma.
 The following example has a method that takes a String called fname as parameter.
 When the method is called, we pass along a first name, which is used inside the method to
print the full name:

EXAMPLE:

public class Main

static void myMethod(String fname) {

System.out.println(fname + "

Refsnes");

public static void main(String[] args)

myMethod("Liam");

myMethod("Jenny")

myMethod("Anja");

When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Passing Object Reference Variables

All object references in Java are passed by value. This means that a copy of the value will be
passed to a method.

But the trick is that passing a copy of the value also changes the real value of the

object. To understand why, start with this example:

public class ObjectReferenceExample {

public static void main(String... doYourBest)

{ Simpson simpson = new Simpson();

transformIntoHomer(simpson);

System.out.println(simpson.name);

static void transformIntoHomer(Simpson simpson)

{ simpson.name = "Homer";

class Simpson {

String name;

2 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Passing Primitive Variables.

Like object types, primitive types are also passed 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 PrimitiveByValueExample {

public static void main(String... primitiveByValue) {

int homerAge = 30;

changeHomerAge(homerAge);

System.out.println(homerAge);

static void changeHomerAge(int homerAge)

{ homerAge = 35;

Garbage collection

 Java garbage collection is the process by which Java programs perform automatic memory
management.
 Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short.
 When Java programs run on the JVM, objects are created on the heap, which is a portion
of memory dedicated to the program.

2 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

 Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.

o It is automatically done by the garbage collector(a part of JVM) so we don't need to


make extra efforts.

Example for 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(){}

Simple Example of garbage collection in


java public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){

2 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

TestGarbage1 s1=new
TestGarbage1(); TestGarbage1
s2=new TestGarbage1(); s1=null;
s2=null;
System.gc()
;
}
}
Output:

Object is garbage

collected Object is

garbage collected

Operators: Java Operators

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

2
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Assignment Operators

The Assignment Operators


Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign value


=
right side operands to left side operand. of A + B into C

Add AND assignment operator. It adds right


C += A is equivalent to C =
+= operand to the left operand and assign the result
C+A
to left operand.

Subtract AND assignment operator. It subtracts


C -= A is equivalent to C = C
-= right operand from the left operand and assign the
–A
result to left operand.

Multiply AND assignment operator. It multiplies


C *= A is equivalent to C =
*= right operand with the left operand and assign the
C*A
result to left operand.

/= Divide AND assignment operator. It divides left


C /= A is equivalent to C = C
operand with the right operand and assign the
/A
result to left operand.

BCA
2
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Relational Operators

The Relational Operators


There are following relational operators supported by Java

language. Assume variable A holds 10 and variable B holds 20,

then −

Show Examples

Operator Description Example

Checks if the values of two operands are equal or


== (equal to) (A == B) is not true.
not, if yes then condition becomes true.

Checks if the values of two operands are equal or


!= (not equal to) not, if values are not equal then condition becomes (A != B) is true.
true.

Checks if the value of left operand is greater than


> (greater than) the value of right operand, if yes then condition (A > B) is not true.
becomes true.

Checks if the value of left operand is less than the


< (less than) value of right operand, if yes then condition (A < B) is true.
becomes true.

BCA
2
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Arithmetic Operators

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then

− Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

Subtracts right-hand operand from left-hand


- (Subtraction) A - B will give -10
operand.

Multiplies values on either side of the


* (Multiplication) A * B will give 200
operator.

Divides left-hand operand by right-hand


/ (Division) B / A will give 2
operand.

Divides left-hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

BCA
2
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

Conditional Operators

The conditional operator is also known as a ternary operator. The conditional statements are
the decision-making statements which depends upon the output of the expression. It is represented by
two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is
also a decision-making statement.

Syntax of a conditional operator


Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below,

Example

#include <stdio.h>
int main()
{
int age; // variable
declaration printf("Enter your
age");
scanf("%d",&age); // taking user input for age variable

3 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII

(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operato
r
return 0;
}

Logical
Operators. The
Logical
Operators
The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds

false, then − Show Examples

Operator Description Example

Called Logical AND operator. If both the operands are (A && B) is


&& (logical and)
non-zero, then the condition becomes true. false

Called Logical OR Operator. If any of the two operands


|| (logical or) (A || B) is true
are non-zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the logical


!(A && B) is
! (logical not) state of its operand. If a condition is true then Logical
true
NOT operator will make false.

3 BCA

You might also like