java(class2)
java(class2)
If no access specifier is given for the member then java takes default as
default access specifier for that member. The default members can be
accessed inside and outside the class but in the same package.
The members declared with the access specifier public are said to be
public members and such members can be accessed in the same and
other classes regardless of their package as well as all its subclasses.
Example:
class A
{
public int x;
public void sum( )
{..
}
The members declared with the access specifier protected are said to
be protected members and such members can be accessed in the same
class and in any other classes of same package and its subclasses of
other packages. Protected members can be defined with the keyword
protected.
Example:
class A
protected int x;
protected void sum( )
{
Access Specifier : private
The members declared with the access specifer private are said
Example:
class A
{
private int x;
private void sum( )
Objects:
A class specification only declares the structure of objects and it must be
instantiated in order to make use of the services provided by it.
This process of creation of objects (variables) of the class is called class
instantiation. It is the definition of an object that actually creates objects in the
program by setting aside memory space for its storage. Hence, a class is like a
blueprint of an object and it indicates how the instance variables and methods are
used when the class is instantiated. The necessary resources are allocated only
when a class is instantiated.
Creation of classes is nothing but creation of userdefined datatype.
We can use this new datatype (class) to create variables of the class type.
However, creating objects of a class is a two-step process.
First, we must declare a reference variable of the class.
This reference variable does not define an object, instead it creates a variable that
stores reference(address) of an object.
Syntax:
classname obj;
Here obj is a reference variable of classname that can store
reference(address) of object of classname.
Second, we must create an actual physical copy of the object and assign it to the
reference variable. This can be done using the new operator.
Syntax:
obj=new classname;
The new operator allocates memory of classnamel) dynamically (at run-time)
which is said to be an object and whose address is assigned to reference variable
obj.
We can also create objects in single statement using the following
syntax:
classname obj=new classname();
In java objects are instantiated at runtime using new operator.
Accessing Class members:
Once an object of a class has been created, there must be a provision to access its
members. This can be achieved by using the member access operator • (dot).
1) Syntax for accessing instance variable of a class
Objectname.instancevariable;
1) Syntax for accessing methods of a class
Objectname.methodname([Arguments list...]);
Example:
class Sample{
private int x=10;
public int y=20;
protected int z=30;
int p=40;
}
class Sam{
public static void main(String[] args){
sample obj=new sample();
//System.out.print("\n obj.x=" +obj.x)//error
System.out.println("obj.y="+obj.y);
System.out.println("obj.z="+obj.z);
System.out.println("obj.p="+obj.p);
}
}
Output:
obj.y=20
obj.z=30
obj.p=40
Explanation:
In the main() the statement sample obj=new sample(); the new allocates memory
of sample() which is the actual object and whose address 1001 is assigned to obj .
The private variable x is not accessed outside the class therefore it is commented,
otherwise it is an error. Where as public, protected and default variables y, z and
p can be accessed outside the class using objectname as a result we got the
output as shown in above output.
The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
name of students etc.
The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
static method can access static data member and can change the value
of it.
Example of static method:
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n)
{ rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display(); s2.display(); s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
The public static methods of a class can be accessed outside the class
using class name without using object name. The public access specifier
specifies that the method can be accessed outside the class. The static
modifier specifies that the method can be accessed using classname.
Example program
Bin>edit static1 java
class A{
public static void show(Strings args[]){
System.out.print("\n show of A...");
}
}
class static1
{
public static void main(String[] args){
A.show();
}
}
java command as
The JVM takes the static class name and using this class name it calls
the main() method as static1.main(). Like this main() method is called
from out side the class using class name therefore main() method
should be declared as public and static.
Command-Line Arguments:
argv is an array of String that can store any number of values passed
from command-line
Example Program:
monitor.
Java Methods:
A method in Java is a block of code within a class that performs a
specific task.
A method is a block of code which only runs when it is called
You can pass data, known as parameters, into a method.
Why use methods? To reuse code: define the code once, and use it
many times.
Create a Method
Call a Method:
Multiple Parameters:
// Liam is 5
// Jenny is 8
// Anja is 31
Method Overloading:
Method overloading in Java is a feature that allows a class to have multiple methods with the
same name but different parameter lists. This is a form of compile-time polymorphism, where
the correct method to be executed is determined during compilation based on the method
signature.
Key characteristics of method overloading:
Same Method Name: All overloaded methods within a class share the same name.
Different Parameter Lists: The parameter lists must differ in at least one of the following ways:
o Number of parameters: The methods have a different count of parameters.
o Data type of parameters: The methods have parameters of different data types.
Example:
class Calculator {
// Overloaded method to add two integers
public int add(int a, int b) {
return a + b;
}
Bin>edit accounts.java
class bank
private String name; private int accno;
public void setbank (String name, int accno)
name = name;
accno=accno;
}
public void show( )
System. out, print ("Inname="+name+"\nacno="+accno) ;
class accounts{
public static void main (String agrv[])
bank obj-new bank ( );
obj setbank ("kumar", 105);
System. out print ("\nBank Account...");
obj. show( );
}
}
Bin> javac accounts.java
Bin> java accounts
Bank Account...
name=null
accno=0
Explanation:
Recursion:
Recursion in Java is a programming technique where a method calls itself to solve a
problem. This approach is typically used when a problem can be broken down into smaller,
similar subproblems.
public class Factorial {
public static int calculateFactorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive step: n * factorial of (n-1)
return n * calculateFactorial(n - 1);
}
}
Java Arrays:
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To
insert values to it, you can place the values in a comma-separated list,
inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
1. No wastage of memory:
collector.
Java Comments :
The java comments are statements that are not executed by the
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or any
statement. It can also be used to hide program code for specific time.
Syntax:
1. //This is single line comment
Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output: 10
Syntax:
/* This is multi line comment */
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:10
There are two types of data types in java: primitive and non-primitive.
Types of Variable
There are three types of variables in java:
o local variable
o instance variable
o static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is
called instance variable . It is not declared as static.
3) Static variable
The scope of a variable defines the section of the code in which the
variable is visible. As a general rule, variables that are defined within a
block are not accessible outside that block. The lifetime of a variable
refers to how long the variable exists before it is destroyed. Destroying
variables refers to deallocating the memory that was allotted to the
variables when declaring it. We have written a few classes till now. You
might have observed that not all variables are the same. The ones
declared in the body of a method were different from those that were
declared in the class itself. There are three types of variables: instance
variables, formal parameters and local variables.
Instance variables :
Instance variables are those that are defined within a class itself and
not in any method or constructor of the class. They are known as
instance variables because every instance of the class (object) contains
a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have
already seen about it earlier. The lifetime of these variables is the same
as the lifetime of the object to which it belongs. Object once created do
not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about
Java's automatic garbage collector later on.
Argument variables :
These are the variables that are defined in the header oaf constructor
or a method. The scope of these variables is the method or constructor
in which they are defined. The lifetime is limited to the time for which
the method keeps executing. Once the method finishes execution,
these variables are destroyed.
Local variables :
Example
Create a variable of type String and assign it a value:
String greeting = "Hello";
Data Types:
Type Conversion or Type Casting
Conversion from one data type value to another data type value is
known as type conversion or type casting. Java supports type
conversion in two ways.
1. Implicit Conversion
2. Explicit Conversion
Implicit Conversion
Converting from one datatype value to another datatype value
internally by the java language is known as implicit conversion. Java
automatically converts one type value to another provided the
following two conditions are satisfied.
(i.e. the data types of variables should belong to same data type
category.)
2. The destination variable data type size is larger than source variable
data type.
Example:
2.
int x; short y=20; x=y;
/ / Correct: because & occupies 4 bytes and y occupies 1/2 bytes and both are type compatible.
int x=30; short y;
y=X;
/ / Error: because size of y is 2 bytes and a size is 4 / / bytes. Therefore
destination variable(y) size is
int a=3000;
float f;
// category.
Operators in java
Operator in java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in java which are given below:
Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Expressions:
Expressions are essential building blocks of any Java program, usually created to
produce a new value, although sometimes an expression simply assigns a value to
a variable. Expressions are built using values, variables, operators and method
calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are
three types of
expressions in Java:
Those that produce a value, i.e. the result of (1 + 1)
Those that assign a variable, for example (v = 10)
Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators
that modify the state (i.e. memory) of a program.
Control Statements:
Inheritance in Java:
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones. A
class that inherits from another class can reuse the methods and fields of that class.
Example:
class A{
class B extends A{
polymorphism:
Method Overriding:
Method overriding in Java is a feature of object-oriented programming that allows a subclass to
provide a specific implementation for a method that is already defined in its superclass. This is a
core concept of polymorphism, specifically runtime polymorphism, where the method to be
executed is determined at runtime based on the actual object type.
Key characteristics and rules of method overriding:
Inheritance:
Method overriding can only occur between a superclass and its subclass, establishing an "IS-A"
relationship.
Same Signature:
The overriding method in the subclass must have the exact same name, return type (or a
covariant return type, which is a subtype of the superclass method's return type), and
parameters as the method in the superclass.
Access Modifiers:
The access modifier of the overriding method in the subclass must be the same or more
permissive than the overridden method in the superclass (e.g., if the superclass method
is protected, the subclass method can be protected or public, but not private).
No Overriding of private or final methods:
private methods are not inherited and thus cannot be overridden. final methods cannot be
overridden because their implementation is fixed.
static methods:
static methods cannot be overridden; if a subclass defines a static method with the same
signature as a static method in the superclass, it is considered method hiding, not overriding.
Example:
class A{
}
}
class B extends A{
B obj=new B();
obj.sum();
obj.sub();
obj.mul();
obj.div();
}
}
output:
the sum is method of class A
the sub is a method of class A but overriding in class B
the mul is method of class A
the div is method of class B
Encapsulation:
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Example explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this
class:
If the variable was declared as public, we would expect the following output:
However, as we try to access a private variable, we get an error:
Instead, we use the getName() and setName() methods to access and update the variable:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John"
Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-
only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Exceptions:
Different types of errors can occur while running a program - such as coding mistakes, invalid
input, or unexpected situations.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example