0% found this document useful (0 votes)
7 views83 pages

Java Unit 1

The document outlines a course on Object Oriented Programming using Java, detailing the course structure, required knowledge, and key concepts such as encapsulation, inheritance, and polymorphism. It also covers Java basics, including the history of Java, its contributions to the internet, and practical examples of Java programming. Additionally, it discusses the Java Development Kit (JDK) and provides examples of Java code for various applications.

Uploaded by

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

Java Unit 1

The document outlines a course on Object Oriented Programming using Java, detailing the course structure, required knowledge, and key concepts such as encapsulation, inheritance, and polymorphism. It also covers Java basics, including the history of Java, its contributions to the internet, and practical examples of Java programming. Additionally, it discusses the Java Development Kit (JDK) and provides examples of Java code for various applications.

Uploaded by

sarveshyogi2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming using JAVA

Course
Course Code 22CI442 Credits L-T-P 2-0-1
type
Hours/week: L-T-P 3-0-2 Total credits 3
Total Contact L = 40Hrs; T = 0Hrs; P = 20Hrs
CIE Marks 100
Hours Total = 60Hrs
Flipped Classes
10 Hours SEE Marks 100
content

Required Knowledge of: Procedure Oriented Programming Languages


Unit – I
• OOP Paradigm: The key attributes of object-oriented programming.
• Java basics: The Java language, JDK, arrays, multidimensional arrays,
alternative array declaration, assigning array references, using the
length member, the for-each loop.
• Introducing classes and objects: Class fundamentals, how objects are
created, reference variables and assignment, String class
OOP Paradigm: The key attributes of object-oriented programming
• Encapsulation: Encapsulation is a programming mechanism that binds together both code and data it
manipulates. When code and data are linked together an object is created. The data is not accessible to outside world
and only those methods which are wrapped in class can access it.
• Data Hiding: Encapsulation allows you to hide the internal details of an object, exposing only the necessary interface to
the outside world.
• achieved through access modifiers (public, private, protected) in many object-oriented languages.

• Information Hiding: It provides a mechanism to control the visibility of object internals, preventing unintended
interference and ensuring data integrity.

• The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
To achieve this, you must:
•declare class variables/attributes as private
•provide public get and set methods to access and update the value of a private variable
Example:
Data Hiding
class Circle {
private:
double radius;
public:
void setRadius(double r) {
if (r >= 0) {
radius = r;
}
}
double getRadius() const {
return radius;
}
};
Information Hiding
class Circle {
private:
double radius;
public:
void setRadius(double r) {
if (r >= 0) {
radius = r;
}
}
double getRadius() const {
return radius;
}
double getArea() const {
return 3.14159265359 * radius * radius;
}
};
Benefits of Encapsulation
• Modularity: Encapsulation promotes modularity, allowing you to break down
complex systems into smaller, more manageable components (objects).

• Security : By restricting access to an object's data, you can control how data
Security is modified and prevent unauthorized changes.

• Ease of Maintenance: Changes to an object's internal implementation can be made


without affecting other parts of the program that use the object's interface.
•Inheritance : Inheritance is the process by which one object can acquire the
properties of another object. In Java, it is possible to inherit attributes and methods from
one class to another. We group the "inheritance concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
• To inherit a class ,use the extend keyword.
Polymorphism
•Polymorphism: Polymorphism means "many forms", or one Interface multiple methods,
and it occurs when we have many classes that are related to each other by
inheritance. Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a
single action in different ways.
(One interface multiple methods)
• Definition: Ability of different objects to respond to the same method or message in their own
unique way.

• Key Aspects:
• Method Overriding: Polymorphism is often achieved through method overriding, where a
subclass provides a specific implementation for a method defined in its superclass.
• Interfaces: Interfaces and abstract classes provide a way to achieve polymorphism by defining
a common set of methods that multiple classes can implement.
Benefits of Polymorphism
• Code Reusability: Polymorphism promotes code reusability by allowing different
classes to share a common interface. This reduces code duplication.

• Flexibility: Polymorphism enables dynamic method invocation, allowing you to


