You are on page 1of 89

Department of

Computer Science and Engineering

1151CS121:PROGRAMMING USING JAVA

SLOT NO : S1 & S9
UNIT 1 : BASICS OF OOP and JAVA
Faculty Name : Dr. Murali Dhar M S
Academic Year : 2022-2023

School of Computing
Vel Tech Rangarajan Dr. Sagunthala R&D Institute of
Science and Technology
Syllabus

UNIT I BASICS OF OOP and JAVA


Introduction to object-oriented programming - Features of Java - JVM- Keywords-
Variables - Data types – Operators - Control statements -Command line arguments -
Classes and Methods - Objects –Java Packages – Build-in packages - user-defined
package -Access specifiers: private, protected, default, public - Constructors - Method
Overloading - Type Casting - this keyword- Static – Arrays, Multi-dimensional Arrays.
UNIT II INHERITANCE, EXCEPTION HANDLING ANDSTRING
Basics of Inheritance - Forms of Inheritance -Super keyword – Final - Method
Overriding –Abstraction: Abstract Classes - Interfaces. Exception Handling: Java
Exception Hierarchy - Exception Types - Throwing and Catching exceptions -Declaring
New Exception Types – custom exceptions. String class – Immutable String - String
handling methods.

Department of Computer Science and Engineering


UNIT III JAVA STREAMS, COLLECTIONS, UI DESIGN, THREAD
Java Streams: Features, methods – Generic Classes and Methods - Collections
Frameworks: List, Queue, Set and Map. JavaFX: Architecture, Effects,
Transformation, Animation, Layouts, UI Controls, Event Handling. Threads: Life
cycle - Thread states - Thread priority– Thread Synchronization.

Department of Computer Science and Engineering


Syllabus

UNIT IV SERVER PROGRAMMING HIBERNATE FRAMEWORK


Introduction to Servlet and JSP, JDBC, Example Web applications with DB - Basics of
Java Networking. Introduction to Java Frameworks - Basics of Hibernate – Hibernate
Web application - Hibernate Mapping and types – HQL – Annotations – Caching.
Integrating Hibernate and Spring.
UNIT V JAVA SPRING FRAMEWORK
Basics of Spring – Spring in IDE– Dependency Injection – Constructor Injection –
Spring ORM: Spring with Hibernate – SPEL -Spring MVC – Spring Web – Spring
JDBC – Spring with Angular – Spring Boot.

Department of Computer Science and Engineering


A. Preamble
This course provides basic concepts about Object Oriented Programming, Java
Packages, Exceptions, Database connectivity, Java Streams, JavaFX and Java Servlets,
JSP, Spring and Hibernate. After successful completion of this course learners can able
to develop
software modules for real world problem.

B. Pre-requisite courses:
10210CS101 - Problem Solving using C

Department of Computer Science and Engineering


C. Course Objectives:

Learners are exposed to,


• Implement Basic OOP principles to solve problems
• Practice Java basic constructs
• Build efficient Programming practice in Java
• Web application development with DB servers
• Work on Frameworks such as Spring and Hibernate

Department of Computer Science and Engineering


D. Course Outcomes:

Department of Computer Science and Engineering


Department of Computer Science and Engineering
UNIT I BASICS OF OOP and JAVA
Introduction to object-oriented programming - Features of Java - JVM-
Keywords- Variables - Data types – Operators - Control statements -
Command line arguments - Classes and Methods - Objects –Java Packages
– Build-in packages - user-defined package -Access specifiers: private,
protected, default, public - Constructors - Method Overloading - Type
Casting - this keyword- Static – Arrays, Multi-dimensional Arrays.

Department of Computer Science and Engineering


Introduction to Object-oriented Programming

Software
Evaluation
Ernest Tello, A well known writer in the field of artificial intelligence, compared
the evolution of software technology to the growth of the tree. Like a tree, the
software evolution has had distinct phases “layers” of growth.

Department of Computer Science and Engineering


