Java Unit 1
Java Unit 1
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
• 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.
• 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.
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.
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.
• 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
• 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
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
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) {
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;
}
}
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.
• 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:
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 {
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:
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){
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.
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:
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: