Unit 2-Java
Unit 2-Java
Class Naming: Class names should be nouns and start with a capital letter (e.g., MyClass).
Method Naming: Method names should be verbs and start with a lowercase letter, if multiple
words are used to form the name of the method, then each iiner word’s first letter should be
upper case/(e.g., calculateArea()).
Program File Name: Name of The program file shold exactly match the class name, if multiple
class available in single file, File name should match with the class name including main
method.
Java Identfiers
In Java, an identifier is a name given to a variable, method, class, package, or other user-defined
item.
basic rules for Java identifiers:
✓ Must begin with a letter, underscore (_), or dollar sign ($). It cannot begin with a digit.
✓ Subsequent characters can be letters, digits, underscores, or dollar signs. No other
characters are allowed.
✓ Java identifiers are case-sensitive. For example, myVariable and MyVariable are treated
as different identifiers.
✓ Cannot be a reserved keyword. Java has reserved keywords that have specific meanings
in the language and cannot be used as identifiers. Examples of keywords include class,
int, public, static, etc.
✓ No length limit. Java identifiers can be of any length.
Java modifiers
In Java, modifiers are keywords that define the access level, behavior, and properties of classes,
methods, variables, and other program elements.
Access Modifiers:
protected: The element is accessible within its own package and by subclasses.
Non-Access Modifiers:
static: The element belongs to the class rather than instances of the class.
final: The element's value cannot be changed. For variables, it indicates a constant value. For
methods, it indicates the method cannot be overridden. For classes, it indicates the class cannot
be subclassed.
abstract: The element does not have an implementation. For methods, it indicates the method
must be implemented by a subclass. For classes, it indicates the class cannot be instantiated
directly and must be subclassed.
synchronized: The element is thread-safe and can only be accessed by one thread at a time.
volatile: The variable may be modified asynchronously (by different threads), and its value
should never be cached.
Java Comments
In Java, comments are used to provide information about the code to developers or to
temporarily disable certain parts of the code.
Java supports three types of comments:
Single-Line Comments: Single-line comments begin with // and continue until the end of the
line. They are commonly used for short descriptions or annotations.
Multi-Line Comments: Multi-line comments begin with /* and end with */. They can span
multiple lines and are typically used for longer descriptions or for temporarily disabling blocks
of code.
Javadoc Comments: Javadoc comments are a special type of comment used to generate
documentation for classes, interfaces, methods, and fields. They begin with /** and end with
*/. Javadoc comments support special tags such as @param, @return, @throws, etc., which are
used to provide additional information about the code that can be processed by documentation
generation tools.
Java keywords
In Java, keywords are reserved words that have predefined meanings and cannot be used for
naming variables, classes, methods, or any other identifiers. These keywords serve various
purposes in Java, such as defining classes, control flow, data types, and access modifiers.
Type Safety:
Java ensures type safety by disallowing operations that would result in incompatible types or
potential data loss.
Class in Java
In Java, a class is a blueprint or template for creating objects.It is a user defined data type.
It defines the properties (attributes) and behaviors (methods) that objects of that class will
have.
When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data.
class ClassName {
// Fields (attributes)
dataType fieldName1;
dataType fieldName2;
// ...
// Methods
returnType methodName1(parameters) {
// Method body
}
returnType methodName2(parameters) {
// Method body
}
// ...
}
Fields (Attributes): Inside the class body, you can declare fields to represent the attributes of
objects of this class. Each field declaration includes the data type of the field followed by the
field name.
instance variable
Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the data
for one object is separate and unique from the data for another.
Methods: Inside the class body, you can define methods to define the behavior of objects of
this class. Each method declaration includes the return type (or void if the method does not
return anything), method name, and parameter list. Method bodies contain the executable code
for performing specific actions.
return type specifies the type of data returned by the method. This can be any valid type,
including class types that you create. If the method does not return a value, its return type
must be void.
The name of the method is specified by name. This can be any legal identifier other than those
already used by other items within the current scope.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters
are essentially variables that receive the value of the arguments passed to the method when it
is called. If the method has no parameters, then the parameter list will be empty.
The data/fields, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
class Box
{
//instance variable
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box();
// assign values to mybox1's instance variables
b1.width = 10;
b1.height = 20;
b1.depth = 15;
The first line declares b1 as a reference to an object of type Box. After this line executes,
b1 contains the value null, which indicates that it does not yet point to an actual object.
The next line allocates an actual object and assigns a reference to it to b1. After the second line
executes, you can use b1 as if it were a Box object. But in reality, b1 simply holds the memory
address of the actual Box object.
Box b1;
b1
b1 = new Box();
b1
The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1. Thus, any changes
made to the object through b2 will affect the object to which b1 is referring, since they are the
same object.
When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference.
Constructor in java
In Java, a constructor is a special type of method that is used to initialize objects of a class.
It has the same name as the class in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the object is created,
before the new operator completes.
Constructors have the same name as the class and do not have a return type, not even void.
Constructors are primarily used to initialize instance variables or perform any necessary setup
operations.
class Box
{
double width;
double height;
double depth;
Constructor overloading
Constructor overloading in Java allows a class to have multiple constructors with different
parameter lists. Each constructor can initialize the object in a different way based on the
parameters provided. This provides flexibility when creating objects of the class, as different
constructors can be used depending on the specific requirements.
Constructor overloading is useful when you want to provide multiple ways to initialize objects
of a class, based on different combinations of parameters.
class MyClass
{
private int value;
}
}
}
}