Procedure-Oriented Programming/ Structured Oriented
Programming
In the procedure oriented approach, the problem is viewed as the sequence
of things to be done such as reading, calculating and printing.
The primary focus is on functions

Department of Computer Science and Engineering


Object Oriented
Paradigm
The major motivating factor in the invention of object-oriented approach is
It treats data as a critical element in the program development
Doesn't allow it to flow freely around the system.
Ties data more closely to the function that operate on it
Protects it from accidental modification from outside function

Department of Computer Science and Engineering


PROCEDURAL ORIENTED PROGRAMMING vs. OBJECT ORIENTED PROGRAMMING

PROCEDURAL ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING


program is divided into small parts program is divided into small parts
called functions. called objects.
top down approach. bottom up approach.
There is no access specifier in procedural have access specifiers like private, public,
programming. protected etc.
does not have any proper way for hiding
provides data hiding so it is more secure.
data so it is less secure.
Overriding is possible in object oriented
Overriding is not possible.
programming.
function is more important than data. data is more important than function.
Procedural programming is based on unreal Object oriented programming is based
world. on real world.
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.

Department of Computer Science and Engineering


Features of Java
James Gosling and his team members in the early 90’s.
Java language project was started 1991.
Green Team
James Gosling,
Mike Sheridan,
Patrick Naught.
Initially, the name of the Java language was "Greentalk“
Then it was named as Oak June 1991
1995 : oak renamed as Java
JDK1.0(1996)---First java release

private and protected keywords could be used together to


create yet another form of protection
restriction to methods or variables mainly to subclasses

Department of Computer Science and Engineering


VERSIONS

JDK 1.1(1997)
JDK 1.2(1998)
JDK 1.3(2000)
JDK 1.4(2002)
JDK 1.5(2004)
JDK 1.6(2006)
JDK 1.7(2011)
JDK 1.8(2014)
JDK 1.9 (2017)
JDK 1.10 (March 2018)
JDK 1.11(Sep 2018)
JDK 1.12(March 2019)
JDK 1.13 (September 2019)
JDK 1.14(March 2020)
JDK 1.15 (September 2020)

Department of Computer Science and Engineering


TIOBE Index for August
2021

Department of Computer Science and Engineering


Department of Computer Science and Engineering
JAVA
Frameworks

Department of Computer Science and Engineering


Companies using Java

9348 companies reportedly use Java in their tech stacks,


including Uber, Airbnb, and Google.
Uber.
Airbnb.
Google.
Pinterest.
Netflix.
Instagram.
Spotify.
Amazon.

Department of Computer Science and Engineering


Applications of Java
Web Development
Game Development
Machine Learning and Artificial Intelligence
Data Science and Data Visualization
Desktop GUI
Business Applications
Audio and Video Applications
CAD Applications
Embedded Applications
Mobile Application Development

31-08-2022 Department of Computer Science and Engineering


C++ vs
Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.
Java is mainly used for
application programming. It is
C++ is mainly used for system
Mainly used for widely used in Windows-
programming.
based, web-based, enterprise,
and mobile applications.
Java was designed and created
as an interpreter for printing
C++ was designed for systems and systems but later extended as
applications programming. It was an
Design Goal extension of the a support network computing.
C programming language. It was designed to be easy to
use and accessible to a
broader audience.
Java doesn't support the goto
Goto C++ supports the goto statement.
statement.
Java doesn't support multiple inheritance
C++ supports multiple through class. It can be achieved by using
Multiple inheritance
inheritance. interfaces in java.
C++ supports Java doesn't support operator
Operator Overloading operator overloading. overloading.
Java supports pointer
Department of Computer Science and Engineering
internally. However, you can't
Java uses both compiler and
interpreter. Java source code is
C++ uses compiler only. C++ is
converted into bytecode at
compiled and run using the
compilation time. The
compiler which converts
Compiler and Interpreter interpreter executes this
source code into machine
bytecode at runtime and
code so, C++ is platform
produces output. Java is
dependent.
interpreted that is why it is
platform-independent.
Java supports call by value
Call by Value and Call by C++ supports both call by
only. There is no call by
reference value and call by reference.
reference in java.
C++ supports structures and Java doesn't support
Structure and Union
unions. structures and unions.
C++ doesn't have built-in
support for threads. It relies Java has built-in thread
Thread Support
on third-party libraries for support.
thread support.