write code that can adapt to different object types at runtime.

• Extensibility: It makes it easier to add new classes that conform to an existing


interface, enhancing the extensibility of a system.
class A {
void display() {
[Link]("Inside class A");
}
}
class B extends A {
@Override
void display() {
[Link]("Inside class B");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
A obj1 = new A();
A obj2 = new B();
[Link](); // Calls the display method of class A
[Link](); // Calls the overridden display method of class B
}
}
Inheritance
• Definition: Inheritance is a mechanism in OOP that allows a new class
(subclass or derived class) to inherit properties and behaviors from an
existing class (superclass or base class).
• The subclass can extend or override the inherited attributes and
methods.
Key Aspects:
• Superclass-Subclass Relationship: Inheritance establishes an "is-a" relationship
between the derived class and the base class.
• Code Reuse: Inheritance promotes code reuse by allowing a subclass to inherit the
attributes and methods of a superclass, reducing redundancy.

Benefits of Inheritance:
• Code Reusability: Inheritance allows you to build new classes based on existing
ones, reducing the need to write similar code from scratch.

• Hierarchy: It helps create class hierarchies that model real-world relationships,


improving the organization of code.

• Polymorphism: Inheritance is closely related to polymorphism, enabling the use of


common interfaces and dynamic method dispatch.
Inheritance(Sample)
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Java basics: The Java language
• The Java was chosen for two primary reasons:
1st it is one of the worlds most widely used computer language.
2nd its features are designed and implemented in such a way that makes it easy to
demonstrate the foundations of programming.

• The Origin of Java


• Java’s Contribution to the Internet
• Java Applets
• Security
• Portability
• Java’s Solution :The Bytecode
• The Evolution of Java.
The Origin of Java
Year Development
1991 Java was conceived by James Gosling & others @ Sun Microsystems in 1991 . It was
initially called “oak’’ by James Gosling. ’’. Oak was renamed “Java”.
Gosling and others began to work on portable ,cross-platform language that could run
on variety of CPU’s under different platform. The WWW (World Wide Web) appeared
on internet due to which Java programs were portable.

1993 Web applets(tiny programs) using the new language that could run on all the types of
computer connected to Internet.
1994 The team developed a Web browser called “Hot Java” to locate & run applet program
on Internet.

1995 Oak was renamed “Java


Java is an island of Indonesia where first coffee was produced.
1996 JDK(Java Development Kit) 1.0 released in January 23,1996.
• Java’s Contribution to the Internet: Java innovated a new type of networked program called
applet, but it had issues with the Internet I,e. Portability and security.

• Java Applets: Applet is a special type of a program that is embedded in the webpage to generate a
dynamic content .It runs inside the browser and works at client side.
Drawbacks :Applets presented a serious challenges interms of Security and Portability.

• Security : Every time when you download the “normal program ‘’ it may contain virus like Torjan
Horse or some harmful code which may cause damage to the system.
✔ Java achieved this protection by confining an applet to the Java execution environment and not
allowing it to access to other parts of the computer.

• Portability: Portability is a major aspect of the Internet because many different types of computer
and operating system are connected to it. When ever a program is downloaded it must be able to
run on that system. Therefore some means of generating portable executable code was needed.
Same mechanism that ensures security also helps create portability.
• Java’s Solution :The Bytecode

• As soon as a Java program is compiled bytecode is generated.


• Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is where JVM comes into
play.
• Byte code is a machine-level language code that runs on the JVM.
• Bytecode adds portability to Java which resonates with the saying, “write once, read anywhere”.
• JVM, loads, verifies and executes Java bytecode. It is known as the interpreter or the core of Java programming
language because it executes Java programming.
• The Evolution of Java: Java is a programming language that was first released in 1995 by
Sun Microsystems (now owned by Oracle).
• Since its initial release, Java has undergone several updates and changes, with the most recent
version being Java 15, which was released in September 2020.

