Unit 2 (Java Btech)
Unit 2 (Java Btech)
Ex:
class A
{
Private int x=10;
Private void msg()
{
System.out.println(“hello”);
}
}
Public class B
{
Public static void main(String args[])
{
A obj=new A();
System.out.println(obj.x);
Obj.msg();
1
}
}
Output:compile time error.
2.public:
• The access level of public modifier is everywhere.
• It can be accessed from with in the class outside the class,with in the package and
outside the package.
Ex:
package x;
public class A
{
Public void msg()
{
System.out.println(“hello”);
}
//save by B
Import x.*;
Class B
{
public static void main(String args[])
{
A obj=new A();
Obj.msg();
}
}
Output: hello.
3.default:
• If you don’t use any modifier, it is located as default by default.
• The default modifier is accessible only within the package.it cannot be accessed from
outside the package.
• It provides more accessibility than private, but it is more restrictive than protected and
public.
2
Ex:
//saved by A.java
Package x;
class A
{
Void msg()
{
System.out.println(“hello”);
}
}
//saved by B.java
Import x.*;
Class B
{
Public static void main(String args[])
{
A obj=new A();
obj.msg();
}
}
Output: compile time error.
• Here scope of a class A and its method msg() is default.so it cannot be accessed from
out of the package.
4.protected:
• The access modifier is accessible within package and outside the package but through
inheritance only.
• The protected access modifier can be applied on the data member, method and
constructor. it cannot be applied on the class.
• It provides more accessibility than the default modifier.
Ex://save by A.java
Package x;
Public class A
3
{
Protected void msg()
{
System.out.println(“hello”);
}
}
//save by B.java
Import x.*;
Class B extends A
{
Public static void main(String args[])
{
B obj=new B();
Obj.msg();
}
}
Output:
Hello
non-access modifiers:
• There are many non-access modifiers, such as static,abstract,synchronized etc.
• There are 7 types of non access modifiers available in java.
1.static:
• static keyword in java is used for memory management.it can be applicable for
methods,variables,blocks etc.
2.final:
• final keyword indicates that specific class cannot be extended or a method cannot be
over ridden.
3.abstract:
• abstraction is a process of hiding the internal details and showing the functionality to
the user.
4.synchronized:
4
• this keyword prevents block of code from executing multiple threads at once.it is very
important for some critical operations.
5.volatile:
• the volatile keyword is only applicable to a variable.by using this keyword every
reading and writing operations will be done directly on the main memory. i.e, memory
management.
6.transient:
• this needs a prior knowledge of serialization. serialization is used to convert an object
into a stream of bytes.
• Deserialization performs exactly an opposite operation.it is used with data members of
a class in order to avoid their serialization.
• When jvm reads transient keyword.it ignores the original value of the object instead it
stores the default value of the object.
Ex: if a program accepts a user’s login details and password. but we don’t want to store the
original password in the file. here we can use transient keyword.
Syntax: private transient<member value>;
7.native keyword:
1.local variable:
• A variable which is declared inside the body of the method is known as local variable.
5
• You can use this variable only with in the method and other methods in the class are
not even aware that the variable exists.
• Local variable cannot be defined with static.
2.instance variable:
• A variable is declared inside the class but outside the body of the method is known as
instance variable.
• It is not declared as static.
3.static variable:
• A variable which is declared with a static keyword is known as ststic variable
• It cannot be local
Ex:
Class A
{
Int data=10;//instance variable
Static int m=100;//static variable
Void method()
{
Int n=1000;
}
}
Method:
• Method is a block of code or collection of statements or set of code grouped together
to perform specific task
• It is used to achieve reusability of code
• The method is executed only when we call or invoke it.
• The most important method in java is the main() method.
Method declaration:
6
Naming a method:
• While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
• If the method name has more than two words, the first name must be a verb followed
by adjective or noun.
• In the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example:
• It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of methods:
1.predefined method
Predefined method:
• In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods
• We can directly use these methods just by calling them in the program at any point.
7
System.out.println("hello");
Java hello
hello
8
}
OUTPUT:
javac SumOfNumbers.java
java SumOfNumbers
Enter the first number: 10
Enter the second number: 20
The sum of two numbers x and y is: 30
DECLARATION OF CLASS OBJECTS:
• Object: it is a basic unit of object oriented programming represents the real life entity.
• An entity that has state and behaviour is known as an entity.
Declaration of an object:
12
Nested classes:
• In java ,it is possible to define a class within another class, such classes are known as
nested classes.
• They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation and create more readable and maintainable code.
• The scope of a nested class is bounded by the scope of its enclosing class.
• A nested class is also a member of its enclosing class.
• Nested classes are divided into two categories:
• 1-static nested class: nested classes that are declared static are called static nested
classes.
• 2-inner class: an inner class is a non-static nested class.
Ex: public class demo
{
Public static void main(string args[])
{
A obj=new A();
A.B obj1=obj.new B();
}
}
Class A
{
Class B
{
Int x=10;
Void display(){
System.out.println(“ helloworld”);
}
}
Output: helloworld.
Passing arguments by value:
• Call by value means that arguments value is copied and is passed to the parameter
list of a method.
• Changes made in a copy of variable never modify the value of variable outside the
function
13
Ex: public class value
{
Int a;
Int b;
Private static void add(int x, int y);
{
X=10;
System.out.println(“result is :”+(x+y));
}
Public static void main(string args[])
{
Value obj=new value();
Obj.a=5;
Obj.b=10;
System.out.println(“before:”+(obj.a+obj.b));
add(obj.a,obj.b);
System.out.println(“after:”+(obj.a+obj.b));
}
}
Output:before:15
Result:20
After:15.
14
Private static void add(ref obj, ref obj1);
{
Obj.a=10;
System.out.println(“result is :”+(obj.a+obj.b));
}
Public static void main(string args[])
{
ref obj=new ref();
ref obj1=new ref();
Obj.a=5;
Obj.b=10;
System.out.println(“before:”+(obj.a+obj.b));
add(obj, obj);
system.out.println(“after:”+(obj.a+obj.b));
}
}
Output:before:15
Result:20
After:20
Keyword this:
• This can be used to refer current class instance variable.
• This can be used to invoke current class method,constructor.
• This can be passed as an object in the method call, constructor call.
• This can be used to return the current class instance from the method.
Ex:
class This1
{
int a=10;
void display()
{
int a=20;
System.out.println(a);
System.out.println(this.a);
}
public static void main(String args[])
15
{
Overloaded Methods :
Method: method is a block of code or collection of statements grouped together to perform a
certain
Task or operation and return the result to the caller if applicable.
Syntax:
accessmodifier returntype method name(parameters)
{
//method body;
}
• When there are multiple functions with the same name but different parameters, then
these functions are said to be overloded.
• Different ways to overload the methods are,
1.by changing the no.of arguments.
2.by changing the data type.
1.by changing the 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.
Ex:
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;
16
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder. add(10,10));
System.out.println(Adder. add(10,10,10));
}}
Output:20
30
2.by changing the data type:
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 .
Ex:
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class Overloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output: 22
24.9
17
Overloded constructor methods:
• in Java, we can overload constructors like methods
• The constructor overloading can be defined as the concept of having more than one
constructor with different parameters, so that every constructor can perform a different
task.
Ex:
class Constructordemo
{
Constructordemo()
{
System.out.println("constructor with out arguments");
}
Constructordemo(int a)
{
System.out.println("constructor with arguments");
}
}
class Coverload
{
public static void main(String args[])
{
Constructordemo obj=new Constructordemo();
Constructordemo obj1=new Constructordemo(10);
}
}
Output: constructor with out arguments
constructor with arguments
18
• It means that any changes made to the object inside the method will have an immediate
impact on the original object.
Ex:
public class Objectparameter
{
private int a;
private String name;
public Objectparameter(int a, String name)
{
this.a=a;
this.name=name;
}
public void x(Objectparameter p)
{
System.out.println("a"+p.a);
System.out.println("name"+p.name);
}
public static void main(String args[])
{
Objectparameter obj=new Objectparameter(10,"hello");
Objectparameter obj1=new Objectparameter(20,"world");
obj.x(obj1);
}
}
Output:
a20
name world
Recursive methods:
• Recursion is the technique of making a function call itself.
• This technique provides a way to break complicated problems down into simple
problems which are easier to solve.
• Adding two numbers together is easy to do, but adding a range of numbers is more
complicated.
• recursion is used to add a range of numbers together by breaking it down into the simple
task of adding two numbers.
Ex:
public class Recursion1
{
static int a=0;
static void x()
{
19
a++;
if(a<=5)
{
System.out.println("hello" +a);
x();
}
}
public static void main(String args[])
{
x();
}
}
Output:
hello1
hello2
hello3
hello4
hello5
Nesting of methods:
• In Java, methods and variables that are defined within a class can only be accessed by
creating an instance of that class or by using the class name if the methods are static
• The dot operator is used to access methods and variables within a class.
• However, there is an exception to this rule: a method can also be called by another
method using the class name, but only if both methods are present in the same class.
• Efficient code organization and simplified method calls within a class are possible
through nesting of methods.
Syntax:
Class A
{
Method1();
}
Method2()
20
{
Method1();
}
}
Ex:
class Nestedmethod
{
void display()
{
System.out.println("hello");
}
void show()
{
System.out.println("world");
display();
}
public static void main(String args[])
{
Nestedmethod obj=new Nestedmethod();
obj.show();
}
}
Output:
World
Hello.
Overriding methods:
• If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
• Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass
21
• Method overriding is used for runtime polymorphism
Ex:
class A
{
void x()
{
System.out.println("hello");
}
}
class B extends A
{
void x()
{
System.out.println("world");
}
}
class C extends A
{
void x()
{
System.out.println("name");
}
}
class Runtimeploy
{
public static void main(String args[])
{
A obj;
obj=new B();
obj.x();
22
obj=new C();
obj.x();
}
}
Output:
World
Hello.
Attributes final and static:
Static:
• If you apply any method with static keyword, it is known as static method
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data members and can change the value of it.
• There are 2 main restrictions for static methods are:
1.static method cannot use non static data members.
2.this and super keyword cannot be used in static context.
3.Static block:
• it is used to initialize the static data members.
• It is executed before the main method at the time of class loading.
• Executed by default without any explicit call
Nested classes:
• Access with the help of class name
• For single class, we can access directly
Ex:
class A
23
{
static int x=10;
static void display()
{
System.out.println("static method");
}
static
{
System.out.println("static block");
}
}
class Staticdemo
{
public static void main(String args[])
{
System.out.println("main");
System.out.println(A.x);
A.display();
}
}
Output:
main
static block
10
static method
final keyword:
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many context.
• Final can be applied with the variable, method, class.
• A final variable that have no value it is called blank final variable or un initialized final
variable.
• Final keyword stop value change, stop method overriding, stops inheritance.
24
1.final variable:
• If you make any variable as final,you can change the value of final variable.
Ex:
class A
{
final int x=10;
void display()
{
x=20;
System.out.println(x);
}
public static void main(String args[])
{
A obj=new A();
obj.display();
}
}
Output:compile time error.
2.final method():
25
A obj=new A();
obj.display();
}
}
Output:compile time error.
3.final class:
26