Java New Syllabus
Java New Syllabus
The scope of local variables will be only within the given method or class.
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.
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.
Local Variables:
The scope of local variables will be only within the given method or class.
Access modifiers cannot be applied to local variables. A local variable declaration will be as
shown below:
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.
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.
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:
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.
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 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:
4 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
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 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.
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.
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.*;
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
*/
7 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
For example:
package java.awt;
Define Classes
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 {}
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.
import pkg1[.pkg2].(classname|*);
example:
import java.lang.*;
Java API
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
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.
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 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.
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
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:
byte
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.
short
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.
int
Integer is generally used as the default data type for integral values unless there is a
concern about memory.
long
1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
Default value is 0L
float
Float is mainly used to save memory in large arrays of floating point numbers
Float data type is never used for precise values such as currency
double
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
Boolean
This data type is used for simple flags that track true/false conditions
1 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
char
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 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.
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.
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
A class that implements an interface must implement all the methods declared in the interface.
Syntax
interface <interface_name>
{
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.
Output:
Hello
BCA
1
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
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
{
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:
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;
The final modifier for finalizing the implementations of classes, methods, and variables.
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
return numInstances;
numInstances++;
} InstanceCounter() {
InstanceCounter.addInstance();
new InstanceCounter();
2 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
Output:
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.
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.
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
void m() {
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.
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:
class Geek
.......
// A Constructor
new Geek() {}
.......
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.
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;
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
}
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 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.
Provide public setter and getter methods to modify and view the variables values.
Example:
3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
return age;
return name;
return idNum;
age = newAge;
name = newName;
{ idNum = newId;
3 BCA
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
Benefits of Encapsulation
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 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.
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.
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
Output:
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.
3
CCA31/CCS 31-PROGRAMMING IN JAVA UNITI
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.
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));
}}
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
.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.
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
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>
{
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
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");}
4 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
A6 obj = new
A6(); obj.print();
}
}
Output:
Hello
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:
5 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
int y = 70;
int z =
x+y; return
z;
Output:
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.
Output:
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.
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 {
8 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
It occupies the initial memory for the object and returns a reference. An object instantiation
in Java provides the blueprint for the class.
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.
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.
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;}
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
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
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
s2.display();
}
}
OUTPUT
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;
}
125
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
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.
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
Instanceare
Literals Variables
data used(Non-Static Fields)fixed values. They can be used directly in the code.
for representing
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
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
4. Character Literals
5. String literals
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
Variables
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.
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:
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
It can be used as a number but was created to be a character and display the corresponding
symbol on the screen.
[-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.
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 is used to represent decimal numbers and perform operations like division, the square root of
a number.
float
It is used to represent decimal numbers and perform operations like division, the square root of
a number.
type boolean
void
1 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
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.
1. When the local variable is created inside a method, constructor, or block, their scope only
remains within the method, block, or constructor.
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;
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
// Declaration of static
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.
StaticTest st = new
StaticTest(); st.m1();
Output:
a:3
a:2
2
BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
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:
System.out.println(fname + "
Refsnes");
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
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
transformIntoHomer(simpson);
System.out.println(simpson.name);
{ simpson.name = "Homer";
class Simpson {
String name;
2 BCA
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
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.
changeHomerAge(homerAge);
System.out.println(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.
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:
Gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup
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
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
Show Examples
BCA
2
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
Relational Operators
then −
Show Examples
BCA
2
CCA31/CCS31-PROGRAMMING IN JAVA UNITII
Arithmetic Operators
− Show Examples
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.
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 −
3 BCA