• Some of the major updates and changes to Java over the years include:
Java 1.1 (1997): Introduced the event-delegation model for event handling, inner classes, and JavaBeans.
Java 2 (1998): Included the introduction of the Java Standard Edition (J2SE) and the Java Enterprise Edition
(J2EE).
Java 5 (2004): Introduced generics, annotations, and the for-each loop.
Java 7 (2011): Introduced the try-with-resources statement and the diamond operator for generic types.
Java 8 (2014): Included the introduction of lambda expressions and functional interfaces, as well as the Streams API.
Java 9 (2017): Included the introduction of the Java Platform Module System (JPMS), as well as improvements to
the Java shell (JShell) and the HTTP client.
Java 10 (2018): Introduced local-variable type inference and additional improvements to the JPMS.
Java 11 (2018): Java 11 was the first Long-term support release with a new release cycle, where Oracle releases a
new version every six months, and supports each release for three years. This release introduced the removal of the
JavaEE and CORBA modules, and the introduction of the HTTP client.
Java 12 (2019), Java 13 (2019), Java 14 (2020) and Java 15 (2020) : These releases have introduced new features and
improvements such as new switch expressions, text blocks, and pattern matching for instanceof.
JDK: The Java Development Kit.
• The JDK (Java Development Kit) is a software development kit that develops
applications in Java
• The JDK provides two primary programs.
• First is javac which is a Java compiler which is used to compile java programs, it
takes .java file as input and produces bytecode.
• Following is the syntax of this command .It converts your source code into
bytecode.
javac [Link]
• Second The java command is used to execute the bytecode of java. It takes
byte code as input and runs it and produces the output. Following is the syntax
of this command.
java sample
A First Example
A First Example:
Every application begins with a class name and that class name must match the file name.
Let us first create a Java file as [Link] that prints "Hello, World!" to the console:
public class Example {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Every line of the code must be included inside the class.
The class begins with opening { and closing }braces. The elements between the two braces are
members of class.
public static void main(String[] args) {
The line starts with the public keyword which indicates access modifier.
[Link]: the keyword static allows main() to be executed independently of any object..
[Link]: This is a return type. The main method doesn't return any value, so it is declared with void.
[Link]: This is the name of the method. The main method is the entry point of the Java program. It's
the method that gets executed when you run the program.
If class is private ,which prevents the members from being used by code defined outside of its class.
Main method has one parameter i.e String[] args, which declares the parameter named args. This is an array of
objects of type String. i.e args receives any command line arguments present when the program is executed.

{: This symbol is an opening curly brace, marking the beginning of the main method block. All the code related
to the main method is enclosed within these curly braces.
[Link]("Hello, World!");
The line outputs the string “Hello , World!” followed by new line on the screen.
System – is a predefined class that provides access to the system
out– is an output stream that is connected to the console.
println—displays the string.

}: This closing curly brace marks the end of the main method block.
}: This closing curly brace marks the end of the Example class block.
Converting Gallons to Liters

Explanation:The program begins by declaring a variable gallons and assigning a value of 5 to it .


• The program then performs the conversion by multiplying the number of gallons by the conversion
factor (3.78541) and storing the result in the variable liters..
• Finally, the program prints the result of the conversion to the console using the [Link]
method .
.

WAP in Java to find the largest of 3 numbers


• The program begins by declaring three variables
num1, num2, num3 and assigning values 10, 20,
30 to them respectively.

• The program then declares a variable largest and


assigns the value of num1 to it.

• The program then uses an if-else statement to


check if num2 is greater than largest. If it is, then
the value of num2 is assigned to largest

• The program then uses another if-else


statement to check if num3 is greater than largest. If
it is, then the value of num3 is assigned to largest.

• Finally, the program prints the largest number using


the [Link] method.

• When you run this program, it will display the largest


number among num1, num2 and num3 which are
assigned in the program.
Scanner Class

import [Link].*;
class Main{
public static void main(String[] args) {
String name;
int a;
float b;
double c;
Scanner io=new Scanner([Link]);
name=[Link]();
a=[Link]();
b=[Link]();
c=[Link]();
[Link](name+","+a+","+b+","+c );
}
}
Find the largest of 3 numbers using scanner class

In this program, we are


using a scanner object to
take input from the user for
three numbers. Then using
if-else statement to find the
largest of three numbers
and print the largest
number.
Arrays
• In Java, an array is an object which is a collection of elements of the same data type.
The elements of an array are stored in contiguous memory locations, and each element can
be accessed by its index.
• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on. We can store only a fixed set of elements in a Java
array.
• Like C/C++, we can also create single-dimensional or multidimensional arrays in Java.
Advantages
•Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
•Random access: We can get any data located at an index
position.

Disadvantages
•Size Limit: We can store only the fixed size of elements in
the array. It doesn't grow its size at runtime. To solve this
problem, a collection framework is used in Java which
grows automatically.
One Dimensional Array
Syntax to Declare an Array in Java
datatype arrayName[] = new datatype[size];
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
• datatype: is the type of the elements that we want to enter in the array,
like int, float, double, etc.
• arrayName: is an identifier.
• new: is a keyword that creates an instance in the memory.
• size: is the length of the array.
// Declaring an array example
int[] myArray;
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
// Initializing an array
myArray = new int[5];
public class Main{
public static void main(String[] args) {

int myarray[]; //Declaring an array

myarray= new int[5]; //Initializing an array//

//Assign values to the array


myarray[0]=1;
myarray[1]=2;
myarray[2]=3;

//Accessing elements of an array


for(int i=0;i<3;i++)
[Link](myarray[i]);
}
}
Example of Java Array
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Main{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++) //length is the property of array
[Link](a[i]);
}
}
//Let's create a program that takes a single-dimensional array as input
import [Link];
public class scanne1 {
public static void main(String[] args) {
int n;
Scanner sc= new Scanner([Link]);
[Link]("Enter how many elements you want to store");
n=[Link](); //The nextInt() method scans the next token of the input data as an “int”.
int[] array =new int[10];
[Link]("Enter the elements of array");
for(int i=0;i<n;i++){
array[i]= [Link]();
}
[Link]("Array elements are");
for(int i=0;i<n;i++)
{
[Link](array[i]);
}
}
}
import [Link];
public class Main {
public static void main(String[] args) {
int n;
Scanner sc= new Scanner([Link]);
[Link]("Enter how many elements you want to store");
n=[Link](); //The nextInt() method scans the next token of the input data as an “int”.

int[] array =new int[10];


[Link]("Enter the elements of array");
for(int i=0;i<n;i++){
array[i]= [Link]();
}

[Link]("Array elements are");


for(int i=0;i<n;i++)
{
[Link](array[i]);
}
}
}
import [Link]; Find the minimum and maximum value in an array
public class Main {
public static void main (String[] args) {
int[] nums=new int[10];
int min , max , n;
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of elements you want to store: ");
n= [Link]();
[Link]("Enter the elements of the array: ");
for(int i=0; i<n ; i++)
nums[i]=[Link]();
[Link]("Array elements are: ");
for(int i=0 ; i<n ; i++) {
[Link](nums[i]); }
min=max=nums[0];
for (int i=1;i<n; i++) {
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i]; }
[Link]("Min value from array is =" + min + " and Max value from array is =" + max);
} }
Find minimum and maximum to from array without using scanner
function.
• Array boundaries are strictly enforced in Java.
• It is run time error to over run or under run an array.
• For example demonstration of ARRAY OVERRUN

