Java Unit-1 Engineering Btech 2
Java Unit-1 Engineering Btech 2
Features of java:
Features
7)Distributed 3)Object oriented
of java
5)Secure
OOP Concept
1)Class
2)Object
3)Data Abstraction
4)Encapsulation
5)Inheritance
6)polymorphism
7)Dynamic Binding
8)Message passing
Class
A class is a collection of instance variables and methods.
object
An object is an instantiation of class. It contains properties and
functions.
Abstraction:
Hiding internal details and showing functionality is known as
abstraction.
Example :
1. ATM Machine
• What you see: Insert card, enter PIN, withdraw cash.
• What’s hidden: Verification, bank communication, cash management logic.
2. Vehicle System
• What you do: Start the vehicle, drive.
• What’s hidden: Engine mechanisms, fuel injection, etc.
Encapsulation
Binding (or wrapping) code and data together into a single unit are
known as encapsulation.
Inheritance
Inheritance is a process in which one object acquires all the properties
and behaviors of its parent object automatically. In such way, you can
reuse, extend or modify the attributes and behaviors which are defined
in other class.
Example: School Management
Common properties like name and age are shared by Students and
Teachers.
So, both can inherit from a common Person class.
class Account
{
void showBalance()
{
System.out.println("Balance: $1000");
}
}
class SavingsAccount extends Account
{
void showInterestRate()
{
System.out.println("Interest Rate: 3.5%");
}
}
class Example
{
public static void main(String[] args)
{
SavingsAccount myAccount = new SavingsAccount();
myAccount.showBalance(); // Inherited from Account
myAccount.showInterestRate(); // Defined in SavingsAccount
}
Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
Example:
class Payment
{
void pay()
{
System.out.println("Making a generic payment.");
}
}
class CreditCard extends Payment
{
void pay()
{
System.out.println("Payment done using Credit Card.");
}
}
class DebitCard extends Payment
{
void pay()
{
System.out.println("Payment done using Debit Card.");
}
class UPI extends Payment
{
void pay()
{
System.out.println("Payment done using UPI.");
}
}
class Demo
{
public static void main(String[] args)
{
Payment obj =new CreditCard();
obj.pay();
obj = new DebitCard();
obj.pay();
obj = new UPI();
obj.pay();
}
}
Dynamic binding
Binding of method call to a method body at run time is called dynamic binding.
Example :
Class calculate
{
void sum(int x) //called function
{
System.out.println(x);
}}
class demo
{
public static void main(String args[])
{
calculate obj=new calculate();
Obj.sum(10); //calling function
}
}
Message passing
One object interacts with another object by invoking methods on that object.
Benefits of OOP
Example1:
int a = 5;
int b = a; // Compatible: both are int
Example2:
String name = 123;
// Not compatible: int cannot be assigned to String
Type size
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
Character:
This group includes char, which represents a unicode character
Type size
char 2 bytes
Floating point number:
This group includes float & double which represents numbers with
fractional precesion.
Type Size
float 4 bytes
double 8 bytes
Boolean:
This group includes boolean which is a special type for
representing true/false value.
Type size
boolean 1 byte
Type Size in Description
bytes
(bits)
1. Byte 1 (8) Stores whole numbers from -128 to 127
6. Float 4 (32) Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
7. Double 8 (64) Stores fractional numbers. Sufficient for storing 15 decimal digits
2)Read statement:-
Ex:Scanner sc=new Scanner(System.in);
int a=sc.readInt();
Types of variable in java
1)Local variables :
Declared inside a method, constructor or block.Only accessible
within that method/block.
2)Instance variables :
Instance variables are known as non-static variables and are
declared in a class outside of any method, constructor, or
block.
3)static variables:
Static variables are also known as class variables.
static variables are declared using the static keyword within a
class outside of any method, constructor, or block.
Scope and life time
Scope of a variable is its lifetime in the program.
The scope tells the compiler about the segment within a program where the variable is accessible or used.
Static variables are created at the start of program execution and destroyed automatically when execution ends.
class variable
{
static int x = 100; // Static variable
int y = 50; // Instance variable
void display()
{
int z = 10; // Local variable
System.out.println("Local Variable: " + z);
System.out.println("Instance Variable: " + y);
System.out.println("Static Variable: " + variable.x);
}
Methods:
nextInt()
nextByte()
nextFloat()
nextLine()
nextLong()
nextDouble()
Java program to read input using scanner class
import java.util.Scanner;
class Read
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
}
Structure of java Program
Documentation section
Package statement
Import Statement
Interface Statement
Class Definitions
class box
{
int height, width, length;
void volume()
{
int volume= height* width* length;
System.out.println(“volume=”+volume);
}
}
class demo
{
public static void main(String args[])
{
Box obj=new box();
obj.height=10;
obj.width=20;
obj.length=25;
Obj.volume();
}
}
Java program on passing parameters to a method.
class box
{
int height, width, length;
void volume(int height,int width, int length)
{
System.out.println(“volume=”+(height*width*length));
}
}
class demo
{
public static void main(String args[])
{
Box obj=new box();
obj.volume(1,2,3);
}
}
Command Line argument:
……….
access_specifier returntype methodname([type para1,…])
{
//body of method
}
}
1)Default: members can 3)Private:Members can
be accessed inside and be accessed inside a class
outside the class but in the Ex:class A
same package. {
Ex:class A private int x=10;
{ }
int x=10;
} 4)Protected: members
2)Public: Members can be can be accessed with in
accessed inside and the class as well it’s sub
outside the class but in class
the same package, Ex:class A
outside the package {
Ex:class A protected int x=10;
{ }
public int x=10;
}
Write a program by using public ,private, protected
class Sample
{
private int x=10;
public int y=20;
protected int z=30;
int p=40;
}
class ex1
{
public static void main(String args[])
{
Sample obj=new Sample();
//System.out.println(obj.x);
System.out.println(obj.y);
System.out.println(obj.z);
System.out.println(obj.p);
class A class C extends B
{ {
void show()
private int x=10;
{
public int y=20; //System.out.println(x);
protected int z=30; System.out.println(y);
int p=40; //System.out.println(z);
} System.out.println(p);
class B extends A }
}
{
class example
void display() {
{ public static void main(String args[])
//System.out.println(x); {
System.out.println(y); C obj=new C();
System.out.println(z); B obj2=new B();
obj2.display();
System.out.println(p);
obj.show();
}} }
Accessing private variable in class
}
}
Conditional operator (?): Conditional operator will verifies the
condition is true then it will considers the first agrument after the (?)
and if the condition is false it considers the second argument after(:)
symbol.
Syntax:
(condition)?argument1:argument2;
class Conditional
{
public static void main(String args[])
{
int a=10,b=20,x;
x= a < b ? a : b;
System.out.println(“x=“+x);
}
Bitwise operator:It is used to test the bits or shifting them to the right or left.
For Example: & , | , ^ ,<< , >> , ~
class Bitwise
{
public static void main(String[] args)
{
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println("a & b: " + (a & b)); // 0001 => 1
System.out.println("a | b: " + (a | b)); // 0111 => 7
System.out.println("a ^ b: " + (a ^ b)); // 0110 => 6
System.out.println("~a: " + (~a)); // Inverts 0101 => 1010 => -6 in 2's
complement
System.out.println("a << 1: " + (a << 1)); // 1010 => 10
System.out.println("a >> 1: " + (a >> 1)); // 0010 => 2
}
}
Special operator:
Java support some special operator such as
1) Dot operator 2)instanceof operator
1)Dot operator:Dot operator is used to access the instance
variables & methods of class objects.
Ex:person.display();
2)instanceof operator:
The instanceof is an object reference operator
& returns true if the object on the lefthand side is an instanceof
the class given on the righthand side.
class student
{
public static void main(String[] args)
{
student object = new student();
System.out.println(object instanceof student);
System.out.println(object1 instanceof student);
}
Conditional statements
Conditional statements are used to perform different actions based
on different conditions.
The following conditional statements are:
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
1)If statement: if statement tests the condition. It executes the if block if
condition is true.
Syntax:
if(condition){
//code to be executed
}
Ex:
class IfExample {
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
class stmt
{
public static void main(String args[])
{
int stdmarks=70;
if(stdmarks>=60)
{
System.out.println(“passed”);
}
}}
2) if-else Statement:
The Java if-else statement also tests the condition. It executes the if
block if condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
//It is a program of odd and even number.
class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
Else
{
System.out.println("odd number");
}
}
}
//To display result
class stmt
{
public static void main(String args[])
{
int stdmarks=60;
if(stdmarks>=50)
{
System.out.println(“passed”);
}
else
{
System.out.println(“fail”);
}
}
}
3)if-else-if ladder Statement:
The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
class stmt
{
public static void main(String args[])
{
int stdmarks=98;
if(stdmarks>=90)
System.out.println(“Grade A”);
elseif(stdmarks>=80)
System.out.println(“Grade B”);
elseif(stdmarks>=70)
System.out.println(“Grade C”);
elseif(stdmarks>=60)
System.out.println(“Grade D”);
else
System.out.println(“failed”);
}
Nested if statement:
The nested if statement represents the if block within
another if block. Here, the inner if block condition
executes only when outer if block condition is true.
Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Java Program to demonstrate the use of Nested If Statement
class Example
{
public static void main(String[] args)
{
int number = 5;
if (number != 0)
{
if (number > 0)
{
System.out.println("The number is positive.");
}
else
{
System.out.println("The number is negative.");
}
}
}
}
Conditional loops
In programming languages, loops are used to
execute a set of instructions/functions repeatedly
when some conditions become true. There are
three types of loops in Java.
• for loop
• while loop
• do-while loop
1) For Loop:
The Java for loop is used to iterate a part of the
program several times. If the number of iteration
is fixed, it is recommended to use for loop.
import java.util.Scanner;
class Multiplicationtable
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to print its multiplication table: ");
import java.util.Scanner;
class WhileExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int sum = 0;
while (num > 0)
{
sum += num % 10;
num = num / 10;
}
System.out.println("Sum of digits: " + sum);
}
}
Java do-while Loop
The Java do-while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed and you
must have to execute the loop at least once, it is recommended
to use do-while loop.
The Java do-while loop is executed at least once because
condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Java program to calculate factorial of a given number
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int i = 1;
long fact = 1;
do
{
fact *= i;
i++;
} while (i <= num);
System.out.println("Factorial of " + num + " is: " + fact);
}
}
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while
loop.
Syntax:
do{
//code to be executed
}while(true);
Example:
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Java Switch Statement
The Java switch statement executes one statement from multiple
conditions. It is like if-else-if ladder statement. The switch statement
works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long.
Points to Remember
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders
compile-time error.
The Java switch expression must be of byte, short, int,, enums and
string.
Each case statement can have a break statement which is optional.
When control reaches to the break statement, it jumps the control after
the switch expression. If a break statement is not found, it executes the
next case.
The case value can have a default label which is optional.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
class switchexample
{
public static void main(String[] args)
{
int a = 10, b = 5, c;
for (int i = 1; i <= 4; i++)
{
switch (i)
{
case 1: c = a + b;
System.out.println("Addition: " + c);
break;
case 2: c = a - b;
System.out.println("Subtraction: " + c);
break;
case 3: c = a * b;
System.out.println("Multiplication: " + c);
break;
case 4: c = a / b;
System.out.println("Division: " + c);
break;
default:
System.out.println("No operation");
}
}
}
}
Break and continue:
datatype arrayname[];
Ex: int n[];
arrayname[subscript]=value;
Ex:n[0]=35;
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization 0 1 2 3 4
a[1]=20; 10 20 70 40 50
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix
form).
Two dimensional arrays are similar to single dimensional arrays,the only
difference is a two dimensional array has two dimensions.
class Testarray3
{
public static void main(String args[])
{ Output:
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 123
//printing 2D array 245
for(int i=0;i<3;i++) 445
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
Passing Arrays to Methods
Example:
class ArrayExample
{
void showNumbers(int[] n)
{
System.out.println("The numbers in the array are:");
for (int i = 0; i < n.length; i++)
{
System.out.println(n[i]);
}
}
public static void main(String[] args)
{
int[] a = {10, 20, 30}; // Create an array
ArrayExample obj = new ArrayExample();
obj.showNumbers(a);
}
}
Returning an array from the method
In java we can also return an array from the method .To return an array from a
method, the method's return type must be declared as an array of the appropriate data
type.
class ArrayReturnExample
{
int[] getNumbers() // Method that returns an array of integers
{
int[] numbers = {10, 20, 30, 40, 50};
return numbers;
}
public static void main(String[] args)
{
ArrayReturnExample obj = new ArrayReturnExample();
int[] result = obj.getNumbers();
System.out.println("Returned array:");
for (int i = 0; i < result.length; i++)
{
System.out.print(result[i] + " ");
} } }
Anonymous Array in Java
class Student
{
String name;
int age;
Student(String n, int a)
{
name = n;
age = a;
}
void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
}
class StudentArray
{
public static void main(String[] args)
{
Student[] s = new Student[3];
s[0] = new Student("Anitha", 18);
s[1] = new Student(“Sunith", 19);
s[2] = new Student(“Pranitha", 20);
for (int i = 0; i < s.length; i++)
{
s[i].display();
}
}
}
Constructor in Java:
A constructor in Java is a block of code within a class that is used to
initialize objects of class.
In other words, a constructor is used to initializing the value of
variables.
A constructor is a special method which is invoked automatically at
the time of object creation.
Syntax:
class classname
{
public classname()
{
.
.
.// code of constructor
}
}
Example of default constructor
class Car
{
String brand;
Car()
{
brand = "Toyota";
}
void display()
{
System.out.println("Brand: " + brand);
}
}
class Demo
{
public static void main(String[] args)
{
Car myCar = new Car();
myCar.display();
}
Parameterized Constructor:
Syntax:
class classname
{
public classname(type para1,type para2,…..)
{
.
. //code of constructor
}
class Student4 s1
{
int id;
String name;
id
Student4(int i, String n)
{
id = i;
name
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
} s2
class demo
{
public static void main(String args[])
{
id
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
name
s1.display();
s2.display();
}
}
Copy Constructor:
A copy constructor is a constructor that creates a new object by
copying the fields of another object of the same class.
Syntax:
class classname
{
public:classname(classname &ob)
{
.
.//code of constructor
.
}
class Book
{
String title;
String author;
Book(String t, String a)
{
title = t;
author = a;
}
Book(Book b)
{
title = b.title;
author = b.author;
}
void display()
{
System.out.println("Title: " + title + ", Author: " + author);
}
}
class Main
{
public static void main(String[] args)
{
Book b1 = new Book("Java Programming“,”James
Gosling”);
Book b2 = new Book(b1);
System. out. println("Original Book:");
b1.display();
System. out. println("Copied Book:");
b2.display();
}
}
Private constructor
class student
{
privtate student()
{
System.out.println(“ it’s a private constructor”);
}
public static void get()
{
student s=new student();
}
}
class demo
{
public static void main(String args[])
{
student.get();
}
}
Method
class Main
{
static void myMethod(String fname)
{
System.out.println(fname );
}
public static void main(String[] args)
{
myMethod(“Apple");
myMethod(“Banana");
myMethod(“Orange");
}
}
Passing object as an argument to a method
class A
{
int x;
void set(int a)
{
x=a;
System.out.println(x);
}
void display(A ob)
{
System.out.println(ob.x);
}
public static void main(String[] args)
{
A obj1=new A();
obj1.set(10);
A obj2=new A();
obj2.display(obj1);
}
}
Difference between constructor and method
Constructor Method
A constructor is used to initialize A method is used to define the
objects when they are created. behavior or functionality of an
The name of a constructor must be object.
the same as the class name. A method can have any valid name.
A constructor does not have any A method must have a return type
return type, not even void. like void, int, string etc..
A constructor is automatically called A method must be called manually
when an object is created. using the object.
A constructor is not inherited by A method can be inherited and
child classes. overridden in child classes.
A constructor cannot be declared A method can be declared final,
final, abstract, static. abstract, static.
A constructor cannot return any A method can return a value using
value. the return statement.
this keyword
this keyword refers to the current instance of the class.
It is mainly used to:
• Call methods and access fields of the current class
• Pass the current object as a parameter
• Tell the difference between local variables and instance variables
when they have the same name
this keyword is predefined reference variable which can store
address of an object.
Methods to use “this” in java
Invoke current class instance variable.
Invoke current class method.
Invoke current class constructor.
Pass an argument in the method call
Return the current class object
this: current class instance variable
When a method or constructor has a parameter with the same name as an instance
variable , we use this. variablename to refer to the instance variable and preventing
ambiguity between the local variable and the instance variable.
class box
{
int length=20;
void print()
{
int length=30;
System .out. println(“local variable” + length);
System. out. println(“Global variable”+ this. length);
}
class test
{
public static void main(String args[])
{
box b=new box();
b.print();
}
}
class A
{
int a;
int b;
A(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
A obj = new A(10, 20);
obj.display();
}
}
this: Invoke current class method
"this" can be used to call one method from another method within
the same class.
class test
{
void show()
{
System.out.println("Inside show function");
}
void display()
{
this.show();
System.out.println("Inside display function");
}
public static void main(String args[])
{
test t1 = new test();
t1.display();
}}
this: Invoke current class constructor
• "this" can be used to call a constructor from another constructor in the same class.
Rule:
• To call one constructor from another within the same class, the this() call must be
the first statement in the constructor.
class Test
{
Test()
{
System.out.println("Default constructor");
}
Test(String s1, String s2)
{
this(); // Calls the default constructor first
System.out.println("s1 = " + s1 + ", s2 = " + s2);
}
}
class Main
{
public static void main(String args[])
{
Test t1 = new Test("default constructor",
"parameterized constructor");
}
}
this:Pass an argument in the method call
“this” can be used to pass the current object as an argument to another method.
class Demo
{
void show(Demo obj)
{
System.out.println("Method called using this as argument");
}
void display()
{
show(this); // passing current object to the method
}
public static void main(String[] args)
{
Demo d1 = new Demo();
d1.display();
}
}
this: Return the current class object
class Demo
{
Demo getObject()
{
return this;
}
void display()
{
System.out.println("this keyword returning current class object");
}
public static void main(String[] args)
{
Demo obj = new Demo();
obj.getObject().display(); // Using the returned object to call display()
}
}
Polymorphism
• The word polymorphism means having many forms, and it
comes from the Greek words poly (many) and morph
(forms), this means one entity can take many forms.
Or
• When one task is performed by different ways i.e. known as
polymorphism.
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));
}
}
Without static keyword
class Adder
{
int add(int a, int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}}
class TestOverloading1
{
public static void main(String[] args)
{
Adder obj=new Adder();
System. out. println(obj. add(11,11));
System. out. println(obj. add(11,11,11));
}}
By a change in the data type of arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static int add(double a, double b)
{
return a+b;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11));
}
}
Can we overload java main method() in java?
Yes, we can overload the main() method in java like any
other method using the concept of method overloading.
However, the JVM only calls the main() method that
receives a String[] (string array) as an argument.
class Main
{
public static void main(int num)
{
System.out.println("Main method with int: " + num);
}
public static void main(String msg)
{
System.out.println("Main method with String: " + msg);
}
public static void main(double val)
{
System.out.println("Main method with double: " + val);
}
public static void main(String[] args)
{
main(42);
main("Hello");
main(3.14);
}
}
Constructor overloading
class Adder
{
Adder(int a, int b)
{
System. out. println (a+b);
}
Adder(int a,int b,int c)
{
System. out. println (a+b+c);
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder obj=new Adder(11,11);
Adder obj=new Adder(11,11,11);
}
}
Overriding
• Overriding is the concept of hiding the members of super class
by the members of subclass.
Types of Overriding:
Instance variable overriding.
Method overriding.
Instance variable overriding
class A
{
public int x=10;
}
class B extends A
{
public int x=10;
Void show()
{
System.out.println(“A class x value= ”+x);
System.out.println(“B class x value= ”+x);
}
}
class demo
{
Public static void main(String args[])
{
B obj=new B();
Obj.show();
}
}
Method overriding
If the methods of super class and subclass have same name along with their signatures
then it is said to be method overriding.
Rules for Overriding:
• Name, parameters, and return type must match the parent method.
• Java picks which method to run, based on the actual object type, not just the variable type.
• Static methods cannot be overridden.
class A
{
public void show()
{
System.out.println(“show of A class….”);
} }
class B extends A
{
public void show()
{
System.out.println(“show of B class….”);
}
public void display()
{
show();//class show() of B
show();//class show() of A
}
}
class override
{
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}
output:
show of B class….
show of B class….
Solution for overriding is super keyword:
We can call the parent class variables and method in the
overriding method using the super keyword.
Example:
class RecursionExample
{
// Recursive method to calculate factorial
static int factorial(int n)
{
if (n == 0)
{
return 1;
}
return n * factorial(n - 1);
// Recursive call
}
public static void main(String[] args)
{
int number=5;
System.out.println("Factorial of " + number + " is " + factorial(number));
}
}
Passing Parameter
There are different ways in which parameter data can be passed
into and out of methods and functions.
Types of parameters:
1.Formal Parameters: These are the parameters declared in a
method or constructor signature. They act as placeholders and
receive values when the method is called.
2.Actual Parameters: These are the values or variables passed
when calling a method. They get assigned to the formal
parameters.
parameters can be passed in two ways:
• call by Value
• call by Reference
Java Program on call by value
class Example
{
public static void add(int a)
{
a = a + 10;
System.out.println(" a = " + a);
}
public static void main(String[] args)
{
int num = 5;
System.out.println("num = " + num);
add(num); // call by value
}
}
java program on call by reference
class Box
{
int size;
}
class Example
{
public static void changeSize(Box b)
{
b.size = 50;
System.out.println("size = " + b.size);
}
public static void main(String[] args)
{
Box b1 = new Box();
b1.size = 10;
System.out.println("Before changeSize: size = " + b1.size);
changeSize(b1); // Passing the object reference
}
}
Nested and Inner Classes
// 2. Finding Length
System.out.println("Length of str1: " + str1.length());
// 3. Concatenation
String str3 = str1.concat("Welcome .");
System.out.println("Concatenated String: " + str3);
// 4. Character Extraction
System.out.println("Character at index 1: " + str1.charAt(1));
// 5. Substring
System.out.println("Substring from index 7: " + str1.substring(7));
System.out.println("Substring from 7 to 11: " + str1.substring(7, 11));
// 6. String Comparison
String str4 = "Hello, Java!";
System.out.println("str1 equals str4? " + str1.equals(str4));
// 7. Changing Case
System.out.println("Uppercase: " + str1.toUpperCase());
System.out.println("Lowercase: " + str1.toLowerCase());
// 9. Replacing Characters
System.out.println("Replacing 'Java' with 'Python': " + str1.replace("Java",
"Python"));
}
}
Garbage collection
In order to call the garbage collector explicitly we use finalize() and gc().
Syntax:
protected void finalize()
{
// code for finalize method
}
Advantage:
No wastage of memory.
Disadvantages:
If an object holds resources from outside the JVM (such as files or
memory allocated through native code), those resources are also lost
when the object is deleted by the garbage collector.
To overcome this disadvantage of garbage collection, we can use the
finalize() method.
The finalize() method is automatically called by the garbage collector
before the object is removed from memory. This method can be used to
release or save any external resources used by the object.
class MyClass public static void main(String[] args)
{ {
MyClass obj1 = new MyClass(1);
int m;
createObject();
MyClass(int n)
System.gc();
{
System.out.println("Program termination");
m = n;
}
System.out.println("Executing
public static void createObject()
constructor for object " + m);
{
}
System.out.println("Object creation
protected void finalize() started");
{ MyClass obj2 = new MyClass(2);
System.out.println("Finalize method MyClass obj3 = new MyClass(3);
called for object = " + m); MyClass obj4 = new MyClass(4);
} System.out.println("Object creation
} completed");
class test }
{ }
Step 1 - Download JDK
Open the browser and search for Download JDK 14 or click the link to download from
the Oracle website. It will show the JDK download page as shown in Fig 1.
Fig 1.
Accept the License Agreement and click on the link to download the installer as
highlighted in Fig 2. It will start downloading JDK 14 installer for Windows.
Fig 2.
Step 2 - Install JDK
Now execute the JDK installer by double-clicking it. It might ask system permission
before starting the installation. Click on yes to allow the installer to execute itself. It
shows the installer welcome screen as displayed in Fig 3.
Fig 3.
Click on Next Button to initiate the installation process. The next screen shows options
to change the installation path. We can change the installation location on this screen if
required as displayed in Fig 4.
Fig 4.
Now click on Next Button to start the installation. It will show the progress as
displayed in Fig 5.
Fig 5.
It shows the success screen after completing the installation as mentioned in Fig 6.
Fig 6.
Now open the Command Prompt and type the command java -version to confirm whether
it's installed successfully as mentioned in Fig 7.
Fig 7.
It will either show the message - java is not recognized as an internal or external
command or show the previously installed version. In order to start using the JDK
installed by us from the command prompt, we need to set the environment variable.
You can follow the below-mentioned steps to do so.
Right Click -> My Computer(This PC) -> Properties -> Advanced System Settings
The above steps will open the Windows settings panel as shown in Fig 8.
Fig 8.
Now click on Environment Variables, select Path under System Variables section and
click on Edit. We need to add the path of installed JDK to system Path.
Remove the path of previously installed JDK. Also, update JAVA_HOME in case it's
already set. Now click on New Button and add the path to installed JDK bin which
is C:\java\oracle\java-14\bin in my case as shown in Fig 9. Press OK Button 3 times to
close all the windows. This sets the JDK 14 on system environment variables to access
the same from the console.
Now again open the console and test the Java version as shown in Fig 10.
Fig 10.
Getting started with Java - OOPS Through JAVA
In this step, we will write, compile, and execute our first program in Java using the
standard OOPS Through JAVA example.
Now write the first Java program as shown below, save the program
as HelloWorld.java and exit the editor. Make sure that the class name and file name are
the same.
Now open the command prompt and navigate to the path where you have saved your
Java program. Use the below-mentioned commands to compile and execute the
program.
These are the easy to install steps required to install Oracle Java on Windows and write,
compile and execute the Java program.
Thank
You