Department of Computer Science and Engineering


Java supports documentation
C++ doesn't support comment (/** ... */) to create
Documentation comment
documentation comments. documentation for java source
code.

Java has no virtual keyword.


C++ supports virtual keyword We can override all non-static
Virtual Keyword so that we can decide whether methods by default. In other
or not to override a function. words, non-static methods are
virtual by default.

Java supports unsigned right


shift >>> operator that fills
C++ doesn't support >>> zero at the top for the
unsigned right shift >>>
operator. negative numbers. For positive
numbers, it works same like >>
operator.

Department of Computer Science and Engineering


Java always uses a single
inheritance tree because all
C++ always creates a new classes are the child of the
Inheritance Tree Object class in Java. The
inheritance tree.
Object class is the root of the
inheritance tree in java.

Java is not so interactive with


Hardware C++ is nearer to hardware.
hardware.

Java is also an
object-oriented language.
C++ is an object-oriented However, everything (except
language. However, in the C fundamental types) is an
Object-oriented
language, a single root object in Java. It is a single
hierarchy is not possible. root hierarchy as everything
gets derived from
java.lang.Object.

Department of Computer Science and Engineering


Object Oriented
Features
The basic Object-oriented programming concepts are

Department of Computer Science and Engineering


Object
Real world entity
attributes and
behaviour
Class
Blue print or template
for object.
Collection of Similar
objetd

Department of Computer Science and Engineering


Inheritance Polymorphism
Deriving the child class from Object taking more than one
base class. form.
Reusability of code. Static, Dynamic polymorphism

Department of Computer Science and Engineering


Abstraction
Hiding internal details and showing functionality
Encapsulation
Binding (or wrapping) code and data together into a single unit

Department of Computer Science and Engineering


JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.
The JVM has two primary functions:
To allow Java programs to run on any device or operating system (known as
the "Write once, run anywhere" principle),
To manage and optimize program memory.
Modern JVMs take bytecode and compile it into native code when first needed. "JIT"
in this context stands for "just in time." It acts as an interpreter from the outside,
but really behind the scenes it is compiling into machine code

Department of Computer Science and Engineering


JVM Architecture

Abstract machine.
provides runtime environment in which java bytecode can be
executed.
Platform dependent
The JVM performs following operation:

Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for

Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.

Department of Computer Science and Engineering


JAVA
Keywords
Keywords:

known as reserved words.


it cannot be used as a variable or object name.
Meanings are predefined
abstra assert boolean break
. ct
byte case catch char
class const continue default
do double else enum
extend final finally float
s
for null if implements
import instance int interface
of
long native new package
privat protecte public return
e d
short static strictfp super
Department of switch
Computersynchro
Science andthis
Engineering throw
nized
JAVA
Variables
container which holds the value while the Java program is executed.
a name of memory location
Value will be changeable.
E.g int a=10, String s=“raja”
Rules for variable name:
All variable names must begin with a letter of the alphabet, an
underscore.
You cannot use a java keyword.
variable names may also contain letters and the digits 0 to 9. No
spaces or special characters are allowed.
variable names are case-sensitive

Department of Computer Science and Engineering


Department of Computer Science and Engineering
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among all
the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.

Department of Computer Science and Engineering


Example:
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Department of Computer Science and Engineering


Data Types

Department of Computer Science and Engineering


specify the different sizes and values that can
be stored in the variable.
There are two types of data types in Java: Data Type Default Default size
Primitive data types Value
Boolean
byte boolean false 1 bit
char
short char '\u0000' 2 byte
int
long byte 0 1 byte
float short 0 2 byte
double
Non primitive data types int 0 4 byte
Class
Interface long 0L 8 byte
Array float 0.0f 4 byte
double 0.0d 8 byte

Department of Computer Science and Engineering


Department of Computer Science and Engineering
Simple Java Program Execution
public class FirstJavaProgram
{
public static void main(String[] args)
{
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

To Set Path
set path=C:\Program Files\Java\jdk1.8.0_121\bin
export JAVA_HOME=/Library/Java/Home
echo $JAVA_HOME
To compile
javac FirstJavaProgram.java
To Run
java FirstJavaProgram

Department of Computer Science and Engineering


Compiled Languages

Program
mer
Executable
Object Code
Source Code
Code
Text Compil linker
Editor er
.c .o file a.out
file file
Notepa gc
d, c
emacs,v
i
Department of Computer Science and Engineering
Java is Compiled and Interpreted

Program Hardware
mer and
Operating
System
Source Code Byte
Text Compil Code Interp
Editor er reter
.java .class
file file
Notepad, javac java
emacs,vi appletviewer
netscape

Department of Computer Science and Engineering


Operators in
JAVA
Operator in Java is a symbol which is
used to perform operations. Operato Category Operators in
There are 8 types of operators in Java r Type Precedence order
which are given below Unary postfix expr++ expr--
Unary Operator, prefix ++expr --expr +expr -expr ~ !
Arithmetic Operator,
Shift Operator, Arithme multiplicative * / %
Relational Operator, tic
Bitwise Operator, additive +-
Logical Operator, Shift shift << >> >>>
Ternary Operator and Relation comparison < > <= >= instanceof
Assignment Operator. al
equality == !=
Bitwise bitwise AND &
bitwise ^
exclusive OR
bitwise |
inclusive OR
Logical logical AND &&
logical OR ||
Department of Computer Science and Engineering
Ternary ternary ?:
Example
Assignment operator:
Int a=10;
a+=1------ a=a+1
a-=2------a=a-2
Shift operator:
10<<2 //10*2^2=10*4=40
10>>2//10/2^2=10/4=2
Logical operator:
a=5 ,b=10
a>10 && b<10----False && False--False
a>10 || b<=10----- False || True- True
Bitwise operator:
a = 60 and b = 13
Unary operator:
a=10
a++➔a=a; a=a+1
++a- a=a+1;
Ternary Operator:
a=10,b=20;
c=a>b?a:b

Department of Computer Science and Engineering


Unary Operator Example

class UnaryOperator
{
public static void main(String[] args)
{
double number = 5.2, resultNumber;
Output?
boolean flag = false;
System.out.println("+number = " +
+number);
System.out.println("-number = " + -
number);
System.out.println("number = " + +
+number);
System.out.println("number = " + --
number);
System.out.println("!flag = " + !flag);
}
}
Department of Computer Science and Engineering
Logical Operator Example

class LogicalOperator
{
public static void main(String[] args)
{
int number1 = 1, number2 = 2, number3 Output?
= 9;
boolean result;
result = (number1 > number2) ||
(number3 > number1);
System.out.println(result);
result = (number1 > number2) &&
(number3 > number1);
System.out.println(result);
}
}

Department of Computer Science and Engineering


Ternary Operator Example

class ConditionalOperator
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" :
"Leap year";
System.out.println(result);
}
Output?
}

Department of Computer Science and Engineering


Bitwise Operator
Example
public class Test
{
public static void main(String args[])
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
int d=1; Output?
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~d; /*-2 = 1000 0010 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("aDepartment
>>> 2 = "of+ Computer
c ); Science and Engineering
}
Assignment Operator Example

public class ChainAssign


{
public static void main(String
args[])
{
int a, b, c; Output?
a = b = c = 100; // set a, b, and c to
100
a+=10;
b*=20;
c-=10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Department of Computer Science and Engineering
Assignment Relational Example
public class relatiop {
public static void main(String[] args)
{
//Variables Definition and Initialization
int num1 = 12, num2 = 4;
//is equal to
System.out.println("num1 == num2 = " + (num1 Output?
== num2) );
//is not equal to
System.out.println("num1 != num2 = " + (num1 !=
num2) );
//Greater than
System.out.println("num1 > num2 = " + (num1 >
num2) );
//Less than
System.out.println("num1 < num2 = " + (num1 <
num2) );
//Greater than or equal toof Computer Science and Engineering
Department
Control
statements
Statement which execute set of code based on
condition
The following are the control statements in java If-else statement
Java If-else Statement if(condition){
java switch statement //code if condition is true
Java for loop }else{
Java while loop //code if condition is false
Java do while }
Break
Continue
Output?

public class Sample {


public static void main(String[] args) {
int age=26;
if(age>18){
System.out.print("Age is greater tha
n 18");
}
else
System.out.print("Age is less than 18");

}
Department of Computer Science and Engineering
}
Nested IF-Else
Example
class NestedIfDemo Nested if statements:
{ if(condition){
public static void main(String args[]) //code to be executed
{ if(condition){
int i = 10; //code to be executed
}
if (i == 10) else
{ {
// First if statement //false code
if (i < 15) }
System.out.println("i is smaller than }
15"); else
{
// Nested - if statement //false code
// Will only be executed if statement }
above
// it is true Output?
if (i < 12)
System.out.println("i is smaller than
12 too");
else
System.out.println("i is greater than
15");
} Department of Computer Science and Engineering
Continue…….

public class SwitchCaseExample1


{
public static void main(String args[])
{
int num=2;
switch(expression){ switch(num+2)
case value1: {
// case 1:
code to be executed; System.out.println("Case1: Value is: "+num);
break;
break; //optional case 2:
case value2: System.out.println("Case2: Value is: "+num);
break;
//
case 3:
code to be executed; System.out.println("Case3: Value is: "+num);
break;
break; //optional default:
...... System.out.println("Default: Value is: "+num);
}
default: }
}
code to be executed if
all cases are not matc
hed;
}
Department of Computer Science and Engineering
Continue…….

SYNTAX
public class Sample {
for(initialization;condition;incr/ public static void main(String[] args) {
decr)
{
// for(int i=0;i<=100;i++){
statement or code to be execu System.out.println(i);
ted }
} }
}

Output?

Department of Computer Science and Engineering


Continue…….

SYNTA public class WhileSample {


X public static void main(String[] args) {
int i=0;
while(condition) while(i<=100){
{ System.out.println(i);
// i++;
code to be execut }
ed }
} }

SYNTAX public class DoWhileSample {


public static void main(String[] args) {
int i=0;
do{
do{
//
System.out.println(i);
code to be execute
i++;
d
}while(i<=100);
}while(condition);
}
}

Department of Computer Science and Engineering


Break Statement

the Java break statement is used to break loop or switch statement.


It breaks the current flow of the program at specified condition.
Used in all types of loops such as
for loop, while loop and do-while loop.

public class BreakExample { Output?


public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
Department of Computer Science and Engineering
}
Continue Statement
It continues the current flow of the program and skips
the remaining code at the specified condition.
can used in all types of loops such as for loop, while
loop and do-while loop.

public class ContinueExample {


Output?
public static void main(String[] args)
{
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//
it will skip the rest statement
}
System.out.println(i);
}
}
Department of Computer Science and Engineering
}
Class, Object and Methods
An object in Java is the physical as well as a logical entity.
An object is an instance of a class
An object has three characteristics:
State:
represents the data (value) of an object.
Behavior:
represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
Identity
An object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user.
A class is a template or blueprint from which objects are created.
A class is a group of objects which have common properties.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface

Department of Computer Science and Engineering


Class and Object Example

Department of Computer Science and Engineering


Continue…….

class Student{
Syntax for class: int id;
class <class_name>{ String name;
fields or attributes; void display()
methods; {
System.out.println("id is:"+id+"name
} is:"+name);
Syntax for creating object: }
class_name obj_name=new }
class_name(params); class TestStudent2{
Obj_name.instance_variable; public static void main(String args[]){
Student s1=new Student();
Obj_name.method1() s1.id=101;
s1.name=“Raja";
System.out.println(s1.id+" "+s1.name);
s1.display();
}
}
Output?

Department of Computer Science and Engineering


Continue…….

Method: class Addition


In Java, a method is like a function which {
is used to expose the behavior of an int a,b;
public int sum()
object. {
Advantage of Method return a+b;
Code Reusability }
}
Code Optimization Class MainClass
{
public static void main(String args[]){
{
Addition obj=new Addition();
obj.a=10;
SYNTAX: Obj.b=20;
Return_type System.out.println(obj.sum())
function_name(argument list) }
}
{ Output?
// code
}

Department of Computer Science and Engineering


Access
specifiers
The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class.
Private:
The access level only within the class.
cannot be accessed 6yfrom outside the class.
Default:
The access only within the package.
cannot be accessed from outside the package.
If you do not specify any access level, it will be the
default.
Protected:
The access level is within the package and outside
the package through child class.
Public:
The access level of a public modifier is everywhere.
accessed from within the class, outside the class,
within the package and outside the package.

Department of Computer Science and Engineering


Department of Computer Science and Engineering
Continue…….

Access within class within package outside package outside package


Modifier by subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Department of Computer Science and Engineering


Continue…….

class A{
private int data=40;
public void msg(){System.out.println("Hello java");}
}

class Simple{
public static void main(String args[]){ Output?
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//No error
}
}

Department of Computer Science and Engineering


Constructor
s
What is constructor?
special type of method which is used to initialize the object.

It is called when an instance of the class is created.

At the time of calling constructor, memory for the object is

allocated in the memory.

Rules for creating Java constructor


Constructor name must be the same as its class name

A Constructor must have no explicit return type

A Java constructor cannot be abstract, static, final, and

synchronized

Department of Computer Science and Engineering


Types of Java
constructors

Types of Java constructors


Default constructor (no-arg constructor)
A constructor is called "Default
Constructor" when it doesn't have
any parameters

Implicitly by JVM
Explicitly by programmer
Parameterized constructor
A constructor which has a specific
number of parameters is called a
parameterized constructor.

Department of Computer Science and Engineering


Continue…….

Syntax:
Access_specifier Class_name()
{
// intitialization code
}

Default constructor By programmer Example:


class A{
//creating a default constructor
int a;
int b;
A()
{
a=10;
b=20;
}
//main method
public static void main(String args[]){
//calling a default constructor
A obj=new A();
}
} Department of Computer Science and Engineering
Continue…….

Default constructor by JVM


class A{
int a;
int b;
//main method
public static void main(String args[]){
//calling a default constructor created by
JVM
A obj=new A();
System.out.println(“a=”+obj.a+”b=”+obj.b
)
}
}

Department of Computer Science and Engineering


Continue…….

Syntax:
Access_specifier Parameterized Constructor Example:
Class_name(parameters list) class Student4{
{ int id;
String name;
// intitialization code
Student4(int i,String n)
} {
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Kara
n");
s1.display();
}
}

Department of Computer Science and Engineering


Method Overloading

a class has multiple methods having same name but different in


parameters.
Compile time polymorphism
Different ways to overload the method
By changing number of arguments
By changing the data type
In Java, Method Overloading is not possible by changing the return type
of the method only.

Department of Computer Science and Engineering


By changing number of arguments
class Adder{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(11,11,11));
}
}

Department of Computer Science and Engineering


By changing the data type

class Adder{
int add(int a, int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(12.3,12.6));
}}
Department of Computer Science and Engineering
Type Casting

What is Type casting?


Casting is a process of changing one type value to another type.
In Java, we can cast one type of value to another type.
It is known as type casting.
type casting is classified into two types,
Widening Casting(Implicit)
the target type is larger than the source type
Narrowing Casting(Explicitly done)
When assigning a larger type value to a variable of smaller type.
The target type is smaller than source type
Convert explicitly by programmer

Department of Computer Science and Engineering


Type
Casting
Syntax:
(destination_type)data
Example:
Int x=10;
double d=x;
float f=(float)d;
long l=(long)d;

Department of Computer Science and Engineering


Continue…
….

public class Test


{ public static void main(String[] args)
{
double d = 100.04;
float f=(float)d;// explicit type casting Output?
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
System.out.println("float value"+f);
}
}

Department of Computer Science and Engineering


‘this’
keyword
this Keyword
this is a reference variable that refers to the current
object.
Usage of java this keyword
this can be used to refer current class instance
variable.
this can be used to invoke current class method
(implicitly)
this() can be used to invoke current class
constructor.
this can be passed as an argument in the method
call.
this can be used to return the current class
instance from the method.

Department of Computer Science and Engineering


Example Program

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee; Output?
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Department of Computer Science and Engineering


Static Keyword

Static keyword
The static keyword in Java is used for memory management mainly.
We can apply static keyword with variables, methods, blocks and nested
classes.
The static keyword belongs to the class rather than an instance of the
class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class

Department of Computer Science and Engineering


Java static variable:

The static variable can be used to refer to


the common property of all objects .
The static variable gets memory only once
at the time of class loading.
To access no object is required

Department of Computer Science and Engineering


Continue…
….
class Counter2{
static int count=0;
int a;

Counter2(){
count++;
a=10;
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}

Department of Computer Science and Engineering


Department of Computer Science and Engineering
Continue…
….
Static Method:
If you apply static keyword with any method, it is
known as static method. class Calculate{
belongs to the class rather than the object of a class. static int a;
can be invoked without the need for creating an int b;
instance of a class. static int cube(int x)
can access static data member and can change the {
a=10;
value of it.
return x*x*x;
There are two main restrictions for the static }
method.
public static void main(Stri
ng args[]){
The static method can not use non static data int result=Calculate.cube(5
member or call non-static method directly. );
this and super cannot be used in static context.
System.out.println(result);
}
} Output?

Department of Computer Science and Engineering


Continue…
….
Java static block
Is used to initialize the static data member.
It is executed before the main method at the time
of class loading.

class A2{
static Output?
{
System.out.println("static block is invok
ed");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

Department of Computer Science and Engineering


Array
s
What is an array?
an array is a collection of similar type of elements which has
contiguous memory location.
which contains elements of a similar data type.
Types of Array in java
Single Dimensional Array
Multidimensional Array
Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];
Initialization:
arrayRefVar[0]=10
Department of Computer Science and Engineering
1D Example

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20; Output?

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]);
} Department of Computer Science and Engineering
Multi Dimensional
Array
Array having more than one index
data is stored in row and column based index (also known as matrix form).
Example to instantiate Multidimensional Array in
Java
Syntax to Declare Multidimensional
Array in Java int[][] arr=new int[3][3];//3 row and 3 column
dataType[][] arrayRefVar; (or) Example to initialize Multidimensional Array in
dataType [][]arrayRefVar; (or) Java
dataType arrayRefVar[][]; (or)
Syntax for Instantiation arr[0][0]=1;
arrayRefVar=new dataType[size][size]; arr[0][1]=2;
Both in same statement: arr[0][2]=3;
dataType[][] arrayRefVar arr[1][0]=4;
arrayRefVar=new dataType[size][size]; arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Declarion+instantiation+intialization
Int[][] arr={{1,2,3},{4,5,6},{7,8,9}}
Department of Computer Science and Engineering
2D Array Representation in
memory

Department of Computer Science and Engineering


2D
Example

class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++) Output?
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Department of Computer Science and Engineering


References

[1] Herbert Schildt, “Java the Complete Reference”, Ninth


edition, Tata Mc-GrawHill ,2014.
[2] E. Balaguruswamy, “Programming in java”, Fourth
Edition, Tata McGraw Hill,2010
[3] https://www.javatpoint.com/
[4]https://www.tutorialspoint.com/java/
[5]https://www.studytonight.com/java/type-casting-in-
java.php

Department of Computer Science and Engineering

You might also like