Basics of Java Programming
Basics of Java Programming
22CS33 / Course
Course Code IPCC Credits L-T-P 3 - 0- 1
22IS33 type
Hours/week: L-T-P 3 - 0 - 2 Total credits 4
Total Contact L = 40Hrs; T = 0Hrs; P = 20Hrs
CIE Marks 100
Hours Total = 60Hrs
Flipped Classes
10 Hours SEE Marks 100
content
IA Test:
1. No objective part in IA question paper
2. All questions descriptive
Conduct of Lab:
1. Conducting the experiment and journal: 5 marks
2. Calculations, results, graph, conclusion and Outcome: 5 marks
3. Viva voce: 5 marks
Lab test: (Batchwise with 15 students/batch)
1. Test will be conducted at the end of the semester
2. Timetable, Batch details and examiners will be declared by Exam section
3. Conducting the experiment and writing report: 5 marks
4. Calculations, results, graph and conclusion: 10 marks
5. Viva voce: 10 marks
Eligibility for SEE:
1. 40% and above (24 marks and above) in theory component
2. 40% and above (16 marks and above) in lab component
3. Lab test is COMPULSORY
4. Not eligible in any one of the two components will make the student Not Eligible for SEE
Scheme of Semester End Examination (SEE):
1. It will be conducted for 100 marks of 3 hours duration
2. Minimum marks required in SEE to pass: 40 out of 100
3. Question paper contains two questions from each unit each
carrying 20 marks. Students have to answer one full question
from each unit.
Unit – I Contact Hours = 8 Hours
• 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.
• 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:
• Inheritance : 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.
• Information Hiding: Hide methods or data should not
be easily accessible or restricted access.
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
• Note: The JDK runs in the command prompt environment and uses command line tools.
It is not a windowed application, It is also not an integrated development
environment(IDE).
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 Example.java that prints "Hello, World!" to the console:
public class Example {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Every line of the code must be included inside the class.
Java is case sensitive. i.e Example and example are different.
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.
If class is private ,which prevents the members from being used by code defined outside of its class.
The main method is the entry point of the program. It is where the program starts executing
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.
System.out.println("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.
Converting Gallons to Liters
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];
Example of Java Array
• /Java Program to illustrate how to declare, instantiate, initialize
• //and traverse the Java array.
• class Testarray{
• 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<a.length;i++)//length is the property of array
• System.out.println(a[i]);
• }}
//Let's create a program that takes a single-dimensional array as input
import java.util.Scanner;
public class scanne1 {
public static void main(String[] args) {
int n;
Scanner sc= new Scanner(System.in);
System.out.println("Enter how many elements you want to store");
n=sc.nextInt(); //The nextInt() method scans the next token of the input data as an “int”.
int[] array =new int[10];
System.out.println("Enter the elements of array");
for(int i=0;i<n;i++){
array[i]= sc.nextInt();
}
System.out.println("Array elements are");
for(int i=0;i<n;i++)
{
System.out.println(array[i]);
}
}
}
Find the minimum and maximum value in an array
import java.util.Scanner;
public class MinMax { min=max=nums[0];
public static void main (String[] args) { for (int i=1;i<n;i++) {
if(nums[i]<min)
int[] nums=new int[10];
min=nums[i];
int min , max , n; if(nums[i]>max)
Scanner sc = new Scanner(System.in); max=nums[i]; }
System.out.println("Min And
System.out.println("Enter the number of elements you want Max=" + min + " " + max); } }
to store: ");
n= sc.nextInt();
System.out.println("Enter the elements of the array: ");
for(int i=0;i<n ; i++)
nums[i]=sc.nextInt();
System.out.println("Array elements are: ");
for(int i=0 ; i<n ; i++) {
System.out.println(nums[i]); }
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 int binarySearch(int[] arr, int target) {
public static void main(String[] args) {
int left = 0;
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int right = arr.length - 1;
int target = 6; while (left <= right) {
int mid = left + (right - left) / 2;
int result = binarySearch(myArray, target);
if (arr[mid] == target) {
if (result == -1) { return mid;
System.out.println("Element not found"); }
} else if (arr[mid] < target) {
left = mid + 1;
{ } else {
System.out.println("Element found at right = mid - 1;
index: " + result); }
} }
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:
• System.out.println(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.
int myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Output: 5
// console.log() is a function in JavaScript that is used to print or output data to the
console.
Example:
int[ ] a={10,20,30,40,50};
int len = a.length //get the size of array.
system.out.println(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. However, they work slightly
differently and have different use cases.
• A traditional for loop uses an index variable to iterate over the elements of an array. Here is an
example of a for loop that iterates over the elements of an int array
• The syntax for a for each loop (also known as a "for each" loop) is as follows:
For example, using the Student class that I provided in the previous response, we can create an object of the class
as follows:
Once an object is created, we can call its methods or access its fields using the dot (.) operator.
For example,
System.out.println(student1.getName());
Reference variables and assignment
• In Java, when a variable is assigned the value of an object, it is actually assigned a
reference to that object. This means that the variable holds a memory address that
points to the location of the object in memory.
For example:
Vehicle car1=new vehicle();
Vehicle car2=car1;
Vehicle car3=new vehicle();
Car2=car3;// now car2 and car3 refer to the same object, but object referred by car1 is unchanged
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
}
STRINGS
• In Java, strings are objects of the String class, which is part of the Java standard library. They are used to
represent text and are commonly used in Java programs.
Constructing Strings: by using new keyword and calling a string constructor
For example:
String str1 = "Hello World";
String str2 = new String("Hello World");
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
String str3 = new String(charArray);
• 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"
System.out.println(str1.length()); // 5
System.out.println(str3.substring(0, 5)); // "Hello"
System.out.println(str3.toUpperCase()); // "HELLO WORLD"
No. Method Description
1 char charAt(int index) It returns char value for the particular index
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
if(result== 0)
is 1"; System.out.println("string1
String str2 =new String(str1); and 3 are equal");
String str3="Java strings are powerfull";
else if(result<0)
System.out.println("string1
int result,idx;
is less than string3");
char ch;
else
System.out.println("length of str1 " + str1.length()); System.out.println("string1
//display str1 , one character at a time is greater than string3");
for(int i=0;i<str1.length();i++) //assign a new string to str2
System.out.print(str1.charAt(i)); str2="One Two Three One";
System.out.println(); idx=str2.indexOf("one");
System.out.println("Index of
if(str1.equals(str2))
first occurance of One:" +idx);
System.out.println("str1 equals str2");
idx=str2.lastIndexOf("one");
else System.out.println("Index of
System.out.println("str1 does not equals str2"); first occurance of One:" +idx);
if(str1.equals(str3)) }
System.out.println("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."};
• System.out.println("Original array"); Original array
• for (String s:strs) This is a test.
• System.out.print(s + " ");
• System.out.println("\n"); Modified array:
• //change a string in the array This was a test,too !
• strs[1]="was";
• strs[3]="test,too !";
• System.out.println("Modified array:");
• for (String s:strs)
• System.out.print(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: