Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views163 pages

Java Unit-1 Engineering Btech 2

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing features such as multi-threading, platform independence, and security. It explains fundamental OOP principles including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding, along with examples and Java syntax. Additionally, it covers data types, variable scopes, user input handling, access specifiers, and operators in Java.

Uploaded by

jonshow85550
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views163 pages

Java Unit-1 Engineering Btech 2

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing features such as multi-threading, platform independence, and security. It explains fundamental OOP principles including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding, along with examples and Java syntax. Additionally, it covers data types, variable scopes, user input handling, access specifiers, and operators in Java.

Uploaded by

jonshow85550
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 163

OOPS Through JAVA

Features of java:

9)Multi threaded 1)Compiled and Interpreted

8)Simple 2)Platform independent

Features
7)Distributed 3)Object oriented
of java

6)Garbage Collector 4)Robust

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

• Through inheritance we can eliminate redundant and extend


the use of existing classes.
• The principle of data hiding helps the programmer build
secure programs.
• It is easy to partition the work in a project based on objects.
Data Types
Java is strongly typed language
 Every variable has type and the type is strictly defined
 All assignment are checked for type compatibility
 variables are containers used to store data values.It determines what kind of
data can be stored in the variable.

Example1:
int a = 5;
int b = a; // Compatible: both are int

Example2:
String name = 123;
// Not compatible: int cannot be assigned to String

int number = "abc";


// Not compatible: String to int
Integers: This group includes bytes, short, int & long which are for
whole-valued signed numbers.

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

2. Short 2 (16) Stores whole numbers from -32,768 to 32,767

3. Int 4 (32) Stores whole numbers from -2,147,483,648 to 2,147,483,647

4. Long 8 (64) Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
5. Char 2 (16) Stores a single character/letter or ASCII values

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

8. Boolean 0 (1) Stores true or false values


class DataTypes
{
public static void main(String[] args)
{
byte b = 100;
short s = 10000;
int i = 100000;
long l = 10000000000L; //note the 'L' at the end
float f = 5.75f; // note the ‘f’ at the end
double d = 19.99;
char c = 'A';
boolean isJavaFun = true;
System.out.println("byte value: " + b);
System.out.println("short value: " + s);
System.out.println("int value: " + i);
System.out.println("long value: " + l);
System.out.println("float value: " + f);
System.out.println("double value: " + d);
System.out.println("char value: " + c);
System.out.println("boolean value: " + isJavaFun);
}
}
Variables:
Variables is an identifier used to store value.

Giving values to variables:


1)Assignment statement:-
Ex: int a=10;

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.

 Java provides 2 types of scopes


 Class level
 Method level

 Scope and life time of a Local variable :


 The scope of local variables exists only within the block in which they are declared.

 Scope and life time of a Instance variable :

 The Scope of instance variables are throughout the class.


 Instance variables are created when an object of the class is created and destroyed when the object is destroyed.

 Scope and life time of a Instance variable :

 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);
}

public static void main(String[] args)


{
variable obj = new variable();
obj.display();
}
}
Java user input(Scanner)
Scanner class is used to read the input from a user and it is found in
java.util package,
To use scanner class, create an object of the class and use methods
found in the scanner class.

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

Main method class


{
Main method definition
}
Procedure for implementing java program
Creating the program:We can create program using any text
editor(note pad).

Compile the program: We must compile the java program by


javac compiler.
Ex:javac sum.java

Running the program:java program can be executed by using the


