JAVA
NAYANA VAIDYA
CHAPTER 1
◼ 5 important aspects of programming language are—
◼ Way it stores data
◼ How it takes input
◼ How it shows output
◼ How it operates on the data
◼ How it executes the instructions in a program
◼ Java data types
◼ What is the type of data
◼ What operations can be performed on the data
◼ Integer data type –addition,subtractions,multiplication,division etc
◼ Boolean data type ---comparison
◼ Primitive ---they are created on stack(ex:integer)-those that occupy less memory
◼ Reference data types-they are stored in heap(string)-those that occupy more memory
◼ Data types are also predefined and userdefined
◼ Primitive-Predefined-integers ,reals,characters,Booleans
◼ Primitive-userdefined-enumerations
◼ Reference types-predefined-objects,strings
◼ Reference types-userdefined-classes,arrays,interfaces
◼ In order to use a data type we have to create,constant and variable
◼ Variable is a name given to a memory location x=5
◼ Constant is a fixed value
◼ Constant is also called as a literal
◼ Variable is also known as an identifier
◼ Rules for creating constants
◼ No commas or blanks are allowed
◼ Only a float constant can contain a decimal point ex:1.2f
◼ Character constant-single alphabet or single digit or special char enclosed within single quotes
RULES FOR CONSTRUCTING VARIABLE NAMES
◼ No commas or blanks are allowed in a variable name
◼ It can contain alphabets,digits or underscores or $
◼ It can begin with an alphabet or underscore
◼ Variable names are case sensitive
◼ If variable names are having 2 words then camel case notation is followed or connected by _
◼ ex: averageSpeed or avg_speed
◼ Avoid creating long variable names
◼ Variable names must be meaningful ex: Principal,roi,noy rather than a,b,c
JAVA KEYWORD
◼ Keywords are the words in java which have special meaning
◼ Ex: int age here int is a keyword
◼ There are 48 keywords in java
◼ Keywords cannot be used as variable names
◼ First java program
◼ A java program is a series of statements terminated by ;
◼ All statements are in small case
FIRST JAVA PROGRAM
◼ //calculation of simple interest
◼ /* formula for simple interest si=p*n*r/100 */
◼ Package calofsi;
◼ Public class SimpleInterest{
◼ Public static void main(String args[])
◼ {
◼ Float p,r,si; //declaration
◼ Int n; //declaration
◼ P=1000.50f;
◼ R=15.5f;
◼ N=5;
◼ Si=p*n*r/100;
◼ [Link](si)
◼ }
◼ }
◼ Once we create a program we need to compile it.
◼ To compile a java program we should have jdk installed on machine
◼ To write java program we can use netbeans or eclipse
ANOTHER PROGRAM
◼ //calculation of average of 3 numbers
◼ Package calofavg;
◼ Public class Average{
◼ Public static void main(String args[])
◼ {
◼ Int a,b,c,avg; //declaration
◼ A=10;
◼ B=20;
◼ c=30;
◼ Avg=(a+b+c)/3;
◼ [Link](avg)
◼ }
◼ }
DATA TYPES REVISITED
◼ Integer types –number without a decimal point is called as int
◼ Byte =1 byte
◼ Short =2bytes
◼ Int =4bytes
◼ Long =8bytes
◼ Long int a=3651000000
◼ Real numbers
◼ Float -4bytes
◼ Double -8bytes
◼ Float a=3.5f or double d=3.5 or double d=3.5f or double d=3d
◼ Character data type
◼ Represents a character in Unicode format
◼ Char ch=‘\u0000’ decimal 0 or ch=‘\uffff’ ie decimal number 65535
◼ Boolean data type
◼ Can take values true and false
◼ Boolean a=true
◼ Boolean b=4>2
RECEIVING INPUT FROM KEYBOARD
◼ Calculation of simple interest by taking input from user
◼ //calculation of simple interest
◼ /* si=p*n*r/100 */
◼ Package calofsiint;
◼ Public class SimpleInterest{
◼ Public static void main(String args[])
◼ {
◼ Float p,r,si;
◼ Int n;
◼ [Link](“enter values of p,n,r”);
◼ BufferedReader br=new BufferedReader(new InputStreamReader([Link]))
◼ P=fl[Link]float([Link]());
◼ N=[Link]([Link]());
◼ R= fl[Link]float([Link]());
◼ Si=(p*n*r)/100;
◼ }
◼ }
◼ To read a character from keyboard we use
◼ Char ch;
◼ BufferedReader br=new BufferedReader(new InputStreamReader([Link]))
◼ Ch=(char)[Link]();
◼ Decision control instruction
◼ Decision control is possible through if else and conditional operators
◼ To express condition we need relational operators
◼ Relational operators in java
◼ X==y x>y x<y x!=y x<=y x>=y
◼ Usage of relational operators using a simple program
◼ In a company an employee is paid as under
◼ If his basic salary is less than 1500 hra=10% of basic salary
◼ Da=90% of basic salary
◼ If salary is equal to or greater than 1500 then
◼ Hra=1200 da=98% of basic salary
◼ If the employees salary is input through keyboard write a program to find his gross salary
◼ //calculation of gross salary
◼ Float bs
◼ If(bs<1500)
◼ {
◼ Hra=(bs*10)/100;
◼ Da=(bs*90)/100;
◼ }
◼ Else
◼ {
◼ Hra=1200;
◼ Da=(98*bs)/100;
◼ }
◼ Gs=hra+da+bs;
◼ Logical operators
◼ &&
◼ ||
◼ !
◼ If(per>=60)
◼ [Link](“first division”)
◼ If(per>=50 && per<60)
◼ [Link](“2nd division”)
◼ If(per>=40 && per<50)
◼ [Link](“3rd division”)
◼ If(per<40)
◼ [Link](“fail”)
◼ Else if ladder
◼ If(per>=60)
◼ [Link](“first division”)
◼ Else If(per>=50 )
◼ [Link](“2nd division”)
◼ Else If(per>=40)
◼ [Link](“3rd division”)
◼ else
◼ [Link](“fail”)
◼ Last else is optional
◼ If one condition is true other conditions are not checked
◼ Int a=1,b=1,c=5,d;
◼ If(a>3 && (b=c+4)>1)
◼ D=35
◼ [Link](b)
◼ The statement (b=c+4)>1) does not get executed as a>3 [Link] is known as shortcircuiting
◼ To avoid this we can use
◼ If(a>3 & (b=c+4)>1)
◼ D=35
◼ In this case both conditions are always checked
◼ Conditional operators
◼ ? And : are also called as ternary operators
◼ This is shortcut for if else
◼ Expression1?expression2:expression3
◼ Int x=8,y;
◼ Y=x>5?3+4:4+7
◼ (x%2==0)?[Link](“even”): [Link](“even”)
◼ A=10 b=3
◼ Max=(a>b)?a:b
◼ Find largest of 3 numbers
◼ Int a,b,c
◼ Big=a>b?(a>c?a:c):(b>c?b:c)
◼ Limitation of the conditional operator is after ? Or : only one statement can occur
LOOPS
◼ While loop
◼ //calculate simple interest for 3 sets of numbers
◼ Public class simple{
◼ Public static void main(String args[])
◼ {
◼ Float p,r,si;
◼ Int n;
◼ Int count=1;
◼ While(count<3)
◼ {
◼ [Link](“enter values of p,n,r”);
◼ BufferedReader br=new BufferedReader(new InputStreamReader([Link]))
◼ P=fl[Link]float([Link]());
◼ N=[Link]([Link]());
◼ R= fl[Link]float([Link]());
◼ Si=(p*n*r)/100;
◼ Count++;
◼ }
◼ }
◼ }
◼ ++ increment operator
◼ - - decrement operator
◼ compound assignment operator
◼ -=
◼ *=
◼ /=
◼ +=
◼ %=
SWITCH
◼
CASE
You can make decision from a number of choices
◼ Int i=2;
◼ Switch(i)
◼ {
◼ Case 1:
◼ [Link](“ I am in case 1”);
◼ Break;
◼ Case 2:
◼ [Link](“ I am in case 2”);
◼ Break;
◼ Case 3:
◼ [Link](“ I am in case 3”);
◼ Break;
◼ default:
◼ [Link](“ I am in default”);
◼ Break;
◼ }
◼ Cases in switch can be written in any order
◼ Break is mandatory
◼ Even if there are multiple statements in case there is no need to enclose them in braces
◼ Default is not compulsory
◼ After the case we can have a byte,short,int,char or string:
◼ Advantage of switch is that we can have a more structured program
◼ Switch(i+j+k) is valid
◼ Case 3+7: is correct,
◼ Case a+b is not allowed
◼ Switch statement is useful while writing menu driven programs
◼ A float,double,Boolean or long expression cannot be tested using a switch
◼ Switch works faster than an if else ladder
◼ Public static void main()
◼ {
◼ Char ch;
◼ [Link](“enter an alphabet”)
◼ Ch=[Link]();
◼ Switch(ch)
◼ {
◼ Case ‘a’:
◼ Case ‘A’:
◼ [Link](“ a is in America”);
◼ Break;
◼ Case ‘b’:
◼ Case ‘B’:
◼ [Link](“ b is in bombay”);
◼ Break;
◼ }
◼ }
◼ }
INTRODUCTION TO OOPS
◼ Function in java
◼ Uptil now we have seen main function
◼ But a program in java can have multiple functions
◼ What is a function-it is a set of steps which are doing some task
◼ Execution of java program begins with main function
◼ Public class functiondemo{
◼ public static void main(String args[])
◼ {
◼ Message();
◼ [Link](“back in main”);
◼ }
◼ Static void message()
◼ {
◼ [Link](“this is a message”);
◼ }
◼ }
◼ Public class Multiplefunctiondemo{
◼ public static void main(String args[])
◼ {
◼ [Link](“ I am in main”)
◼ Italy();
◼ Brazil();
◼ Argentina();
◼ }
◼ Static void italy()
◼ {
◼ [Link](“I am in italy”);
◼ }
◼ Static void italy()
◼ {
◼ [Link](“I am in italy”);
◼ }
◼ }
◼ Public class function calss{
◼ Public static void main()
◼ {
◼ [Link](“ I am in main”)
◼ Italy()
◼ [Link](“ I am back in main”)
◼ }
◼ Static void Italy()
◼ {
◼ [Link](“ I am in italy”)
◼ Brazil()
◼ [Link](“ I am back in italy”)
◼ }
◼ Static void brazil()
◼ {
◼ [Link](“ I am in brazil”)
◼ Argentina()
◼ }
◼ Static void Argentina(){[Link](“ I am in argentina”)}}
◼ A function can call itself ----recursion
◼ There are 2 types of functions
◼ Library functions
◼ User defined functions
◼ Passing values between functions
◼ Public class A{
◼ Public static void main()
◼ {
◼ Int a,b,sum;
◼ BufferedReader br=new BufferedReader(new InputStreamReader([Link]))
◼ [Link](“enter 2 numbers a and b”)
◼ A=[Link]([Link]())
◼ B=[Link]([Link]())
◼ Sum(a,b);
◼ }
◼ Static int sum(int x,int y)
◼ {
◼ Sum=a+b;
◼ [Link](“sum=“+sum)
◼ }
◼ }
◼ If the value of the formal argument is changed in the called function it does not change the value in the
calling function
◼ Public class A{
◼ Public static void main()
◼ {
◼ Int a=30;
◼ Func(a);
◼ [Link](a)
◼ }
◼ void func(int b)
◼ {
◼ B=60;
◼ [Link](b)
◼ }
◼ }
RECURSION
◼ In java a function can call itself
◼ A function is called recursive if the statement in the body of function calls the same function
◼ Public class Main{
◼ Public static void main(String args[])
◼ {
◼ Int a,fact;
◼ BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
◼ [Link](“enter a number”);
◼ A=[Link]();
◼ Fact =rec(a);
◼ [Link](“factorial value=“+fact);
◼ }
◼ }
◼ Static int rec(int x)
◼ {
◼ Int f;
◼ If(x==1)
◼ Return 1;
◼ Else
◼ F=x*rec(x-1)
◼ Return(F)
◼ }
◼ Suppose x=4
◼ F=4xrec(3)=4x3xrec(2)=4x3x2xrec(1)=4x3x2x1=24
INTRODUCTION TO OOP
◼ Structured programming-programming divided into functions
◼ Program is created in terms of objects and classes
◼ The basic idea behind OOPs is to combine data and functions into a single unit called object
◼ The objects communicate through function calls
◼ The way to access data of object is through functions
◼ A java program consists of a number of objects which communicate with each other by calling each
others methods
OOPS CONSISTS OF THE FOLLOWING-----
◼ Data hiding
◼ Encapsulation
◼ Inheritance
◼ Containership
◼ Polymorphism
◼ Templates
◼ Exception handling
◼ Objects
◼ Employees of company
◼ Students of college
◼ Gui elements like windows,menus
◼ Classes
◼ A class serves as template or blueprint for objects
◼ Inheritance
◼ In inheritance one class derives from other class
◼ The new class the derived class inherits the data and functions from the base class
◼ The new class can add its own data members and functions
◼ Polymorphism
◼ A single name can be used for 2 or more functions doing the same task
◼ Containership
◼ Containership is the concept in OOP
◼ where an object of one class is used as a data member inside another class.
◼ // Engine class
◼ class Engine {
◼ void start() {
◼ [Link]("Engine started");
◼ }
◼ }
◼ // Car class contains Engine object
◼ class Car {
◼ Engine eng = new Engine(); // Containership
◼ void drive() {
◼ [Link]();
◼ [Link]("Car is moving");
◼ }
◼ }
◼ public class Main {
◼ public static void main(String[] args) {
◼ Car c = new Car();
◼ [Link]();
◼ }
◼ }
◼ Objects like cold cream,facewash,shampoo are inside a category object called cosmetics
UNIT 2
◼ Reference Variables
◼ In Java, when you create an object, a reference variable stores the memory address of that object (not the actual
object itself).
◼ class Car {
◼ String color = "Red";
◼ }
◼ public class Main {
◼ public static void main(String[] args) {
◼ Car c1 = new Car(); // c1 is a reference variable
◼ Car c2 = c1; // c2 refers to the same object as c1
◼ [Link] = "Blue";
◼ [Link]([Link]); // Output: Blue
◼ }
◼ }
◼ class Animal {
◼ void sound() {
◼ [Link]("Animals make sounds");
◼ }
◼ public static void main(String[] args) {
◼ Animal a = new Animal(); // Object created
◼ [Link](); // Method call
◼ }
◼ }
◼ class Employee {
◼ int id;
◼ String name;
◼ void showDetails() {
◼ [Link]("ID: " + id + ", Name: " + name);
◼ }
◼ public static void main(String[] args) {
◼ Employee e1 = new Employee();
◼ [Link] = 101;
◼ [Link] = "Boybu";
◼ [Link]();
◼ Employee e2 = new Employee();
◼ [Link] = 102;
◼ [Link] = "Girlbu";
◼ [Link]();
◼ }
◼ }
◼ Class with constructor
◼ class Book {
◼ String title;
◼ String author;
◼ // Constructor
◼ Book(String t, String a) {
◼ title = t;
◼ author = a;
◼ }
◼ void display() {
◼ [Link](title + " by " + author);
◼ }
◼ public static void main(String[] args) {
◼ Book b1 = new Book("1984", "George Orwell");
◼ [Link]();
◼ }
◼ }
◼ Reusability
◼ Once a class is completed and tested it can be distributed to other programmers
◼ If those programmers want to add new features or change the existing one
◼ Object as method parameter
◼ class Circle {
◼ double radius;
◼ Circle(double r) {
◼ radius = r;
◼ }
◼ void compareArea(Circle c2) {
◼ double area1 = [Link] * radius * radius;
◼ double area2 = [Link] * [Link] * [Link];
◼ if (area1 > area2)
◼ [Link]("First circle is larger.");
◼ else if (area1 < area2)
◼ [Link]("Second circle is larger.");
◼ else
◼ [Link]("Both circles are equal.");
◼ }
◼ public static void main(String[] args) {
◼ Circle c1 = new Circle(3);
◼ Circle c2 = new Circle(4);
◼ [Link](c2);
◼ }
◼ }
◼ Returning Object from Method
◼ class Product {
◼ int id;
◼ String name;
◼ Product getProduct() {
◼ Product p = new Product();
◼ [Link] = 201;
◼ [Link] = "Laptop";
◼ return p;
◼ }
◼ public static void main(String[] args) {
◼ Product p1 = new Product();
◼ Product p2 = [Link]();
◼ [Link]("ID: " + [Link] + ", Name: " + [Link]);
◼ }
◼ }
◼ Class Rectangle{
◼ private int length,breadth;
◼ public void getData()
◼ {
◼ Scanner sc=new Scanner([Link]);
◼ [Link](“enter length and breadth”);
◼ Length=[Link]();
◼ Breadth=[Link]();
◼ }
◼ Public void setData(int l)
◼ {
◼ Length=l
◼ Breadth=b
◼ }
◼ Public void displayData(){
◼ [Link](“length=“+length)
◼ [Link](“breadth=“+breadth)
◼ }
◼ Public void areaPeri(){
◼ Int a,p;
◼ A=length*breadth;
◼ P=2(length+breadth);
◼ }
◼ }
◼ Public class Demo{
◼ Psvm()
◼ {
◼ Rectangle r1,r2,r3;
◼ R1=new Rectangle();
◼ R2=new Rectangle()
◼ R3=new Rectangle()
◼ [Link](10,20)
◼ [Link]()
◼ [Link]();
◼ [Link]()
◼ [Link]()
◼ [Link]()
◼ }
◼ }
◼ Objects occupy space in memory
◼ Objects are created in heap
◼ Constructors
◼ Class Number{
◼ private int I
◼ public void setData(int j)
◼ {
◼ i=j;
◼ }
◼ public void getData()
◼ {
◼ Scanner s=new Scanner([Link]);
◼ [Link](“enter a number”)
◼ i=[Link]()
◼ }
◼ Public Number()
◼ {
◼ }
◼ Public Number(int j)
◼ {
◼ i=j
◼ }
◼ Public void displayData()
◼ {
◼ [Link](“value of i=“+i)
◼ }
◼ }
◼ Class ConstructorDemo{
◼ Public static void main(){
◼ Number n1,n2,n3;
◼ N1=new Number()
◼ [Link]()
◼ [Link]()
◼ [Link]()
◼ }
◼ }
◼ Constructors have same name as class names
◼ Constructors have no return type
◼ Constructor is called automatically when object is created
◼ Object destruction
◼ When the object is created using the new operator memory is allocated to the object
◼ But when the program stops running the memory must be freed
◼ This is done by JVM
◼ Java has automatic garbage collection which frees up the memory used by objects
◼ There are many resources like files,network connections,database connections.
◼ Java has a finalize method to free up the resources
◼ This function is defined inside the class and is called by the garbage collector
◼ Finalize function is opposite of constructor
◼ Constructor is called when the object is created
◼ Finalize is called when the object is destroyed by the garbage collector
◼ package test;
◼ class Example
◼ {
◼ private int data;
◼ public Example()
◼ {
◼ [Link]("inside the constructor");
◼ }
◼ protected void finalize() throws Throwable
◼ {
◼ super.finalize();
◼ }
◼ }
◼ public class ObjectDestruction {
◼
◼ public static void main(String[] args) {
◼ Example e=new Example();
◼ }
◼ }
◼
◼
◼ When the control goes out of the main object is no longer needed
◼ Garbage collector calls the finalize function
◼ Finalize function does not receive any parameter nor does it return any value
◼ It cannot be declared as public
◼ In the finalize method we have called the base class finalize method
◼ All the classes in java belong to the base class object
◼ class Student {
◼ String name;
◼ int age;
◼ // Parameterized constructor
◼ Student(String studentName, int studentAge) {
◼ name = studentName;
◼ age = studentAge;
◼ }
◼ // Method to display student info
◼ void display() {
◼ [Link]("Name: " + name);
◼ [Link]("Age: " + age);
◼ }
◼ public static void main(String[] args) {
◼ // Creating objects with different values
◼ Student s1 = new Student("Boybu", 20);
◼ Student s2 = new Student("Girlbu", 19);
◼ // Displaying data
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ class Rectangle {
◼ int length, width;
◼ // Parameterized constructor
◼ Rectangle(int l, int w) {
◼ length = l;
◼ width = w;
◼ }
◼ int area() {
◼ return length * width;
◼ }
◼ public static void main(String[] args) {
◼ Rectangle r1 = new Rectangle(10, 5);
◼ [Link]("Area: " + [Link]());
◼ }
◼ }
ARRAYS IN JAVA
◼ What is an Array in Java?
◼ An array in Java is a container object that holds a fixed number of elements of the same data type.
◼ Arrays are indexed: the first element is at index 0, the second at index 1, and so on.
◼ Once the size is defined, it cannot be changed.
◼ Java arrays can be 1D, 2D, or multi-dimensional.
◼ Declaring an Array
◼ int[] arr; // Recommended
◼ // or
◼ int arr[]; // Also valid
◼ allocating memory for an array
◼ arr = new int[5]; // Array of 5 integers
◼ Declaring, Creating, and Initializing Together
◼ int[] arr = {10, 20, 30, 40, 50};
◼ Simple array example
◼ public class ArrayExample {
◼ public static void main(String[] args) {
◼ int[] numbers = new int[5]; // Declare and create array
◼ // Initialize values
◼ numbers[0] = 10;
◼ numbers[1] = 20;
◼ numbers[2] = 30;
◼ numbers[3] = 40;
◼ numbers[4] = 50;
◼ // Access and print array elements
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Element at index " + i + " : " + numbers[i]);
◼ }
◼ }
◼ }
◼ public class StringArrayExample {
◼ public static void main(String[] args) {
◼ String[] fruits = {"Apple", "Banana", "Mango"};
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Fruit: " + fruits[i]);
◼ }
◼ }
◼ }
◼ Accessing the elements of array using enhanced for loop
◼ For(String name:fruits)
◼ [Link](name)
◼ Passing array elements to a function
◼ Public class Demo{
◼ Public static void main(String args[])
◼ {
◼ Int marks[]={55,65,75,56,78,78,90};
◼ Int I;
◼ For(i=0;i<=6;i++)
◼ {
◼ Modify(marks[i]);
◼ }
◼ For(i=0;i<=6;i++)
◼ {
◼ Modify(marks[i]);
◼ }
◼ }
◼ Static void modify(int m)
◼ {
◼ m=m*2;
◼ }
◼ }
◼ So what output we will get?
◼ We get the output as
◼ There is no change in the array elements as we are passing by value
◼ Passing array reference to a function
◼ Public class Demo{
◼ Public static void main(String args[])
◼ {
◼ Int[] marks={10,20,30,40,50,60};
◼ modify(marks);
◼ for(int i=0;i<[Link]();i++)
◼ {
◼ m[i]=m[i]*2;
◼ }
◼ }
◼ modify(int m[])
◼ {
◼ for(int i=0;i<[Link]();i++)
◼ {
◼ m[i]=m[i]*2;
◼ }
◼ }
◼ Returning an array
◼ Public class Demo{
◼ Public static void main(String args[])
◼ {
◼ Int[] p;
◼ p=func();
◼ for(int i=0;i<=[Link]();i++)
◼ [Link](p[i]);
◼ }
◼ int[] func()
◼ {
◼ int[] arr={10,20,30,40,50,60}
◼ return arr
◼ }
◼ Print elements of an array
◼ public class PrintArray {
◼ public static void main(String[] args) {
◼ int[] arr = {5, 10, 15, 20};
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Element at index " + i + ": " + arr[i]);
◼ }
◼ }
◼ }
◼ Find the sum of all elements of array
◼ public class SumArray {
◼ public static void main(String[] args) {
◼ int[] arr = {3, 6, 9, 12};
◼ int sum = 0;
◼ for (int i = 0; i < [Link]; i++) {
◼ sum += arr[i];
◼ }
◼ [Link]("Sum = " + sum);
◼ }
◼ }
◼ Find maximum element in an array
◼ public class MaxElement {
◼ public static void main(String[] args) {
◼ int[] arr = {25, 70, 15, 90, 45};
◼ int max = arr[0];
◼ for (int i = 1; i < [Link]; i++) {
◼ if (arr[i] > max) {
◼ max = arr[i];
◼ }
◼ }
◼ [Link]("Maximum value = " + max);
◼ }
◼ }
◼ Reverse the array
◼ public class ReverseArray {
◼ public static void main(String[] args) {
◼ int[] arr = {1, 2, 3, 4, 5};
◼ [Link]("Original Array:");
◼ for (int val : arr) {
◼ [Link](val + " ");
◼ }
◼ [Link]("\nReversed Array:");
◼ for (int i = [Link] - 1; i >= 0; i--) {
◼ [Link](arr[i] + " ");
◼ }
◼ }
◼ }
◼ Count even and odd numbers in an array
◼ public class CountEvenOdd {
◼ public static void main(String[] args) {
◼ int[] arr = {4, 7, 10, 13, 16};
◼ int even = 0, odd = 0;
◼ for (int num : arr) {
◼ if (num % 2 == 0)
◼ even++;
◼ else
◼ odd++;
◼ }
◼ [Link]("Even numbers: " + even);
◼ [Link]("Odd numbers: " + odd);
◼ }
◼ }
◼ What is a String in Java?
◼ In Java, a String is an object that represents a sequence of characters.
◼ It is immutable, meaning once a String object is created, it cannot be changed.
◼ // Using String literal
◼ String s1 = "Hello";
◼ // Using new keyword
◼ String s2 = new String("World");
Method Description
length() Returns length of the string
charAt(i) Returns character at index i
substring(i,j) Returns substring from i to j-1
equals() Compares two strings (case-sensitive)
equalsIgnoreCase() Compares two strings ignoring case
toLowerCase() / toUpperCase() Converts string case
concat() Joins two strings
contains() Checks if string contains a substring
replace(a, b) Replaces character a with b
trim() Removes leading/trailing spaces
◼ public class StringBasics {
◼ public static void main(String[] args) {
◼ String name = "Nayana";
◼ [Link]("Length: " + [Link]());
◼ [Link]("First character: " + [Link](0));
◼ [Link]("Substring (1 to 4): " + [Link](1, 4));
◼ [Link]("Uppercase: " + [Link]());
◼ [Link]("Lowercase: " + [Link]());
◼ }
◼ }
◼ public class StringComparison {
◼ public static void main(String[] args) {
◼ String s1 = "hello";
◼ String s2 = "Hello";
◼ [Link]([Link](s2)); // false
◼ [Link]([Link](s2)); // true
◼ }
◼ }
◼ public class StringConcatReplace {
◼ public static void main(String[] args) {
◼ String s1 = "Java";
◼ String s2 = "Programming";
◼ String result = [Link](" ").concat(s2);
◼ [Link]("Concatenated: " + result);
◼ String replaced = [Link]("Java", "Python");
◼ [Link]("Replaced: " + replaced);
◼ }
◼ }
◼ import [Link];
◼ public class StringInput {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ [Link]("Enter your name: ");
◼ String name = [Link](); // Reads full line
◼ [Link]("Welcome, " + name + "!");
◼ [Link]();
◼ }
◼ }
◼ Check if string is a palindrome
◼ import [Link];
◼ public class PalindromeCheck {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ [Link]("Enter a string: ");
◼ String str = [Link]();
◼ String reversed = "";
◼ for (int i = [Link]() - 1; i >= 0; i--) {
◼ reversed += [Link](i);
◼ }
◼ if ([Link](reversed))
◼ [Link]("Palindrome");
◼ else
◼ [Link]("Not a palindrome");
◼ [Link]();
◼ }
◼ }
◼ Reverse a string
◼ import [Link];
◼ public class ReverseString {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ [Link]("Enter a string: ");
◼ String str = [Link]();
◼ String reverse = "";
◼ for (int i = [Link]() - 1; i >= 0; i--) {
◼ reverse += [Link](i);
◼ }
◼ [Link]("Reversed string: " + reverse);
◼ [Link]();
◼ }
◼ }
◼ Count vowels and consonants
◼ import [Link];
◼ public class CountVowelsConsonants {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ [Link]("Enter a string: ");
◼ String str = [Link]().toLowerCase();
◼ int vowels = 0, consonants = 0;
◼ for (int i = 0; i < [Link](); i++) {
◼ char ch = [Link](i);
◼ if ([Link](ch)) {
◼ if ("aeiou".indexOf(ch) != -1)
◼ vowels++;
◼ else
◼ consonants++;
◼ }
◼ }
◼ [Link]("Vowels: " + vowels);
◼ [Link]("Consonants: " + consonants);
◼ [Link]();
◼ }
◼ }
◼ Count words in a sentence
◼ import [Link];
◼ public class WordCount {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ [Link]("Enter a sentence: ");
◼ String str = [Link]();
◼ String[] words = [Link]().split("\\s+"); // split by space
◼ [Link]("Word count: " + [Link]);
◼ [Link]();
◼ }
◼ }
STATIC DATA AND FUNCTIONS
◼ A class can contain instance data members and static data members
◼ Multiple objects have instance data members and share the static data members
◼ Static data members are used when we wish to share the data among all objects
◼ Class Ex{
◼ Private int I;
◼ private static int count=0;
◼ Ex(int val)
◼ {
◼ i=val;
◼ count+=1;
◼ }
◼ Public static void showcount()
◼ {
◼ [Link](count);
◼ }
◼ }
◼ Public class Sample
◼ {
◼ public static void main(String args[])
◼ {
◼ Ex e1=new Ex(10);
◼ [Link]();
◼ Ex e2=new Ex(20);
◼ [Link]();
◼ Ex e3=new Ex(30);
◼ [Link]();
◼ }
◼ }
◼ An ArrayList is a resizable array implementation in Java found in the [Link] package.
◼ Unlike regular arrays, the size of an ArrayList can grow or shrink dynamically as elements are added or
removed.
◼ Basic Features of ArrayList:
◼ Can store objects .
◼ Maintains insertion order.
◼ Allows duplicate elements.
◼ Offers random access via indices.
◼ Resizable (unlike fixed-length arrays).
◼ Creating arraylist
◼ ArrayList<String> names = new ArrayList<>();
◼ ArrayList<Integer> numbers = new ArrayList<>();
Method Description
add(element) Adds an element
add(index, element) Adds at a specific position
get(index) Retrieves element at index
set(index, element) Replaces element at index
remove(index) Removes element at index
size() Returns number of elements
clear() Removes all elements
contains(element) Checks if element exists
◼ import [Link];
◼ public class ArrayListExample {
◼ public static void main(String[] args) {
◼ ArrayList<String> fruits = new ArrayList<>();
◼ [Link]("Apple");
◼ [Link]("Banana");
◼ [Link]("Mango");
◼ [Link]("Fruits: " + fruits);
◼ [Link]("Banana");
◼ [Link]("After removal: " + fruits);
◼ [Link]("First fruit: " + [Link](0));
◼ }
◼ }
◼ Great! Here's a menu-driven Java program using an ArrayList<Integer> to manage a list of numbers with
the following features:
◼ Add a number
◼ Remove a number
◼ Search for a number
◼ Display all numbers
◼ Sort the list
◼ Exit
◼ import [Link];
◼ import [Link];
◼ import [Link];
◼ public class ArrayListMenu {
◼ public static void main(String[] args) {
◼ ArrayList<Integer> numbers = new ArrayList<>();
◼ Scanner sc = new Scanner([Link]);
◼ int choice;
◼ do {
◼ [Link]("\n--- ArrayList Menu ---");
◼ [Link]("1. Add Number");
◼ [Link]("2. Remove Number");
◼ [Link]("3. Search Number");
◼ [Link]("4. Display All Numbers");
◼ [Link]("5. Sort Numbers");
◼ [Link]("6. Exit");
◼ [Link]("Enter your choice: ");
◼ choice = [Link]();
◼ switch (choice) {
◼ case 1:
◼ [Link]("Enter number to add: ");
◼ int numToAdd = [Link]();
◼ [Link](numToAdd);
◼ [Link]("Number added.");
◼ break;
◼ case 2:
◼ [Link]("Enter number to remove: ");
◼ int numToRemove = [Link]();
◼ if ([Link]([Link](numToRemove))) {
◼ [Link]("Number removed.");
◼ } else {
◼ [Link]("Number not found.");
◼ }
◼ break;
◼ case 3:
◼ [Link]("Enter number to search: ");
◼ int numToSearch = [Link]();
◼ if ([Link](numToSearch)) {
◼ [Link]("Number found at index " + [Link](numToSearch));
◼ } else {
◼ [Link]("Number not found.");
◼ }
◼ break;
◼ case 4:
◼ [Link]("Numbers in list: " + numbers);
◼ break;
◼ case 5:
◼ [Link](numbers);
◼ [Link]("Numbers sorted.");
◼ break;
◼ case 6:
◼ [Link]("Exiting program.");
◼ break;
◼ default:
◼ [Link]("Invalid choice. Try again.");
◼ }
◼ } while (choice != 6);
◼ [Link]();
◼ }
◼ }
◼ 1. Store and Display Student Names
◼ Problem:
◼ Create an ArrayList to store 5 student names entered by the user. Display them all.
◼ 2. Add and Remove Numbers
◼ Problem:
◼ Create an ArrayList of integers.
◼ Add numbers: 10, 20, 30, 40, 50
◼ Remove the number 30
◼ Display the list after removal
◼ 3. Search for a Name
◼ Problem:
◼ Ask the user to enter 5 names and store them in an ArrayList.
◼ Then ask for a name to search and display if it exists.
◼ 4. Sort a List of Marks
◼ Problem:
◼ Take input of marks scored by students.
◼ Store them in an ArrayList and display the list in sorted order (ascending).
◼ 5. Count Even and Odd Numbers
◼ Problem:
◼ Store 10 integers in an ArrayList.
◼ Count how many are even and how many are odd.
◼ 6. Merge Two Lists
◼ Problem:
◼ Create two ArrayLists of strings: one for fruits and one for vegetables.
◼ Merge them into a third ArrayList and display all items.
◼ 7. Remove Duplicates
◼ Problem:
◼ Take input of 10 integers (some may be duplicates).
◼ Store in an ArrayList and remove duplicate values.
◼ Hint: Use a Set or loop to check duplicates.
◼ import [Link];
◼ import [Link];
◼ public class StudentNames {
◼ public static void main(String[] args) {
◼ ArrayList<String> studentNames = new ArrayList<>();
◼ Scanner sc = new Scanner([Link]);
◼ // Input 5 student names
◼ for (int i = 0; i < 5; i++) {
◼ [Link]("Enter name of student " + (i + 1) + ": ");
◼ String name = [Link]();
◼ [Link](name);
◼ }
◼ // Display all names
◼ [Link]("\nList of Student Names:");
◼ for (String name : studentNames) {
◼ [Link](name);
◼ }
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ public class AddRemoveNumbers {
◼ public static void main(String[] args) {
◼ // Create an ArrayList of integers
◼ ArrayList<Integer> numbers = new ArrayList<>();
◼ // Add numbers to the list
◼ [Link](10);
◼ [Link](20);
◼ [Link](30);
◼ [Link](40);
◼ [Link](50);
◼ [Link]("Original List: " + numbers);
◼ // Remove the number 30
◼ [Link]([Link](30)); // important: use [Link]()
◼ // Display the list after removal
◼ [Link]("List after removing 30: " + numbers);
◼ }
◼ }
◼ import [Link];
◼ import [Link];
◼ public class SearchName {
◼ public static void main(String[] args) {
◼ ArrayList<String> names = new ArrayList<>();
◼ Scanner sc = new Scanner([Link]);
◼ // Input 5 names
◼ [Link]("Enter 5 names:");
◼ for (int i = 0; i < 5; i++) {
◼ [Link]("Enter name " + (i + 1) + ": ");
◼ String name = [Link]();
◼ [Link](name);
◼ }
◼ // Ask user for the name to search
◼ [Link]("\nEnter a name to search: ");
◼ if ([Link](searchName)) {
◼ [Link](searchName + " is in the list at index " + [Link](searchName));
◼ } else {
◼ [Link](searchName + " is not in the list.");
◼ }
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ import [Link];
◼ import [Link];
◼ public class SortStudentMarks {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ ArrayList<Integer> marks = new ArrayList<>();
◼ [Link]("Enter the number of students: ");
◼ int n = [Link]();
◼ // Input marks for each student
◼ for (int i = 0; i < n; i++) {
◼ [Link]("Enter marks of student " + (i + 1) + ": ");
◼ int mark = [Link]();
◼ [Link](mark);
◼ }
◼ // Sort marks in ascending order
◼ [Link](marks);
◼ // Display sorted marks
◼ [Link]("\nMarks in Ascending Order:");
◼ for (int mark : marks) {
◼ [Link](mark);
◼ }
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ import [Link];
◼ public class CountEvenOdd {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ ArrayList<Integer> numbers = new ArrayList<>();
◼ int evenCount = 0, oddCount = 0;
◼ // Input 10 integers
◼ [Link]("Enter 10 integers:");
◼ for (int i = 0; i < 10; i++) {
◼ [Link]("Number " + (i + 1) + ": ");
◼ int num = [Link]();
◼ [Link](num);
◼ // Count even and odd
◼ if (num % 2 == 0)
◼ evenCount++;
◼ else
◼ oddCount++;
◼ }
◼ // Display the results
◼ [Link]("\nTotal Even Numbers: " + evenCount);
◼ [Link]("Total Odd Numbers: " + oddCount);
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ public class MergeLists {
◼ public static void main(String[] args) {
◼ // Create fruits list
◼ ArrayList<String> fruits = new ArrayList<>();
◼ [Link]("Apple");
◼ [Link]("Banana");
◼ [Link]("Mango");
◼ // Create vegetables list
◼ ArrayList<String> vegetables = new ArrayList<>();
◼ [Link]("Carrot");
◼ [Link]("Spinach");
◼ [Link]("Tomato");
◼ // Merge both lists into a third list
◼ ArrayList<String> allItems = new ArrayList<>();
◼ [Link](fruits);
◼ [Link](vegetables);
◼ // Display merged list
◼ [Link]("Merged List of Fruits and Vegetables:");
◼ for (String item : allItems) {
◼ [Link](item);
◼ }
◼ }
◼ }
◼ import [Link];
◼ import [Link];
◼ import [Link];
◼ import [Link];
◼ public class RemoveDuplicates {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ ArrayList<Integer> numbers = new ArrayList<>();
◼ [Link]("Enter 10 integers (duplicates allowed):");
◼ for (int i = 0; i < 10; i++) {
◼ [Link]("Number " + (i + 1) + ": ");
◼ int num = [Link]();
◼ [Link](num);
◼ }
◼ // Remove duplicates using LinkedHashSet (maintains insertion order)
◼ Set<Integer> uniqueNumbers = new LinkedHashSet<>(numbers);
◼ // Display list after removing duplicates
◼ [Link]("\nList after removing duplicates:");
◼ for (int num : uniqueNumbers) {
◼ [Link](num);
◼ }
◼ [Link]();
◼ }
◼ }
◼ Multidimensional arrays
◼ int[][] matrix;
◼ int[][] matrix = new int[3][4]; // 3 rows, 4 columns
◼ int[][] matrix = {
◼ {1, 2, 3},
◼ {4, 5, 6},
◼ {7, 8, 9}
◼ };
◼ for (int i = 0; i < [Link]; i++) { // rows
◼ for (int j = 0; j < matrix[i].length; j++) { // columns
◼ [Link](matrix[i][ j] + " ");
◼ }
◼ [Link]();
◼ }
◼ Example: Input and Display a 2D Array
◼ import [Link];
◼ public class TwoDArrayExample {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ int[][] matrix = new int[3][3];
◼ // Input elements
◼ [Link]("Enter 3x3 matrix elements:");
◼ for (int i = 0; i < 3; i++) {
◼ for (int j = 0; j < 3; j++) {
◼ [Link]("Element [" + i + "][" + j + "]: ");
◼ matrix[i][ j] = [Link]();
◼ }
◼ }
◼ // Display matrix
◼ [Link]("\nMatrix:");
◼ for (int i = 0; i < 3; i++) {
◼ for (int j = 0; j < 3; j++) {
◼ [Link](matrix[i][ j] + "\t");
◼ }
◼ [Link]();
◼ }
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ public class MatrixAddition {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ // Define size of the matrix
◼ int rows, cols;
◼ [Link]("Enter number of rows: ");
◼ rows = [Link]();
◼ [Link]("Enter number of columns: ");
◼ cols = [Link]();
◼ // Declare matrices
◼ int[][] matrix1 = new int[rows][cols];
◼ int[][] matrix2 = new int[rows][cols];
◼ int[][] result = new int[rows][cols];
◼ // Input first matrix
◼ [Link]("\nEnter elements of first matrix:");
◼ for (int i = 0; i < rows; i++) {
◼ for (int j = 0; j < cols; j++) {
◼ [Link]("matrix1[" + i + "][" + j + "]: ");
◼ matrix1[i][ j] = [Link]();
◼ }
◼ }
◼ [Link]("\nEnter elements of second matrix:");
◼ for (int i = 0; i < rows; i++) {
◼ for (int j = 0; j < cols; j++) {
◼ [Link]("matrix2[" + i + "][" + j + "]: ");
◼ matrix2[i][ j] = [Link]();
◼ }
◼ }
◼ // Add matrices
◼ for (int i = 0; i < rows; i++) {
◼ for (int j = 0; j < cols; j++) {
◼ result[i][ j] = matrix1[i][ j] + matrix2[i][ j];
◼ }
◼ }
◼ // Display result
◼ [Link]("\nResultant Matrix (Addition):");
◼ for (int i = 0; i < rows; i++) {
◼ for (int j = 0; j < cols; j++) {
◼ [Link](result[i][ j] + "\t");
◼ }
◼ [Link]();
◼ }
◼ [Link]();
◼ }
◼ }
◼ Example 1: Array of Student objects
◼ Define a Student class.
◼ Create an array to hold multiple Student objects.
◼ Initialize each object in the array.
◼ class Student {
◼ String name;
◼ int rollNo;
◼ // Constructor
◼ Student(String name, int rollNo) {
◼ [Link] = name;
◼ [Link] = rollNo;
◼ }
◼ // Method to display details
◼ void display() {
◼ [Link]("Name: " + name + ", Roll No: " + rollNo);
◼ }
◼ }
◼ public class StudentArrayDemo {
◼ public static void main(String[] args) {
◼ // Create an array of Student objects
◼ Student[] students = new Student[3];
◼ // Initialize each object
◼ students[0] = new Student("Nayana", 1);
◼ students[1] = new Student("Boybu", 2);
◼ students[2] = new Student("Dadbu", 3);
◼ // Display all student details
◼ for (Student s : students) {
◼ [Link]();
◼ }
◼ }
◼ import [Link];
◼ public class VectorDemo {
◼ public static void main(String[] args) {
◼ Vector<String> names = new Vector<>();
◼ // Add elements
◼ [Link]("Nayana");
◼ [Link]("Boybu");
◼ [Link]("Dadbu");
◼ [Link]("Nayana"); // duplicates allowed
◼ // Access elements
◼ [Link]("First element: " + names.firstElement());
◼ [Link]("Last element: " + [Link]());
◼ // Loop through elements
◼ [Link]("All names:");
◼ for (String name : names) {
◼ [Link](name);
◼ }
◼ }
◼ }
◼ Store and Display Student Details
◼ Create a Student class with fields: rollNo, name, and marks.
◼ Create an array of 5 students and display their details using a display() method.
◼ Search an Employee by ID
◼ Create an Employee class.
◼ Store details of 5 employees.
◼ Accept an ID from the user and search for that employee in the array.
◼ Display Products Above a Certain Price
◼ Create a Product class with id, name, and price.
◼ Input 5 products.
◼ Display the products whose price is greater than ₹1000.
◼ Find Average Marks of Students
◼ Store 5 students with name and marks.
◼ Calculate and display the average marks.
◼ Count Employees in a Specific Department
◼ Class: Employee with fields id, name, department.
◼ Count how many employees are in the "HR" department.
◼ What is a Constructor in Java?
◼ A constructor in Java is a special method that is called automatically when an object is created.
◼ It is used to initialize objects.
◼ Key Points:
◼ The name of the constructor is same as the class name.
◼ It does not have a return type, not even void.
◼ It is automatically called when an object is created using new.
◼ You can have multiple constructors in a class (constructor overloading).
◼ Types of Constructors:
◼ Default Constructor (No parameters)
◼ Parameterized Constructor (Takes arguments)
◼ Copy Constructor
◼ Example 1: Default Constructor (no parameters)
◼ class Student {
◼ Student() { // constructor
◼ [Link]("Constructor called");
◼ }
◼ void display() {
◼ [Link]("Welcome to Java!");
◼ }
◼ public static void main(String[] args) {
◼ Student s = new Student(); // Constructor called
◼ [Link]();
◼ }
◼ }
◼ Example 2: Parameterized Constructor
◼ class Student {
◼ String name;
◼ int age;
◼ Student(String n, int a) {
◼ name = n;
◼ age = a;
◼ }
◼ void display() {
◼ [Link]("Name: " + name + ", Age: " + age);
◼ }
◼ public static void main(String[] args) {
◼ Student s1 = new Student("Nayana", 30);
◼ [Link]();
◼ }
◼ }
◼ Constructor overloading
◼ class Student {
◼ Student() {
◼ [Link]("No-arg constructor");
◼ }
◼ Student(String name) {
◼ [Link]("Name: " + name);
◼ }
◼ public static void main(String[] args) {
◼ Student s1 = new Student();
◼ Student s2 = new Student("Boybu");
◼ }
◼ }
◼ What is a Copy Constructor?
◼ A copy constructor is a constructor
◼ that creates a new object by copying values from an existing object of the same class.
◼ class Student {
◼ String name;
◼ int age;
◼ // Parameterized constructor
◼ Student(String n, int a) {
◼ name = n;
◼ age = a;
◼ }
◼ // Copy constructor
◼ Student(Student s) {
◼ name = [Link];
◼ age = [Link];
◼ }
◼ void display() {
◼ [Link]("Name: " + name + ", Age: " + age);
◼ }
◼ public static void main(String[] args) {
◼ Student s1 = new Student("Boybu", 20); // Original object
◼ Student s2 = new Student(s1); // Copy constructor called
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ Why use constructors
◼ To initialize instance variables
◼ Constructor Chaining means calling one constructor from another constructor within the same class or from a
superclass.
◼ class Student {
◼ String name;
◼ int age;
◼ Student() {
◼ this(“nayana", 40); // calls parameterized constructor
◼ [Link]("Default constructor called");
◼ }
◼ Student(String name, int age) {
◼ [Link] = name;
◼ [Link] = age;
◼ [Link]("Parameterized constructor called: " + name + ", " + age);
◼ }
◼ public static void main(String[] args) {
◼ Student s1 = new Student();
◼ }
◼ }
◼ this() must be the first statement in the constructor.
◼ 2. Constructor Chaining to Superclass using super()
◼ class Person {
◼ Person() {
◼ [Link]("Person constructor");
◼ }
◼ }
◼ class Student extends Person {
◼ Student() {
◼ super(); // calls superclass constructor
◼ [Link]("Student constructor");
◼ }
◼ public static void main(String[] args) {
◼ Student s = new Student();
◼ }
◼ }
◼ Write a Java class Student that demonstrates constructor chaining. Implement the following:
◼ A default constructor that calls a constructor with one parameter (name).
◼ A one-parameter constructor that calls a constructor with two parameters (name and age).
◼ A two-parameter constructor that initializes the data.
◼ class Student{
◼ String name;
◼ int age;
◼ Student(String n,int a)
◼ {
◼ name=n;
◼ age=a;
◼ }
◼ Student(String name)
◼ {
◼ this(name,43);
◼ }
◼ Student(){
◼ this("nayana");
◼ [Link]("default constructor called");
◼ }
◼ void display()
◼ {
◼ [Link](name+age);
◼ }
◼ }
◼ }
◼ public class Conchaindemo {
◼ public static void main(String[] args) {
◼ Student s1=new Student();
◼ [Link]();
◼ }
◼
◼ package demo;
◼ class Book{
◼ String title;
◼ String author;
◼ double price;
◼ Book()
◼ {
◼ title="unknown title";
◼ author="unknown author";
◼ price=0.0;
◼ [Link]("default constructor called");
◼ [Link](title+author+price);
◼ }
◼ Book(String t)
◼ {
◼ title=t;
◼ [Link](title);
◼ }
◼ }
◼ public class Conchaindemo {
◼ public static void main(String[] args) {
◼ Book b1=new Book();
◼ }
◼ }
◼ Recursion is a programming technique where a method calls itself to solve a problem.
◼ It's useful for problems that can be broken into smaller subproblems, like:
◼ Factorial
◼ Fibonacci
◼ Sum of digits
◼ class FactorialDemo {
◼ static int factorial(int n) {
◼ if (n == 0)
◼ return 1;
◼ else
◼ return n * factorial(n - 1); // recursive call
◼ }
◼ public static void main(String[] args) {
◼ int result = factorial(5); // 5! = 120
◼ [Link]("Factorial: " + result);
◼ }
◼ }
◼ class FibonacciDemo {
◼ static int fibonacci(int n) {
◼ if (n == 0 || n == 1)
◼ return n;
◼ else
◼ return fibonacci(n - 1) + fibonacci(n - 2); // recursive call
◼ }
◼ public static void main(String[] args) {
◼ [Link]("Fibonacci series up to 5 terms:");
◼ for (int i = 0; i < 5; i++) {
◼ [Link](fibonacci(i) + " ");
◼ }
◼ }
◼ }
◼ Passing parameters to method
◼ class Demo {
◼ void greet(String name) { // parameter
◼ [Link]("Hello, " + name + "!");
◼ }
◼ public static void main(String[] args) {
◼ Demo obj = new Demo();
◼ [Link]("Mombu"); // argument passed
◼ }
◼ }
◼ Returning value from method
◼ class Calculator {
◼ int square(int x) {
◼ return x * x; // returns the square of x
◼ }
◼ public static void main(String[] args) {
◼ Calculator c = new Calculator();
◼ int result = [Link](5); // store the return value
◼ [Link]("Square: " + result);
◼ }
◼ }
◼ class MathDemo {
◼ int add(int a, int b) {
◼ return a + b;
◼ }
◼ public static void main(String[] args) {
◼ MathDemo m = new MathDemo();
◼ int sum = [Link](10, 20);
◼ [Link]("Sum = " + sum);
◼ }
◼ }
◼ 1. Single Inheritance – Employee Details
◼ Create two classes:
◼ Employee with attributes: empId, name, salary.
◼ Manager inherits Employee and has an additional field: department.
◼ Task: Input and display details of a manager using inheritance
◼ class Employees
◼ {
◼ int empid;
◼ String name;
◼ Double salary;
◼ Employees(int e,String n,Double s)
◼ {
◼ empid=e;
◼ name=n;
◼ salary=s;
◼ }
◼ }
◼ class Manager extends Employees{
◼ String department;
◼ Manager(int e,String n,Double s,String d)
◼ {
◼ super(e,n,s);
◼ department=d;
◼ }
◼ void display()
◼ {
◼ [Link](empid+name+salary+department);
◼ }
◼ }
IRREGULAR ARRAYS
◼ In an irregular (jagged) array, each row can have a different number of columns.
◼ public class JaggedArrayExample {
◼ public static void main(String[] args) {
◼ // Declare a 2D array with 3 rows but no column sizes yet
◼ int[][] jagged = new int[3][];
◼ // Assign columns of different lengths
◼ jagged[0] = new int[2]; // row 0 has 2 columns
◼ jagged[1] = new int[4]; // row 1 has 4 columns
◼ jagged[2] = new int[3]; // row 2 has 3 columns
◼ // Display the array
◼ for (int i = 0; i < [Link]; i++) {
◼ for (int j = 0; j < jagged[i].length; j++) {
◼ [Link](jagged[i][ j] + " ");
◼ }
◼ [Link]();
◼ }
◼ }
◼ }
•Useful when data naturally comes in rows of different lengths
•(e.g., student marks where each student took a different number of subjects).
•Saves memory because you don’t waste space for unused elements.
◼ public class JaggedArrayDemo {
◼ public static void main(String[] args) {
◼ // Creating a jagged array with 3 rows
◼ int[][] marks = new int[3][];
◼ // Initializing each row with different column lengths
◼ marks[0] = new int[2]; // Student 1 has 2 subjects
◼ marks[1] = new int[4]; // Student 2 has 4 subjects
◼ marks[2] = new int[3]; // Student 3 has 3 subjects
◼ // Assigning marks to each student
◼ // Displaying marks for each student
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Student " + (i + 1) + ": ");
◼ for (int j = 0; j < marks[i].length; j++) {
◼ [Link](marks[i][ j] + " ");
◼ }
◼ [Link]();
◼ }
◼ }
◼ }
◼ public class JaggedArrayUserInput {
◼ public static void main(String[] args) {
◼ Scanner sc = new Scanner([Link]);
◼ // Ask for number of students
◼ [Link]("Enter number of students: ");
◼ int students = [Link]();
◼ // Create jagged array
◼ int[][] marks = new int[students][];
◼ // Taking input for each student
◼ for (int i = 0; i < students; i++) {
◼ [Link]("Enter number of subjects for Student " + (i + 1) + ": ");
◼ int subjects = [Link]();
◼ // Allocate columns for this student
◼ marks[i] = new int[subjects];
◼ // Input marks for each subject
◼ for (int j = 0; j < subjects; j++) {
◼ [Link]("Enter marks for subject " + (j + 1) + ": ");
◼ marks[i][ j] = [Link]();
◼ }
◼ }
◼ // Displaying the marks
◼ [Link]("\n--- Marks of Students ---");
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Student " + (i + 1) + ": ");
◼ for (int j = 0; j < marks[i].length; j++) {
◼ [Link](marks[i][ j] + " ");
◼ }
◼ [Link]();
◼ }
◼ [Link]();
◼ }
◼ }
◼ In Java, command-line arguments are values passed to your program when you run it from the terminal (or
command prompt).
◼ They are stored in the String[] args parameter of the main() method.
◼ public class Demo {
◼ public static void main(String[] args) {
◼ [Link]("Number of arguments: " + [Link]);
◼ for (int i = 0; i < [Link]; i++) {
◼ [Link]("Argument " + i + ": " + args[i]);
◼ }
◼ }
◼ }
◼ public class SumArgs {
◼ public static void main(String[] args) {
◼ // Check if exactly 2 arguments are provided
◼ if ([Link] != 2) {
◼ [Link]("Usage: java SumArgs <num1> <num2>");
◼ return;
◼ }
◼ // Convert string arguments to integers
◼ int num1 = [Link](args[0]);
◼ int num2 = [Link](args[1]);
◼ // Calculate and display sum
◼ int sum = num1 + num2;
◼ [Link]("Sum: " + sum);
◼ }
◼ }
◼ public class SumAllArgs {
◼ public static void main(String[] args) {
◼ if ([Link] == 0) {
◼ [Link]("Please provide at least one number.");
◼ return;
◼ }
◼ int sum = 0;
◼ for (String arg : args) {
◼ sum += [Link](arg); // Convert each argument to int and add
◼ }
◼ [Link]("Sum of all arguments: " + sum);
◼ }
◼ }
◼ In Java, a static initialization block is a block of code inside a class that runs once when the class is first loaded into
memory — before any object is created and before any main() method runs.
◼ It’s mainly used for:
◼ Initializing static variables that require complex logic.
◼ Performing setup operations when the class is loaded.
◼ class Example {
◼ static int count;
◼ // Static initialization block
◼ static {
◼ [Link]("Static block executed");
◼ count = 100; // Initialize static variable
◼ }
◼ public static void main(String[] args) {
◼ [Link]("Main method executed");
◼ [Link]("Count = " + count);
◼ }
◼ }
◼ class Helper {
◼ static {
◼ [Link]("Static block in Helper class executed");
◼ }
◼ static void displayMessage() {
◼ [Link]("[Link]() called");
◼ }
◼ }
◼ public class StaticBlockDemo {
◼ static {
◼ [Link]("Static block in StaticBlockDemo class executed");
◼ }
◼ public static void main(String[] args) {
◼ [Link]("Main method of StaticBlockDemo started");
◼ [Link](); // This triggers Helper class loading
◼ }
◼ }
UNIT 3
◼ Types of inheritance in java
◼ 1. Single Inheritance
◼ A class inherits from only one parent class.
◼ This is the most common type in Java.
◼ class Person {
◼ void walk() {
◼ [Link]("Person walks");
◼ }
◼ }
◼ class Student extends Person {
◼ void study() {
◼ [Link]("Student studies");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Student s = new Student();
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ Multilevel inheritance
◼ class Person {
◼ void eat() {
◼ [Link]("Person eats");
◼ }
◼ }
◼ class Employee extends Person {
◼ void work() {
◼ [Link]("Employee works");
◼ }
◼ }
◼ class Manager extends Employee {
◼ void manage() {
◼ [Link]("Manager manages the team");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Manager m = new Manager();
◼ [Link]();
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ 3. Hierarchical Inheritance
◼ Multiple classes inherit from the same parent.
◼ class Vehicle {
◼ void start() {
◼ [Link]("Vehicle starts");
◼ }
◼ }
◼ class Car extends Vehicle {
◼ void drive() {
◼ [Link]("Car drives");
◼ }
◼ }
◼ class Bike extends Vehicle {
◼ void ride() {
◼ [Link]("Bike rides");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Car c = new Car();
◼ Bike b = new Bike();
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ public class SumOfDigits {
◼ // Recursive method
◼ static int sumDigits(int num) {
◼ // Base case
◼ if (num == 0) {
◼ return 0;
◼ }
◼ // Recursive case: last digit + sum of remaining digits
◼ return (num % 10) + sumDigits(num / 10);
◼ }
◼ public static void main(String[] args) {
◼ int number = 12345;
◼ int sum = sumDigits(number);
◼ [Link]("Sum of digits of " + number + " = " + sum);
◼ }
◼ }
◼ class Employee{
◼ float salary=40000;
◼ }
◼ class Programmer extends Employee{
◼ int bonus=10000;
◼ }
◼ public class Main{
◼ public static void main(String args[]){
◼ Programmer p=new Programmer();
◼ [Link]("Programmer salary is:"+[Link]);
◼ [Link]("Bonus of Programmer is:"+[Link]);
◼ }
◼ }
◼ class Animal{
◼ void eat(){[Link]("eating...");}
◼ }
◼ class Dog extends Animal{
◼ void bark(){[Link]("barking...");}
◼ }
◼ public class Main{
◼ public static void main(String args[]){
◼ Dog d=new Dog();
◼ [Link]();
◼ [Link]();
◼ }}
◼ Multilevel inheritance
◼ class Animal{
◼ void eat(){[Link]("eating...");}
◼ }
◼ class Dog extends Animal{
◼ void bark(){[Link]("barking...");}
◼ }
◼ class BabyDog extends Dog{
◼ void weep(){[Link]("weeping...");}
◼ }
◼ public class Main{
◼ public static void main(String args[]){
◼ BabyDog d=new BabyDog();
◼ [Link]();
◼ [Link]();
◼ [Link]();
◼ }}
◼ Hierarchial inheritance
◼ class Animal{
◼ void eat(){[Link]("eating...");}
◼ }
◼ class Dog extends Animal{
◼ void bark(){[Link]("barking...");}
◼ }
◼ class Cat extends Animal{
◼ void meow(){[Link]("meowing...");}
◼ }
◼ public class Main{
◼ public static void main(String args[]){
◼ Cat c=new Cat();
◼ [Link]();
◼ [Link]();
◼ //[Link]();//[Link]
◼ }}
◼ class BankAccount {
◼ String accountHolder;
◼ double balance;
◼ BankAccount(String name, double initialBalance) {
◼ accountHolder = name;
◼ balance = initialBalance;
◼ }
◼ void deposit(double amount) {
◼ balance += amount;
◼ [Link](amount + " deposited. New balance: " + balance);
◼ }
◼ void displayBalance() {
◼ [Link](accountHolder + "'s balance: " + balance);
◼ }
◼ }
◼ class SavingsAccount extends BankAccount {
◼ double interestRate;
◼ SavingsAccount(String name, double initialBalance, double rate) {
◼ super(name, initialBalance);
◼ interestRate = rate;
◼ }
◼ void addInterest() {
◼ double interest = balance * interestRate / 100;
◼ deposit(interest); // using parent's deposit method
◼ [Link]("Interest of " + interest + " added.");
◼ }
◼ }
◼ public class BankingDemo {
◼ public static void main(String[] args) {
◼ SavingsAccount sa = new SavingsAccount("Nayana", 10000, 5);
◼ [Link]();
◼ [Link](2000);
◼ [Link]();
◼ [Link]();
◼ }
◼ }
◼ class Person {
◼ String name;
◼ int age;
◼ Person(String name, int age) {
◼ [Link] = name;
◼ [Link] = age;
◼ }
◼ void displayPersonInfo() {
◼ [Link]("Name: " + name + ", Age: " + age);
◼ }
◼ }
◼ class Student extends Person {
◼ String studentId;
◼ Student(String name, int age, String studentId) {
◼ super(name, age);
◼ [Link] = studentId;
◼ }
◼ void displayStudentInfo() {
◼ [Link]("Student ID: " + studentId);
◼ }
◼ }
◼ class GraduateStudent extends Student {
◼ String thesisTopic;
◼ GraduateStudent(String name, int age, String studentId, String thesisTopic) {
◼ super(name, age, studentId);
◼ [Link] = thesisTopic;
◼ }
◼ void displayThesisInfo() {
◼ [Link]("Thesis Topic: " + thesisTopic);
◼ }
◼ }
◼ public class EducationDemo {
◼ public static void main(String[] args) {
◼ GraduateStudent gs = new GraduateStudent("Ananya", 24, "S12345", "Machine Learning in
Education");
◼ [Link](); // From Person
◼ [Link](); // From Student
◼ [Link](); // From GraduateStudent
◼ }
◼ }
◼ class Parent {
◼ Parent() {
◼ [Link]("Parent constructor called");
◼ }
◼ }
◼ class Child extends Parent {
◼ Child() {
◼ [Link]("Child constructor called");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Child obj = new Child();
◼ }
◼ }
◼ When you create an object of a derived (child) class, the parent constructor is automatically called first, then the
child constructor.
◼ class Parent {
◼ Parent(String name) {
◼ [Link]("Parent constructor called: " + name);
◼ }
◼ }
◼ class Child extends Parent {
◼ Child(String name, int age) {
◼ super(name); // calling Parent(String)
◼ [Link]("Child constructor called, Age: " + age);
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Child obj = new Child("Nayana", 25);
◼ }
◼ }
◼ Parent constructor called: Nayana
◼ Child constructor called, Age: 25
◼ class GrandParent {
◼ GrandParent() {
◼ [Link]("GrandParent constructor");
◼ }
◼ }
◼ class Parent extends GrandParent {
◼ Parent() {
◼ [Link]("Parent constructor");
◼ }
◼ }
◼ class Child extends Parent {
◼ Child() {
◼ [Link]("Child constructor");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Child obj = new Child();
◼ }
◼ }
◼ What is Method Overriding?
◼ Definition: When a subclass provides its own implementation of a method that is already defined in its
superclass, it is called method overriding.
◼ It is used to achieve runtime polymorphism (dynamic method dispatch).
◼ 🔹 Rules of Method Overriding
◼ The method in the child class must have:
◼ Same name
◼ Same parameter list
◼ Same return type
◼ Static methods cannot be overridden
◼ Final methods cannot be overridden.
◼ Constructors cannot be overridden.
◼ class Parent {
◼ void display() {
◼ [Link]("Display from Parent");
◼ }
◼ }
◼ class Child extends Parent {
◼ @Override
◼ void display() {
◼ [Link]("Display from Child");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Parent obj = new Child(); // Upcasting
◼ [Link](); // runtime polymorphism
◼ }
◼ }
◼ Banking example
◼ class Bank {
◼ double rateOfInterest() {
◼ return 5.0;
◼ }
◼ }
◼ class SBI extends Bank {
◼ @Override
◼ double rateOfInterest() {
◼ return 6.5;
◼ }
◼ }
◼ class HDFC extends Bank {
◼ @Override
◼ double rateOfInterest() {
◼ return 7.0;
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Bank b1 = new SBI();
◼ Bank b2 = new HDFC();
◼ [Link]("SBI ROI: " + [Link]());
◼ [Link]("HDFC ROI: " + [Link]());
◼ }
◼ }
◼ Super keyword with overriding
◼ class Animal {
◼ void sound() {
◼ [Link]("Animal makes sound");
◼ }
◼ }
◼ class Dog extends Animal {
◼ @Override
◼ void sound() {
◼ [Link](); // calling parent method
◼ [Link]("Dog barks");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Dog d = new Dog();
◼ [Link]();
◼ }
◼ }
◼ Animal makes sound
◼ Dog barks
◼ Abstract Class
◼ An abstract class is a class that is declared with the abstract keyword.
◼ It can have abstract methods (without body) as well as concrete methods (with body).
◼ You cannot create an object of an abstract class.
◼ It is mainly used for providing a base class for other classes to extend.
◼ Abstract Method
◼ Declared using the abstract keyword.
◼ Has no body (only method signature).
◼ Must be implemented by the child class, unless the child itself is abstract.
◼ abstract class Animal {
◼ abstract void sound(); // abstract method (no body)
◼ void sleep() { // concrete method
◼ [Link]("Sleeping...");
◼ }
◼ }
◼ class Dog extends Animal {
◼ @Override
◼ void sound() {
◼ [Link]("Dog barks");
◼ }
◼ }
◼ class Cat extends Animal {
◼ @Override
◼ void sound() {
◼ [Link]("Cat meows");
◼ }
◼ }
◼ public class Demo {
◼ public static void main(String[] args) {
◼ Animal a1 = new Dog();
◼ Animal a2 = new Cat();
◼ [Link](); // Dog barks
◼ [Link](); // Sleeping...
◼ [Link](); // Cat meows
◼ }
◼ }
◼ abstract class Bank {
◼ abstract double rateOfInterest(); // abstract method
◼ }
◼ class SBI extends Bank {
◼ @Override
◼ double rateOfInterest() {
◼ return 6.5;
◼ }
◼ }
◼ class HDFC extends Bank {
◼ @Override
◼ double rateOfInterest() {
◼ return 7.0;
◼ }
◼ }
◼ public class DemoBank {
◼ public static void main(String[] args) {
◼ Bank b1 = new SBI();
◼ Bank b2 = new HDFC();
◼ [Link]("SBI ROI: " + [Link]());
◼ [Link]("HDFC ROI: " + [Link]());
◼ }
◼ }
◼ Method Overriding = Redefining an existing method of a parent class in the child class.
◼ Abstraction = Defining a blueprint (without implementation) that must be implemented by child classes.