KEMBAR78
Module - 1 Introduction To OOP in Java | PDF | Java Virtual Machine | Java (Programming Language)
0% found this document useful (0 votes)
13 views108 pages

Module - 1 Introduction To OOP in Java

Intro to comlpete JAVA oops
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)
13 views108 pages

Module - 1 Introduction To OOP in Java

Intro to comlpete JAVA oops
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
You are on page 1/ 108

Anjuman-i-Islam’s

M.H.Saboo Siddik College of


Engineering
Department of computer Engineering

Course Name : Full Stack Java Programming


Course code: 2113611
Course Incharge : Prof. Ansari Fatima Anees
2
"Imagine if Siri forgot how to set your alarm. Or if Alexa couldn't play your favorite
playlist until you taught her.

That’s what programming is.

It’s not talking to a smart machine—it’s teaching the machine to become smart.

When you write a line of code, you’re training your assistant: 'This is how to
think.’

Over time, your assistant gets smarter—not with magic, but with logic.

Welcome to programming. You’re not a user anymore. You’re the creator of


intelligence."

3
But here’s the twist—
Intelligence doesn’t live in the machine alone.
It lives in two places:
In you—the one who imagines, questions, and decides what should happen.
And in the machine—which only acts because you taught it how.

Programming is the bridge between these two intelligences.

It’s not just about making a computer work—


It’s about teaching the machine to think like you, but faster, more precisely, and
without getting bored.

Every if, every for, every class you write—


is a thought, an instruction, a rule born in your mind and taught to the machine.

4
Programming is the art of
turning human thought into
machine logic.

• You teach the machine to act without you—


clearly, precisely, tirelessly.
• It’s not about computers.
It’s about how clearly you think, how wisely
you create.
• When you code, you don't just give
commands—
You shape intelligence in your image.

5
• OOP concepts: Objects, class,
Module 1- Encapsulation, Abstraction,
Inheritance, Polymorphism,
Introduction to message passing. Branching and
looping. Class, object, data
OOP in Java members, member functions
Constructors, types, static
members and functions Method
overloading Input and output
functions in Java, Buffered
reader class, scanner class,
Packages in java, types, user
defined packages.

6
7
8
Why Learn Java in 2025?
Timeless Power
25+ years strong — still a top choice for modern development.
Java Powers 20+ Domains
o Mobile Apps – Android, Kotlin (Spotify, Uber)
o Web Apps – JSP, Spring (Amazon, LinkedIn)
o Enterprise – Java EE, APIs (Banks, Salesforce)
o Cloud – Scalable services (Netflix, Dropbox)
o Big Data – Hadoop, Spark (Facebook, Airbnb)
o Blockchain – Hyperledger, secure DLT (IBM, Mastercard)
o IoT & Embedded – Java ME, real-time (Bosch, Sony)
o Games – jMonkey, LibGDX (Minecraft, EA)
o Education – E-learning platforms (Coursera, Khan)

9
History of Java

✔ Java is an object-oriented programming language developed by James Gosling and colleagues at


Sun Microsystems in the early 1990s. The small team of Sun engineers called Green Team.
✔ Originally designed for small, embedded systems in electronic appliances like set-top boxes.
✔ Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
✔ After that, it was called Oak and was developed as a part of the Green project.
✔ Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
✔ In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Prof. ANSARI FATIMA ANEES - MHSSCoE 10


History of Java

11
JAVA

Write Once, Run Anywhere

(WORA)

12
What is Java?
• A programming language.
• As defined by Gosling in the Java Language Specification

• A platform
• A virtual machine (JVM) definition.
• Runtime environments in diverse hardware.

• A class library
• Standard APIs for GUI, data storage, processing, I/O, and networking.

13
Java Technology

Java EE vs. Java SE


– EE: enterprise edition (web services, distribution, RMI, …)
– SE: standard edition (stand alone app.)

• Development Tools
– The main tools you'll be using are the javac compiler, the java launcher (java),
and the javadoc documentation tool.

• Application Programming Interface (API)


– Java SE Development Kit 6 (JDK 6)
– Offers a wide array of useful classes ready for use in your own applications.

14
Java Technology, cont…

• User Interface Toolkits


– Swing and Java 2D toolkits to create Graphical User Interfaces (GUIs).

• Integration Libraries
– Application Programming Interface (API)
– Java RMI, and Java Remote Method Invocation over Internet Inter-ORB
Protocol Technology (Java RMI-IIOP Technology) enable database access.

15
Java Version History
• There are many java versions that has been released. Java SE 14.0. 2 is the latest release of Java
SE Platform.
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
• Java SE 9 (21st Sep, 2017)
• Java SE 10 (20th March, 2018)

Prof. ANSARI FATIMA ANEES - MHSSCoE 16


Features of Java

Prof. ANSARI FATIMA ANEES - MHSSCoE 17


Features of Java
■ Java is simple
■ Java is object-oriented
■ Java is compiled and interpreted
■ Java is robust (No pointers, Garbage Collection &
Exception Handling)
■ Java is platform-independent
■ Java is portable (Architecture-Neutral) (no issue of
varying size of data
types)
■ Java’s high performance (JIT, multithreading,
Lightweight Binary Class Files)
■ Java is distributed (internet, client-server)
■ Java is secure (run on JVM)
■ Java is dynamic (late binding)
Prof. ANSARI FATIMA ANEES - MHSSCoE 18
Features of Java
Security
Platform Independent

Prof. ANSARI FATIMA ANEES - MHSSCoE 19


Platform Independent

Each operating system


has different JVM,
JVM executes the however the output they
byte code produce after execution
generated by of byte code is same
across all operating
compiler and systems. Which means
produce that the byte code
output. JVM is the generated on Windows
one that makes can be run on Mac OS and
vice versa. That is why we
java platform call java as platform
independent. independent language.

Prof. ANSARI FATIMA ANEES - MHSSCoE 20


The Java Virtual Machine
■ It is an abstract machine.
■ It a provides a runtime environment in which Java bytecode can be
executed.
■ The JVM performs the following main tasks:
– Loads code
– Verifies code
– Executes code
– Provides runtime environment

21
The Java Virtual Machine

22
Compile-time Environment
▪ Java Source (.java): Human-written Java code.

▪ Java Compiler: Converts .java to .class (bytecode).

▪ Java Bytecode (.class):Platform-independent instructions.

▪ Bytecodes Move Locally/Through Network:Bytecode can be shared


across systems.

23
Run-time Environment
● Bytecode Verifier: Validates bytecode security and structure.

● Class Loader: Loads .class files into memory.

● Java Class Libraries: Built-in reusable Java functions.

● Runtime Data Areas: Memory areas for code execution (heap, stack,
etc.).

24
Java Development Kit

25
Java IDE Tools in 2025

26
Structure of a Java Program

27
Structure of a Java Program

28
Structure with Example

29
Java Editions & Components
Java SE / EE / ME
Java SE (Standard Edition): Core libraries for desktop/console apps
Java EE (Enterprise Edition): Server-side (Servlets, JSP)
Java ME (Micro Edition): Mobile/embedded devices

Component Description
JDK Java Development Kit – includes compiler, tools, and JRE
JRE Java Runtime Environment – runs Java programs (JVM + libraries)
JVM Java Virtual Machine – Executes bytecode on any platform
javac Java Compiler – Converts .java to .class (bytecode)

30
Java Code Execution Flow
•Write code in IDE
•Compile using javac
•Run on JVM via java command

31
Small Quiz
What does JDK stand for?
a) Java Development Kit
b) Java Deployment Kit
c) Java Debug Kernel
d) Java Data Kit

Answer: Java Development


Kit

32
Small Quiz
Which part of Java executes
bytecode?
a) JDK
b) JRE
c) JVM
d) Compiler
Answer: JVM

33
Object Oriented Concept

• Object
• Class
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

34
Object Oriented Concept
Wikipedia defines OOP as a
“programming paradigm based on the concept of
objects, which may contain data, in the form of
fields, often known as attributes; and code, in the
form of procedures, often known as methods.”
The main idea behind OOP is to represent the data
and logic with objects instead of actions or
functions.

35
36
Class in Java
• A class in Java or any other Object-oriented Language is a blueprint for objects to
follow a specific schema defined in the class.
• Classes define the behavior for objects of its type. It represents a collection of
properties (data and functions) for all its objects.
• It supports a template for creating objects which bind code and data.

37
Object in Java
● An Object is the most fundamental entity in Java or any other Object-Oriented
Language.

● Objects represent real-life entities because each of them could have specific
behavior, identity, and data (attributes).

● In Java, the object is an offspring of its class. The class has properties to
reflect the object state and methods to represent the behavior.

● The methods also show an object’s response to other objects. Identity is a


unique name for the object assigned by the user, much like variables.

● For example – A car, its state are – name, model no, shade,
manufacturer and its behavior can be – moving, blinking the headlights,
honking, etc. 38
Object in Java

For example – A car, its state are – name, model no, shade,
manufacturer and its behavior can be – moving, blinking the
headlights,honking, etc.

39
Class Declaration
Syntax: Example:
class classname class Circle
{ {
double radius = 1.0;//variable
//variables declaration
// Methods declaration double findArea() //method
{
} return radius * radius *
3.14159;
}
}
A class is a collection of fields (data) and methods (procedure or function)
that operate on that data.
40
Declaring/Creating Objects in a Single Step
Syntax: Example:
ClassName objectReference = new Circle myCircle = new Circle();
ClassName();

• Objects in JAVA are created using


new operator.

41
Prg1 : Example – Calculate Tax on some amount
class TaxCalc
{ float amt = 100.0;
float taxRate = 10.5;

void calculate()
{
float tax = amt * taxRate / 100;
S.o.p.(“The taxed amount is : ” + tax);
}

p.s.v.m.( )
{
TaxCalc t = new TaxCalc();
t . calculate();
}
}
42
Encapsulation
• Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed of several medicines.

• We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to set
and get the data in it.

43
Abstraction
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.

44
Inheritance
● Inheritance is the OOP ability that allows Java classes to be derived
from other classes.
● The parent class is called a superclass and the derivatives are called
subclasses. Subclasses inherit fields and methods from their
superclasses.

45
Polymorphism
• Polymorphism in Java allows subclasses of a class to define their own unique
behaviours and yet share some of the same functionality of the parent class.
• In Greek language, Poly means many and morphs means forms.Therefore
Polymorphismtranslates to many forms.
• There are two kinds of polymorphism:
• Overloading
• Two or more methods with different signatures
• Overriding
• Replacing an inherited method with another having the same signature

46
Small Quiz :true / false
Encapsulation ensures that the
internal
details of a class are hidden from
outside.

Answer: True

47
Small Quiz :true / false
A car class having different drive()
methods
based on speed and terrain is an
example
of abstraction.

Answer: False (It's polymorphism)

48
Program : Area of Circle
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
C:\Demo\>java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
49
Main method()

50
Before you start
• Install the Java SE Development Kit 6 (JDK 6).

• Modify the Java Path environment.


– Go to the System Properties by right clicking
you My Computer and choosing
properties🡪 Environment variables🡪click on
TEMP🡪 Edit.
– Add the path to the java bin directory
as shown in the next slide.

• Install the Textpad editor which we will use to develop our applications.

51
Modifying the Path Environment variable
Windows Vista:
1.From the desktop, right click the My Computer icon.
2.Choose Properties from the context menu.
3.Click the Advanced tab (Advanced system settings link in Vista).
4.Click Environment Variables.
In the section System Variables,
find the PATH environment variable and select it.
Click Edit. If the PATH environment variable does not exist, click New.
5.In the Edit System Variable (or New System Variable) window,
specify the value of the PATH environment variable.
Click OK. Close all remaining windows by clicking OK.

52
Java Life Cycle
• Java programs normally undergo four phases
• Edit
• Programmer writes program (and stores program on disk)
• Compile
• Compiler creates bytecodes from program (.class)
• Load
• Class loader stores bytecodes in memory
• Execute
• Interpreter: translates bytecodes into machine language

53
Java Life Cycle

54
Hello world
To begin you need a text editor.
– Notepad, TextPad, …
– Create a new directory on C: name it JavaProjects.

• Open new file, save it as HelloWorld.java in new directory HelloWorld inside the JavaProjects
Directory.

• Write the following code and save the file:

class HelloWorld {
/*simple java application*/
public static void main(String args[]) {
System.out.println(“Hello World”); //displays a string }
}
• Note: the file name should have the same name as the class

55
Compiling and running
Assuming the HelloWorld.java is saved in the c:\JavaProjects\HelloWorld directory:

• Open the a Console, (start🡪Run…), type cmd.

• Type cd \ to return to c:>

• Go to the helloworld directry


– (cd c:\JavaProjects\HelloWorld)

• compile your application


– javac HelloWorld.java

• Run your application


– java HelloWorld.class

• Note: Type all code, commands, and file names exactly as shown. Both the
compiler (javac) and launcher (java) are case-sensitive

56
Closer Look
Three primary components: source code comments, the HelloWorld class definition, and
the main method.

• Comments are ignored by the compiler but are useful to other programmers.

• Two supported kinds of comments


– /* text */ The compiler ignores everything from /* to */.

– // text The compiler ignores everything from // to the end of the line.

• The most basic form of a class definition is


– class name {…}
– Every program must have at least one class, and this class should contain the main method.
57

Closer Look, cont…
In the Java programming language, every application must contain a main method whose
signature is:
– public static void main(String args[])
– The modifiers public and static can be written in either order (public static or static public).
– You can name the argument anything you want, but most programmers choose "args" or "argv.“

• This is the string array that will contains the command line arrguments.
– The main method is the entry point for your application and will subsequently invoke all the other
methods required by your program.

• System.out.println("Hello World!");
– uses the System class from the API to print the "Hello World!" message to standard output.

58
Example, Prints.java
import java.lang.System;
Import java.lang.*;

class Prints
{
public static void main(String[] args)
{
System.out.print(":Haya ");
System.out.println("This Text in one line");
System.out.printf("\nFormated text;\n%s\t%s\n%s\t%d\n%s\t%d\n","Student","Mark","Ahmad",3,"Sami",5);
System.out.printf(" %x\n",15); // f
System.out.printf(" %o\n",15); // 17
}
}
>javac Prints.java
>java Prints
• %o for octal, %x for hexadicemal, %f for floating point representations.

59
Example, Prints.java
• Formatted output in Java : printf()
• This is the easiest of all methods as this is similar to printf() in C.
• Note that System.out.print() and System.out.println() take a single
argument, but printf() may take multiple arguments.

60
Example
• Name of class called identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )

• Does not begin with a digit, has no spaces

• Java is case sensitive

• Examples: Print, $Print, _Print, Print7 is valid


• 7print is invalid

61
62
Different ways of taking Input from User
Now in the addition of two numbers program I want to take
values of a and b from user.

• In C, we used to write scanf(“%d %d”,&a,&b);


• In Java, we can take input from user in three ways:
1. Command Line arguments
2. BufferedReader Class
3. Scanner Class

63
Command Line Argument
• Data entered by user at runtime will be stored in argument
array and this is known as command line argument.
• Data is accepted as string then converted into required data
type.
• There 2 ways of converting a string into primitive data type
1. Using static method of Integer class called parseInt()
2. Using non static method of Interger class called intValue( )

64
Example:Command Line Argument
class Largest
{
public static void main(String args[])
{
int a= Integer.parseInt (args[0]);
int b= Integer.parseInt (args[1]);
int c= Integer.parseInt (args[2]);
if((a>b) && (a>c))
System.out.println("Larget is ="+ a);
if((b>a) && (b>c))
System.out.println("Larget is ="+ b);
if((c>a) && (c>b))
System.out.println("Larget is ="+ c);
}
}

65
Output:Command Line Argument
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>javac Largest.java

C:\Program Files (x86)\Java\jdk1.8.0_60\bin>java Largest 5 8 2


Larget is =8

66
Input Stream Reader/BufferedReader class
• An InputStreamReader is a bridge from byte streams to character
stream .
• It reads bytes and decodes them into characters using a specified
charset.
• The charset that it uses may be specified by name or may be given
explicitly, or the platform’s default charset may be accepted.

67
Input Stream Reader/BufferedReader class
• BufferedReader is a Java class that reads text from the input stream.

• It buffers the characters so that it can get the efficient reading of


characters, arrays, etc.

• It inherits the reader class and makes the code efficient since we can
read the data line-by-line with the readLine() method.

String readLine()

68
Input Stream Reader/BufferedReader class
• ➢points we have to keep in mind while working with
BufferedReader class in Java.

1. Import java.io package


2. Create object of InputStreamReader class object for wrapping the
buffer size.
InputStreamReader isr=new InputStreamReader(System.in));

BufferedReader br=new BufferedReader(isr);

3. To read data use readLine() method.


4. throws IOException clause to be used in signature of method where 69
Example: Reading name and age
import java.io.*;
class Reading
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("enter your name");
String name= br.readLine();
System.out.println(“enter your age”);
int age=Integer.parseInt(br.readLine());
System.out.println("welcome "+name);
System.out.println(“your age is=“+age);
}
}
70
Scanner Class

• Provides methods for reading byte, short, int,long, float, double, and
String data types from the Java console
• Scanner is in the java.util package
• Scanner parses (separates) input into sequences of characters called
tokens.
• By default, tokens are separated by standard white space characters
(tab, space, newline, etc.)

71
Scanner Class

• The Java Scanner class provides nextXXX() methods to return the


type of value such as nextInt(), nextByte(), nextShort(), next(),
nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc.

• To get a single character from the scanner, you can call


next().charAt(0) method which returns a single character.

72
import java.util.*;
import java.io.*;
class input
{
public static void main(String arg[])throws Exception
{
DataInputStream i=new DataInputStream(System.in);
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(ir);
try
{
System.out.println("Enter your surname:");
String name=in.readLine();
System.out.println("Enter your name:");
String n=i.readLine();
System.out.println("Welcome "+name);
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno:");
int r=sc.nextInt();
System.out.println("Your roll no is:"+r);
int x,y;
x=Integer.parseInt(arg[0]);
y=Integer.parseInt(arg[1]);
System.out.println("x="+x+"\ny="+y);
}
catch(Exception e){}
}
}
73
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>javac input.java
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>java input 4 8
Enter your surname:
ansari
Enter your name:
fatima
Welcome ansari
Enter your rollno:
34
Your roll no is:34
x=4
y=8

74
Wrapper Classes

Wrapper classes define an instance variable of that primitive data type and also
provide useful constants and methods for converting between the objects and
the primitive data types

75
Java Control Structures

76
Control Structure Quest – “Choose Your
Codeventure”
Scenario 1: Traffic Light System

Prompt: The light is RED. What should the code do?


•A. if (light.equals("RED"))
•B. switch(light)
•C. while(true) (Danger: infinite loop!)

Correct answers: A or B. Show both usages.

77
Control Structure Quest – “Choose Your
Codeventure”
Scenario 2: School Attendance

Prompt: You want to print the names of all students.


• A. if (student == present)
• B. for (int i = 0; i < n; i++)
• C. switch(student)

Correct answers: B

78
Control Structure Quest – “Choose Your
Codeventure”
Scenario 3: Amusement Park Entry

•Prompt: Visitors keep coming. Check age until one


enters.
• A. for (int age : visitors)
• B. while (scanner.hasNext())
• C. switch(age)
Correct answers: B

79
80
Constructors in Java
• All objects that are created must be given initial values.
• There are 2 approaches to assign values to an object
1. Using dot operator (tedious approach as to initialize all the
variables of all the objects)
2. Using method like getData() to initialize each object individually.
• It would be more concise to initialize an object when it is first created.
• Solution-------------Java Constructor

81
Constructors in Java
• A constructor is a special block of code that is called
when an object is created.
• Its main job is to initialize the object, to set up its
internal state, or to assign default values to its
attributes.
• This process happens automatically when we use the
"new" keyword to create an object.

82
Rules for writing Constructor
• Constructor(s) of a class must has same name as the class name
in which it resides.
• There are no “return value” statements in constructor.
• A constructor in Java can not be abstract, final, static and
Synchronized.
• Access modifiers can be used in constructor declaration to
control its
access i.e which other class can call the constructor.

83
Types of Java Constructors

•Default Constructor:
• A constructor is called "Default Constructor" when it doesn't have any
parameter.
• If we don’t define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class. And if we
write a constructor with arguments or no-argument then compiler does
not create default constructor.
• Default constructor provides the default values to the object like 0, null
etc. depending on the type.

84
Types of Java Constructors

•Parameterized Constructor:
• A constructor is called “Parameterized Constructor" when it takes
parameter.
• Arguments can be passed to constructors ,in order to initialize the
instance variables of an object.

85
Default Constructor (Example
import java.io.*;
class Student {
int num;
String name;
Student() // this would be invoked while object of that class created.
{ System.out.println ("Constructor is called"); }
}
Class MyClass {
public static void main (String[] args) {
Student obj= new Student(); // this would invoke default constructor.
System.out.println(obj.name);
System.out.println(obj.num); }
}

86
Parameterized Constructor (Example)
class Student{
int id; String name;
Student(int i, String n){
id = i; name = n; }
void display() {
System.out.println(id+" "+name);
} public static void main(String args[])
{ Student s1 = new Student(100,“Varun");
Student s2 = new Student(101,"Alia");
s1.display();
s2.display(); }
}

87
Method Overlaoding
• If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
• If we have to perform only one operation, having same
name of the methods increases the readability of the
program.

88
Method Overlaoding
• There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

Note: In java, Method Overloading is not possible by


changing the return type of the method

89
1. Method Overloading by changing the no. of
arguments
lass Calculation
{
void sum(int a , int b) {
System.out.println(a+b); }
void sum(int a, int b, int c) {
System.out.println(a+b+c); }
public static void main(String args[]) { Output:
30
Calculation obj=new Calculation(); 40
obj.sum(10,10,10);
90
obj.sum(20,20);}
2) Method Overloading by changing data type of
argument

class Calculation{
void sum(int a,int b){
System.out.println(a+b);}
void sum(double a,double b){
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20); } } Output:
21.0
40

91
Why Method Overloading is not possible by
changing the return type of method?
class Calculation {
int sum(int a,int b) {
System.out.println(a+b); }
double sum(int a,int b) {
public static void main(String args[]){
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error
/* Here how can java determine which sum() method should be called
*/ } }

92
Can we overload main() method?

class Simple{
public static void main(int a){
System.out.println(a); }
public static void main(String args[]){
System.out.println("main()method invoked");
main(5); }

Output:
main() method invoked
5
93
Can we overload Constuctor

?
94
Constructor Overloading

• Just like method, constructors can also be overloaded.


• Constructor for a class have the same name as that of the class, but
they can have different signatures, i-e different types of arguments or
different numbers of arguments.
• Such constructor can be termed as overloaded constructor.
• Constructor are differentiated on the basis of the arguments passed to
them

95
Constructor Overloading (Example)

import java.io.*;
class Student{
Student(String name) // constructor with one argument
{ System.out.println("Constructor with one argument - String : " + name); }

Student(String name, int age) // constructor with two arguments


{ System.out.print("Constructor with two arguments : String and Integer : " + name + " "+ age); }

Student(long id) // Constructor with one argument but with different type than previous..
{ System.out.println("Constructor with one argument :Long : " + id);}
class MyClass{
public static void main(String[] args) {
Student obj1= new Student(“SACHIN"); // Invoke the constructor with one argument of type 'String'.
Student obj2= new Student(“SOURAV", 36); // Invoke the constructor with two arguments
Student obj3= new Student(23 ); // Invoke the constructor with one argument of type 'Long'.
96
}}
Static Variables and Methods
The static keyword is used when a member variable of a class has to be
shared between all the instances of the class.
All static variables and methods belong to the class and not to any instance
of the class

97
Static Variables and Methods
When can we access static variable?
When a class is loaded by the virtual machine all the static variables and
methods are available for use.
Hence we don’t need to create any instance of the class for using the static
variables or methods.
Variables which don’t have static keyword in the definition are implicitly
non static.

98
Static Variables and Methods
You want to create a class member that will be used independently of any object
of the class
Also called class variables
One copy of a static variable is created per class
static variables are not associated with an object
static constants are often declared as public
To define a static variable, include the keyword static in its definition:
Syntax:
accessSpecifier static dataType variableName;
Example:
public static int countAutos = 0;

99
Static Variables and Methods
Also called class methods
Often defined to access and change static variables
static methods cannot access instance variables:
static methods are associated with the class, not with any object.
static methods can be called before any object is instantiated, so it is possible that
there will be no instance variables to access.

100
Static Variables and Methods
static Non-static Method
Method
Access instance variables? no yes

Access static class variables? yes yes

Call static class methods? yes yes

Call non-static instance methods? no yes

Use the object reference this? no yes

101
Example: Static Variables and Methods
class staticDemo{
public static int a = 100; /* All instances of staticDemo have this variable as a common `
variable*/
public int b =2 ;
public static showA(){
System.out.println(“A is “ + a);
}
}
class StaticClass{
public static void main(String args[]){
staticDemo.showA();

staticDemo.a = 35; /* when we use the class name, the class is loaded, direct access to a static variable without any instance*/
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after creating an instance.
staticDemo.showA();
}
}Output: ??

102
Packages in Java
◻ Packages enable grouping of functionally related classes
◻ Package names are dot separated, e.g., java.lang.*;
◻ Package names have a correspondence with the directory structure
◻ Packages Avoid name space collision. There can not be two classes
with same name in a same Package But two packages can have a
class with same name.
◻ Exact Name of the class is identifed by its package structure.
▪ << Fully Qualified Name>>
java.lang.String ;
java.util.Arrays;
java.io.BufferedReader ;
java.util.Date

103
Packages in Java
Types of Packages
• User defined package: The package we create is called
user-defined package.

• Built-in package: The already defined package like java.io.*,


java.lang.* etc are known as built-in packages.

104
Built in Packages in Java

105
User defined Packages in Java
package <package name>;

◻ The package keyword is used to create a package in java.


◻Packages are mirrored through directory structure.
◻To create a package, First we have to create a directory
/directory structure that matches the package hierarchy.
◻Package structure should match the directory structure also.
◻To make a class belongs to a particular package include the
package statement as the first statement of source file.

106
User defined Packages in Java
◻To Compile:
javac -d directory javafilename.java
◻To Run:

java packagename.classname
◻The -d switch specifies the destination where to put the generated class
file
◻If you want to keep the package within the same directory, you can use .
(dot).

107
User defined Packages in Java
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package"); } }
◻To Compile: e:sources> javac -d c:classes Simple.java
◻To Run: To run this program from e:source directory, you need to set classpath of the

directory where the class file resides. e:sources> set classpath=c:classes;


e:sources> java mypack.Simple

108

You might also like