interpreter.
Ex: java sum
//This a first java program
class sample
{
public static void main(String args[])
{
System.out.println(“welcome to java lab”);
}
}
//Write a java program to add two numbers.
class add
{
public static void main(String args[])
{
int a,b,c;
a=100;
b=200;
c=a+b;
System.out.println(“result=“+c);
}
}
//Write a java to print biggest of two numbers.
class big
{
public static void main(String args[])
{
int a,b;
a=100;
b=200;
if(a>b)
System.out.println(“biggest=“+a);
else
System.out.println(“biggest=“+b);
}
}
//Write a java to print 1 to 10 numbers.
class loop
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.println(“number=“+i);
}
}
}
Write a java program to create a class and object
class box
{
int height, width, length;
}
class demo
{
public static void main(String args[])
{
Box obj=new box();
obj.height=10;
obj.width=20;
obj.length=25;
int volume= obj.height* obj.width* obj.length;
System.out.println(“volume=”+volume);
}
}
Java program on creating multiple objects to a box class
class box
{
int height, width, length;
}
class demo
{
public static void main(String args[])
{
Box obj1=new box();
obj1.height=10;
obj1.width=20;
obj1.length=25;
int volume1= obj1.height* obj1.width* obj1.length;
System.out.println(“volume=”+volume1);
Box obj2=new box();
obj2.height=10;
obj2.width=20;
obj2.length=25;
int volume2= obj2.height* obj2.width* obj2.length;
System.out.println(“volume=”+volume2);
}
}
Java program that includes a method inside the box class

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:

•It is also possible to pass values to main() method & it can be


passed from command line.
//Program on command line argument.
class commandline
{
public static void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.println(“result=“+c);
}
}
Access specifier

The access specifier of a members specifies the scope of the


member where it can be accessed.
There are four types:
1)Default:
2)Public: Syntax:
3)Private: class classname
{
4)Protected access_specifier type instance_variable=value;

……….
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

To access private instances of a class we have to define public


method in the class.
Example:
class sample
{
private int x;
public void set(int a)
{
x=a;
}
public void display()
{
System.out.println(“x=“+x);
}
}
class ex
{
public static void main(String args[])
{
sample obj=new sample();
obj.set(100);
obj.display();
}
}
Operators in java
Operator in Java is a symbol which is used to perform
operations.
There are many types of operators in Java which are given
below:
1)Arithmetic Operator
2)Relational Operator
3)Logical Operator
4)Assignment Operator.
5)Increment and decrement
6)Conditional
7)Bitwise Operator
8)Special
ArithmeticOperator: Arithmatic operators can be used to perform simple
mathematical calculations.
For example: +, -, *, / etc.
.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}
Relational operators: Relational operators can be used to compare
two operands.
For Example: < , > , <= , >= , == , !=
class Relation
{
public static void main(String args[])
{
int a=10,b=5;
System.out.println(“a<b is“+(a<b));
System.out.println(“a>b is“+(a>b));
System.out.println(“a==b is”+(a==b));
System.out.println(“a<=b is”+(a<=b));
System.out.println(“a>=b is”+(a>=b));
System.out.println(“a!=b is “+(a!=b));
}
}
Logical operator: Logical operator can be used to combine two or
more conditions into one main condition.Based on this main condition
the If-Statement makes decision.
For Example: &&(And) , ||(OR) , !(Not)
class Logic
{
public static void main(String args[])
{
int attendencepercentage=75,internalmarks=25;
if(attendencepercentage >75 && internalmarks >25)
{
System.out.println(“Student is eligible to write the exam”);
}
else
{
System.out.println(“Student is not eligible to write the exam”);
}
}
}
class Logic
{
public static void main(String args[])
{
int theorymarks=35;
Int practicalmarks=45;
if(theorymarks>40 || practicalmarks>40)
{
System.out.println(“Student has passed the subject”);
}
else
{
System.out.println(Student has failed the subject”);
}
}
}
Assignment Operator: Assignment operator is one of the most
common operator. It is used to assign the value on its right to the
operand on its left.
For Example: =
class Operator
{
public static void main(String args[])
{
int a=1,b=2,c=3;
a +=5;
b *=4;
c += a * b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}}
Increment and Decrement operator: Increment operator
increments the value of variable by one which it is operating.
For Example: ++
class Increment
{
public static void main(String args[])
{
int m=10;
int n= ++m ;
System.out.println (“m=“ +m);
System.out.println (“n=“ +n);
int a= 5;
int b= a++;
System.out.println (“a=“ +a);
System.out.println (“b=“ +b);
}
}
Decrement operator: Decrement operator decrements the value
of variable by one which it is operating.
For Example: --
class Decrement
{
public static void main(String args[])
{
int m=10;
int n= --m
System.out.println (“m=“ +m);
System.out.println (“n=“ +n);
int a= 5;
int b= a--;
System.out.println (“a=“ +a);
System.out.println (“b=“ +b);

}
}
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: ");