class ArrayErr{
public static void main(String[] args) {
int[] sample =new int[10];
int i;
// generate an array over run
for(i=0;i<100;i++)
sample[i]= i;
}
}

As soon as i reaches 10, an ArrayIndexOutOfBoundsException is generated and the


program is terminated.
Sorting an Array using Bubble sort.
public static void bubbleSort(int[] arr) {
public class Main { int n = [Link];
public static void main(String[] args) { boolean flag;
int[] arr = {12,02,53,74,15}; for (int i = 0; i < n - 1; i++) {
flag = false;
[Link]("Original Array:"); for (int j = 0; j < n - i - 1; j++) {
printArray(arr); if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
bubbleSort(arr); int temp = arr[j];
arr[j] = arr[j + 1];
[Link]("Sorted Array:"); arr[j + 1] = temp;
printArray(arr); flag = true;
} }
}
// If no two elements were swapped in inner loop, the array is
already sorted
if (!flag) {
break;
}
}
}
public static void printArray(int[] arr) {
for (int value : arr) {
[Link](value + " ");
}
[Link]();
}
}
Binary Search

class Main {
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int keyelem = 2;
int result = binarySearch(myArray, keyelem);
if (result == -1) {
[Link]("Element not found");
} else {
[Link]("Element found at index: " + result);
}
}
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
Multidimensional Array
• In Java, a multidimensional array is an array of arrays. It can be used to represent
a table with rows and columns, or a matrix, or a grid.