int number = sc.nextInt();


System.out.println("Multiplication Table for " + number + ":");
for (int i = 1; i <= 10; i++)
{
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}
Java While Loop
The java while loop is used to iterate a part of
the program several times. If the number of
iteration is not fixed, it is recommended to use
while loop.
Syntax:
while(condition){
//code to be executed
}
Java program to calculate the sum of its digits of a given number

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:

• The Java break statement is used to break loop


or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop,
it breaks only inner loop.
• We can use Java break statement in all types of loops
such as for loop, while loop and do-while loop.

• The continue statement breaks one iteration (in the


loop), if a specified condition occurs, and continues
with the next iteration in the loop.
class MyClass
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
System.out.println(i);
}
}
}
class MyClass
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
System.out.println(i);
}
}
}
Type conversion or Type casting
• Conversion from one data type value to another data type value
is known as type conversion.
• Java supports type conversion in two ways.
1)Implicit conversion
2)Explicit conversion

Implicit conversion: Converting from one data type value to


another data type value internally is called implicit conversion.
• To convert it should satisfy 2 condtions:
 Destination and source variable type should be type
compatible.
 The destination variable datatype size should be larger than
source variable
Output:

Program on Implicit conversion


public class Conversion{
public static void main(String[] args)
{
int i = 200; Output
Int value 200
Long value 200
//automatic type conversion Float value 200.0
long l = i;

//automatic type conversion


float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
Explicit conversion
class Narrowing
{
public static void main(String[] args)
{
double d = 200.06;
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double Data type value "+d);
System.out.println("Long Data type value "+l); //fractional part lost
System.out.println("Int Data type value "+i); //fractional part lost
}
}

Double Data type value 200.06


Long Data type value 200
output Int Data type value 200
Arrays in java

• Arrays are used to store multiple values in a single variable,


instead of declaring separate variables for each value.
• The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements.
• To declare an array, define the variable type with square
brackets [].
• Note: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.
Types of Array in java

There are two types of array.


• Single Dimensional Array
• Multidimensional Array
• Single Dimensional Array
A list of items can be given one variable name using only one
subscript & such a variable is called one dimensional array.

Syntax to Declare an Array in Java

datatype arrayname[];
Ex: int n[];

Instantiation of an Array in Java

array_name =new datatype[size];


Ex: n=new int[5];

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.

Syntax to Declare Multidimensional Array in Java


arrayname=new datatype[no. Of Elements] [no. Of Elements]
(OR)
datatype arrayname[][]={
{value1,values2…….},
{value3,values4……}
};

Example to instantiate Multidimensional Array in Java


a=new int[2][3];
Example of Multidimensional Java Array

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

In java we can also pass arrays to methods like variables.

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

An array without any name is known as an anonymous array.


Using an anonymous array, we can pass an array with user values
without the referenced variable.
Properties of Anonymous Arrays:
 We can create an array without a name. Such types of
nameless arrays are called anonymous arrays.
 The main purpose of an anonymous array is just for instant use
(just for one-time usage).
 An anonymous array is passed as an argument of a method.
class AnonymousArrayExample
{
static void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args)
{
// Anonymous array passed directly
printArray(new int[] {10, 20, 30, 40});
}
}
Arrays of Objects
An array of objects is created like a normal array, but instead of
storing primitive data types ,it stores objects of a class.

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.

Rules for creating Java constructor

•Constructor name must be the same as its class name.


•It should be a public member.
•A constructor does not have any return values.
•A Java constructor cannot be abstract, static, final, and
synchronize.
Default Constructor:
A constructor which has no argument is known as default constructor. It is invoked at the
time of creating object.
Purpose of default constructor : It provides default values to the object like 0 , null etc
depending on the dadatype.

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:

A constructor which has parameters is called parameterized constructor.

It is used to provide different values to distinct objects .

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

A method is a block of code which only runs when it is called.


You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also
known as functions.
Why use methods?
To reuse code: define the code once, and use it many times.
Passing parameters to a method
 Information can be passed to methods as a 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 coma(,).

Java program on passing parameters to a 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.

Types of Polymorphism in Java:


In Java Polymorphism is mainly divided into two types:
• Compile-Time Polymorphism (Static binding)
• Runtime Polymorphism (Dynamic binding)
Method overloading
• Compiletime polymorphism also known as static
polymorphism and also known as method overloading.
• when there are multiple methods with the same name but
different parameters then these methods are said to
be overloaded.
Methods can be overloaded in two ways.
 by changes in the number of arguments .
 by a change in the data type of arguments.
By changes in the number of arguments

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

• Constructor overloading means creating multiple constructors in


the same class with different parameter lists. They are differentiated
by the number of parameters and their data types.

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.

Use super.VariableName() to call the parent class instance


variable.

Use super.methodName() to call the parent class method.


Super keyword
In Java the super keyword is a reference variable that is used to refer to the parent class when we are working with
objects.

Solution for instance variable overriding is :


class A
{
public int x=10;
}
class B extends A
{
public int x=10;
Void show()
{
System.out.println(“A class x value= ”+super.x);
System.out.println(“B class x value= ”+x);
}
}
class demo
{
Public static void main(String args[])
{
B obj=new B();
Obj.show();
}
}
Solution for method overriding is

class A public void display()


{ {
public void show() show();//class show() of B
{ super.show();//class show() of A
System.out.println(“show of A
}
class….”);
} }
} class override
class B extends A {
{ public static void main(String args[])
public void show() {
{ B obj=new B();
System.out.println(“show of B obj.display();
class….”);
}
}
}
}
Difference between super keyword ,this keyword