• Example of how to declare and initialize a two-dimensional array in Java


int[][] myArray = new int[3][3];
• This creates a 2-dimensional array with 3 rows and 3 columns. Each element of
the array is initialized with the default value for the int data type, which is 0.

Syntax to Declare and Initialize a two-dimensional array :


int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
• In this example, the array named "myArray" is being declared as a 2-dimensional
array of integers, and it is being initialized with the values 1, 2, 3, 4, 5, 6, 7, 8, 9.
Assigning array references
• In Java, arrays are objects that store multiple values of the same data type. You can
create an array by specifying the type of data it will hold, followed by square
brackets and the name of the array. For example, to create an array of integers
called "numbers", you would use the following syntax:
• int[] numbers;

• You can also initialize an array when you create it by specifying its size and the
values it will hold. For example:
• int[] numbers = {1, 2, 3, 4, 5};

• Once you have an array, you can access its elements by using the array name
followed by the index of the element in square brackets. For example:
• [Link](numbers[0]); // prints 1
• You can also assign new values to specific elements of an array using
the same syntax:
• numbers[0] = 10;
• You can also create a reference to an array using the same syntax.
• int[] numbers = {1, 2, 3, 4, 5};
• int[] copy = numbers;

.
Using the length member
length is an instance variable that contains the size of array.

Example:
int[ ] a={10,20,30,40,50};
int len = [Link] //get the size of array.
[Link](len); //outputs 5
for-each loop
• In Java, the for loop and the for-each loop (also known as the enhanced for loop) are both used to
iterate over the elements of an array or any other iterable object.
• The syntax for a for each loop (also known as a "for each" loop) is as follows:

for (type variable : collection) {


// code to be executed
}

•‘type’ is the data type of the items in the collection.


•‘variable’ is the variable that will be assigned the value of each item in the collection, one at a
time.
•‘collection ‘ is the collection of items over which the loop will iterate. This could be an array, a
list, a set, or any other type of collection.
• For example, the following for each loop iterates over an array of integers and
prints each value:
• int[ ] numbers = {1, 2, 3, 4, 5};
• for (int num : numbers) {
• [Link](num); }

• //The output would be


• 1
• 2
• 3
• 4
• 5
• It's important to note that the for-each loop is used for only iterating over elements
of an array or collections, it can't be used to iterate over the range of integers or
anything like that.
Q. Write a program to add sum of array using for-each loop.

public class ForEach {


public static void main(String[] args) {
int [] nums={1,2,3,4,5,6,7,8,9,10};
int sum=0;
//use for each loop to display and sum the value.
for(int x:nums){
[Link](x);
sum=sum+x;
}
[Link]("Summation =" +sum);
}
}
• Write a Java program display a pattern as shown below using a looping
structure.
1
22
333
4444
55555
public class Main {
public static void main(String[] args) {
int rows = 5; // Number of rows in the pattern

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
[Link](i);
}
[Link]();
}
}
}
• Define the process of building and running Java program. And write a
Java program to accept a number and check whether it is prime or
not.
import [Link].*;
class Main{
public static void main(String[] args) {
int n=9;
boolean prime = true;
for(int i=2;i<n;i++){
if(n%i==0){
prime=false;
break;
}
}
[Link]("Number "+n +" is Prime - "+prime);
}
}
import [Link];
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();