super keyword this keyword


 super refers to the parent  this refers to the current
(superclass) object. class object.
 It is used to access variables  It is used to access variables
and methods of the parent and methods of the current
class. class.
 super() is used to call the  this() is used to call another
constructor of the parent constructor in the same
class. class.
Recursion
Recursion is a process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called a recursive function.

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

 A nested class is a class that is defined inside another class.


 There are two main types of nested classes:
 Static Nested Class :Nested classes that are declared static are called
static nested classes.
 Inner Class :An inner class is a non-static nested class.
Syntax:
class OuterClass
{
. ..
class NestedClass
{
...
}
}
Static Nested Class : A static class is ceated inside a outer class is called static nested
class. It can access the static data members of outer class including private data
members.
class Outer
{
static int x = 10;
int y = 20;
private static int p = 30;
static class Inner
{
void display()
{
System.out.println("x = " + x);
System.out.println("p =”+ p);
// System.out.println("y = " + y);
Outer O = new Outer();
System.out.println("y = "+ O.y);
} } }
class Demo
{
public static void main(String[] args)
{
Outer.Inner Obj = new Outer.Inner();
Obj.display();
Inner class:
class Outer
{
int x = 100;
void test()
{
Inner in = new Inner();
in.display();
}
class Inner
{
void display()
{
System.out.println("Inside Inner Class: " + x);
}
}
}
public class Main {
public static void main(String[] args) {
// Creating an instance of the outer class
Outer out = new Outer();
out.test();
}
}
Strings
String is a predefined class which contains several methods.
class Example
{
public static void main(String[] args)
{
// 1. String Creation
String str1 = "Hello, Java!";
String str2 = "Hello, World!”;

// 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());

// 8. Trim (Remove Whitespaces)


String str5 = " Java Programming ";
System.out.println("Trimmed: '" + str5.trim() + "'");

// 9. Replacing Characters
System.out.println("Replacing 'Java' with 'Python': " + str1.replace("Java",
"Python"));
}
}
Garbage collection

 In Java, memory for an object can be allocated dynamically at runtime


using the new operator.

 When an object is no longer in use or becomes unreferenced, the Garbage


Collector (which is a part of the JVM) automatically destroys the object to
free up memory.

 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.

OOPS Through JAVA

These are the easy to install steps required to install Oracle Java on Windows and write,
compile and execute the Java program.
Thank
You

You might also like