if (isPrime(number)) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}
}
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= [Link](number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
WAP in Java to check weather a given 3 digit number is palindrome or
not
import [Link].*;
class Main{
public static void main(String[] args) {
int num=678,original,reverse=0,rem;
original=num;
while(num>0) {
rem=num%10;
reverse=reverse*10+rem;
num=num/10; }
if(original==reverse)
[Link]("The given Number "+original +" is Palindrome");
else
[Link]("The given Number "+original+" is Not Palindrome");
} }
•Write a Java program display a pattern as shown
below using a looping structure
class Main {

public static void main(String args[]) {


int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k; k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
Introducing classes and objects:
The General Form of a Class
class Vehicle{
int passengers; class SimpleIntrest{
int fulecap;
double p,t,r;
int mpg;
double calcSI() {
}
return (p*t*r)/100;
}
}
How objects are created

In Java, objects are created using the new keyword, followed by the
constructor of the class.
The general syntax for creating an object is as follows:
ClassName objectName = new ClassName(parameters);
• ‘className’ is the name of the class.
• ‘objectName’ is the name of the object (variable) that refers to the created
object.
• ‘new ClassName(parameters)’ is a call to the constructor of the class,
passing in any necessary parameters.
For example, using the Student class , we can create an object of the class as follows:

Student student1 = new Student("John",20,"Computer Science");

Accessing class members


Once an object is created, we can call its methods or access its fields using the dot (.)
operator.

The general form of the dot operator is


[Link]

For example,
[Link]([Link]());
/*program that uses the vehicle class*/
class Vehicle{
int passengers;
int fulecap;
int mpg;
}
Class VehicleDemo{
public static void main(String[] args){
Vehicle minivan= new Vehicle();
int range;
[Link]=7;
[Link]=16;
[Link]=21;
//compute the range assuming full tank of gas
range= [Link]*[Link];
[Link](“Minivan can carry”+[Link]+ ”with a range of “+range);
class Calculator {
int x,y;

int Sum() {
return x+y;
}
}
public class Main{
public static void main(String[] args) {
Calculator calc = new Calculator(); calc.x = 10;

calc.y =20;
[Link]("Sum is:"+[Link]());
}
}
import [Link]; SI s = new SI();
class SI{ s.p = pi;
double p,t,r; s.t= ti;
double calcSI(){ s.r = re;
return (p*t*r)/100; interest = [Link]();
} [Link]("Interest is:"+interest);
} }
public class Main{ }
public static void main(String[] args){
double pi,ti,re, interest;
Scanner sc = new Scanner([Link]);

pi = [Link]();
ti = [Link]();
re = [Link]();
import [Link];
class SI{
double calcSI(int p,int t , int r){
return (p*t*r)/100;
}
}
public class Main{
public static void main(String[] args){

double pi,ti,re, interest;

SI s = new SI();
interest = [Link](100,10,5);
[Link]("Interest is:"+interest); }
}
Methods
• Methods are the subroutines that manipulates the data defined by the class and
in many cases control access to that data.
• main() is reserved for the method that begins execution of the program.

• The general form is as shown here:


return-type name(parameter list)
{
//body of method
}
Reference variables and assignment
∙ When one primitive-type is assigned to another, i.e., the statements int x=y means that
• x receives a copy of the value contained in y.
∙ Hence, after the assignment, both x and y will contain their own, independent copies of the value. Changing one
does not affect the other.
∙ But, when one object variable is assigned to another, the situation is bit different because you are assigning
references.
∙ This means that you are changing the object that the reference variable refers to, not making a copy of that
object
∙ For example,
Box b1=new Box();

Box b2=b1;


In this case b1and b2 will both refer to the same object. Therefore, object can be changed through b1 or b2.

• [Link] = 12;
• [Link]([Link]);
• [Link]([Link]);
∙ After executing both of these println() statements, we get the same value for both the statements as 12.
STRINGS
• In Java, a string is defined as an object
• Constructing Strings: by using new keyword and calling a string constructor
For example:
String str1 = "Hello World"; //Using String literal
String str2 = new String("Hello World"); //Using new operator
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
String str3 = new String(charArray);
Example:
class Main {
public static void main(String args[]) {
String str1 = new String("hello");
String str2 = new String(str1);
String str3 = "Well come to Java";
[Link](str1);
[Link]( str2+"\n"+ str3);
}
}
Once a String object is created, you can perform various operations
on it such as:

• Concatenation using the "+" operator or the concat() method


• Comparison using the equals() method or the "==" operator
• Finding the length of a string using the length() method
• Extracting a substring using the substring() method
• Replacing part of a string using the replace() method
• Converting to lowercase or uppercase using the toLowerCase() or
toUpperCase() method
etc.
• Few examples are:
String str1 = "Hello";
String str2 = "World";
String str3 = str1 + " " + str2; // "Hello World"
[Link]([Link]()); // 5
[Link]([Link](0, 5)); // "Hello"
[Link]([Link]()); // "HELLO WORLD"
No. Method Description
1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length


3 boolean equals(str) It checks the equality of string with the given string.
4 boolean isEmpty() It checks if string is empty.
5 String concat(String str) It concatenates the specified string.

7 int compare To(str) Returns less than 0 if the invoking string is less than str, greater than zero if the
invoking string is greater than str, and zero if the string are equal.
8 int indexOf(str) Searches the invoking string for the substring specified by str. Returns the
index of the first match or 1 on failure.
Program on String Operations
public class StrOps {
public static void main(String[] args) {
String str1="when it comes to web programming ,java is
if(result== 0)
1"; [Link]("string1
String str2 =new String(str1); and 3 are equal");
String str3="Java strings are powerfull";
else if(result<0)
[Link]("string1
int result,idx;
is less than string3");
char ch;
else
[Link]("length of str1 " + [Link]()); [Link]("string1
//display str1 , one character at a time is greater than string3");
for(int i=0;i<[Link]();i++) //assign a new string to str2
[Link]([Link](i)); str2="One Two Three One";
[Link](); idx=[Link]("one");
[Link]("Index of
if([Link](str2))
first occurance of One:" +idx);
[Link]("str1 equals str2");
idx=[Link]("one");
else [Link]("Index of
[Link]("str1 does not equals str2"); first occurance of One:" +idx);
if([Link](str3)) }
[Link]("string1 equals string3"); }
Output:

• Length of str1: 45
• when it comes to web programming ,java is 1
• str1 equals str2
• string1 does not equals string3
• string1 is greater than string3
• Index of first occurance of One: 0
• Index of first occurance of One: 14
Arrays Of Strings
• Like any other data type strings can be assembled into arrays.
For example:
• public class StringArrays {
• public static void main(String[] args) {
OutPut:
• String[] strs={"This" , "is" , "a" , "test."};
• [Link]("Original array"); Original array
• for (String s:strs) This is a test.
• [Link](s + " ");
• [Link]("\n"); Modified array:
• //change a string in the array This was a test,too !
• strs[1]="was";
• strs[3]="test,too !";
• [Link]("Modified array:");
• for (String s:strs)
• [Link](s + " "); } }
Strings are Immutable
• Java, strings are immutable, meaning their value cannot be changed
once they are created.
• This means that any operations that appear to change the value of a
string, such as concatenation or replacement, will actually create a
new string object with the modified value.
• This can have an impact on performance and memory usage, as
multiple copies of the same string may exist in memory.
• However, it also provides a level of security and consistency, as the
original string remains unchanged and any changes can be tracked
and controlled.
Using a string to control a switch statement
• A string can be used to control a switch statement in Java by using the string as the
expression in the switch statement. For example, here is a sample switch statement
that uses a string variable called "input" to control the flow of the program:

• Here the string contained in input


and it is tested against the case
constants.
• When a match is found the code
sequence associated with that string
is executed.
• Explain the following terms with respect to string in JAVA.
charAt()
indexOf()
compareTo()
toCharArray()
toLowerCase()
• What is the difference between a class and an object? How is class
defined in JAVA? Write a Java program to define a class called
myTriangle to model a triangle geometrical object with three sides.
Include functions to:
• Initialize the three sides of triangle.
• Compute and return the area of the triangle.

You might also like