Mca(scheme- 2022 ) 2nd sem (Java) module 1
Mca(scheme- 2022 ) 2nd sem (Java) module 1
MODULE 1
Object Oriented Programming Using Java
The Java Language:
• Java was initiated by James Gosling and others at Sun Microsystems in 1991.
• Team: Mike Sheridan and Patrick Naughton
• This language was initially called “OAK”.
• Later it was renamed as “JAVA” in 1995.
• It is one of the world’s most widely used computer language.
• From practical point of view, it is an excellent language to learn.
• Java was perfect for the Web.
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ supports both call by value and Java supports call by value only.
call by reference. There is no call by reference in java.
Features of Java
The Java Features are:
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple
• Java is very easy to learn, and its syntax is simple,clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarelyused features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
• Java is an object-oriented programming language. Everything in Java is an object.
• Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to any
platform.
• It doesn't require any implementation.
Platform Independent:
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language.
Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Robust
• Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
High Performance
• Bytecode is highly optimised.
• JVM execute Bytecode much faster
Multithreaded
• Multithreading means handling more than one job at a time.
• The main advantage of multi-threading is that it shares the same memory.
Distributed
• Java programs can be shared over the internet
• Inheritance:
o When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance.
• Polymorphism:
o we can perform a single action in different ways.
o Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
o There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
o We can perform polymorphism in java by method overloading and
method overriding.
• Encapsulation:
o Binding (or wrapping) code and data together into a single unit is
known as encapsulation.
Advantages of Inheritance
Flexibility: Inheritance makes the code flexible to change, as you will adjust only in
one place, and the rest of the code will work smoothly.
Overriding: With the help of Inheritance, you can override the methods of the base
class.
Data Hiding: The base class in Inheritance decides which data to be kept private,
such that the derived class will not be able to alter it.
Data Abstraction
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
JVM
• JVM (Java Virtual Machine) is an abstract machine
• It is called a virtual machine because it doesn't physically exist.
• It is a specification that provides a runtime environment in which Java bytecode
can be executed.
• It can also run those programs which are written in other languages and compiled
to Java bytecode.
• JVMs are available for many hardware and software platforms.
• JVM, JRE, and JDK are platform dependent because the configuration of each OS
is different from each other. However, Java is platform independent.
JRE
• JRE is an acronym for Java Runtime Environment.
• It is also written as Java RTE. The Java Runtime Environment is a set of software
tools which are used for developing Java applications.
• It is used to provide the runtime environment. It is the implementation of JVM.
• It physically exists. It contains a set of libraries + other files that JVM uses at
runtime.
JDK
JDK (Java Development Kit) is a software development kit required to develop
applications in Java.
• you download JDK, JRE is also downloaded with it.
• In addition to JRE, JDK also contains a number of development tools (compilers,
JavaDoc, Java Debugger, etc).
How Java Code Runs?
Introducing Classes:
• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created. It is a logical entity. It
can't be physical.
• A class in Java can contain:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface
• An object is an instance of a class.
type method1(parameters){
//body of the method
}
type method2(parameters){
//body of the method
}
//…..
type methodN(parameters){
//body of the method
}
}
Objects
• A Java object is a member (also called an instance) of a Java class.
• Each object has an identity, a behavior and a state. The state of an object is stored
in fields (variables), while methods (functions) display the object's behavior.
Creating an Object
There are three steps when creating an object from a class
• Declaration - A variable declaration with a variable name with an object type.
• Instantiation - The 'new' keyword is used to create the object.
• Initialization - The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
• To create a simple java program, you need to create a class that contains main
method.
Ex1:
class Simple {
public static void main(String args[]) {
System.out.println("Hello Java");
}
}
• save this file as Simple.java
• To compile:javac Simple.java
• To execute: java Simple
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility, it means it is
visible to all.
• static is a keyword, if we declare any method as static, it is known as static method.
The core advantage of static method is that there is no need to
create object to invoke the static method. So it saves memory.
• void is the return type of the method, it means it doesn't return any value.
• main represents startup of the program.
• String[] args is used for command line argument.
• System.out.println() is used print statement.
Example:
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in litres
int mpg; // fuel consumption in miles per litres
}
• A class definition creates a new data type. In this case, the new data type is called
Vehicle.
• You will use this name to declare objects of type Vehicle.
• To create a Vehicle object, you will use a statement such as the following:
• Vehicle minivan= new Vehicle();
• After this statement executes, minivan will be an instance of Vehicle.
• The dot operator(.) links the name of an object with the name of a member.
• The general form of the dot operator is
object.member
Ex:
minivan.fuelcap=16;
• In general the dot(.)operator is used to access both instance variables and
methods.
class Vehicle {
int passengers; int fuelCap; int mpg;
}
class VehicleDemo {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
int range;
minivan.passengers = 7;
minivan.fuelCap = 16;
minivan.mpg = 21;
range = minivan.fuelCap * minivan.mpg;
System.out.println("Minivan can carry " + minivan.passengers + " with
a range of " + range);
}
}
Java Comments
The java comments are statements that are not executed by the compiler and
interpreter.
Example:
class CommentExample1 {
public static void main(String[] args) {
int i=10; //Here, i is a variable
System.out.println(i);
}
}
Example:
class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Type Meaning
boolean Represents true/false values
JAVA KEYWORDS
• In the Java programming language, a keyword is any one of 55 reserved words
that have a predefined meaning in the language; because of this, programmers
cannot use keywords as names for variables, methods, classes, or as any other
identifier.
Although const and goto are reserved words, they are not currently part of the
Java language.
Java Variables
• A variable is a container which holds the value while the java program is executed.
• A variable is assigned with a datatype.
• There are three types of variables in java: local, instance and static.
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.
Instance Variable
• A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
Static variable
• A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of
the class.
class A {
int data=50;//instance variable
static int m=100;//static variable
void method() {
int n=90;//local variable }
}//end of class
class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya");
s1.display();
s2.display();
}
}
• Variables are declared using this form of statement.
type var-name;
• Here type is the date type of the variable and varname is its name.
• The type of the variable cannot be change during its lifetime.
Ex:
an int variable cannot turn into a char variable
Initializing a variable:
• follow the variable’s name with an equal sign and the value being assigned.
- The general form of initialization is shown here
type var=value;
Ex:
int count=10;
char ch =‘a’;
float f=1.2;
• When declaring two or more variables of the same type using a comma-separated
list.
Ex: int a,b=10,c,d=15;
Operators
• Operators in Java are the symbols used for performing specific operations in
Java. Operators make tasks like addition, multiplication, etc which look easy
although the implementation of these tasks is quite complex.
1. Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
• The operands of the arithmetic operators must be of a numeric type.
• You cannot use them on boolean types, but you can use them on char
types, since the char type in Java is a subset of int.
• The following table lists the arithmetic operators:
Operator Result
+ Addition
- Substraction(Also unary minus)
* Multiplication
/ Division
% Modulus
EX:2
x = 42;
y = ++x;
• In this case, y is set to 43 as you would expect, because the increment
occurs before x is assigned to y. Thus, the line y = ++x; is the equivalent
of these two statements:
x = x + 1; y = x;
• However, when written like this,
x = 42;
y = x++;
• the value of x is obtained before the increment operator is executed, so
the value of y is 42.
• Of course, in both cases x is set to 43. Here, the line y = x++; is the
equivalent of these two statements:
y = x;
x = x + 1;
Example:
00101010 42
& 00001111 15
----------------------------------
00001010 10
4. Shift Operators
5. Relational Operators:
• The relational operators determine the relationship that one operand has to the
other.
• Specifically, they determine equality and ordering. The relational operators are
shown here:
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Lessthan
>= Greaterthan or equal to
<= Lessthan or equal to
6. Logical Operators:
• The Boolean logical operators shown here operate only on boolean
operands.
Operator Result
& Logical AND
| Logical OR
! Logical NOT
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
• The logical Boolean operators, &, |, and ^, operate on boolean values in
the same way that they operate on the bits of an integer.
• The logical ! operator inverts the Boolean state:
o !true == false and !false == true.
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a; int a=10; int b=5;
int c=20;
System.out.println(a<b&&a<c);
System.out.println(a<b&a<c);
EX:
class OperatorExample {
public static void main(String args[])
{
int a=10; int b=5;
int c=20; System.out.println(a<b&&a++<c); System.out.println(a);
System.out.println(a<b&a++<c); System.out.println(a);
}
}
• The logical || operator doesn't check second condition if first condition is true.
• It checks second condition only if first one is false.
• The bitwise | operator always checks both conditions whether first condition is
true or false.
EX:
class OperatorExample {
public static void main(String args[]) {
int a=10, b=5, c=20;
System.out.println(a>b||a<c);
System.out.println(a>b|a<c);
System.out.println(a>b||a++<c);
System.out.println(a);
System.out.println(a>b|a++<c);
System.out.println(a);
}
}
Expressions
•An expression is a syntactic construction that has a value.
•Expressions are formed by combining variables, constants, and method
returned values using operators.
The Type Promotion Rules:
• With in expression, it is possible to mix two or more different types of data
as long as they are compatible with each other.
• you can mix short and long within an expression because they are both
numeric types.
• When different types of data are mixed an expression, they are all
converted to the same type.
• All char, byte and short values are promoted to int.
• If one operand is a long, the whole expression is promoted to long.
• If one operand is a float operand, the entire is promoted to float.
• If one operand is double, the result is double
Ex:
class rnsit {
public static void main(String[] args)
{
byte b; int i; b=10;
char ch1=‘a’,ch2=‘b’; ch1=(char)(ch1 + ch2);
i=b * b; // no cast needed System.out.println(“ i and b:” +i+ “ “
+b);
System.out.println(ch1);
}
}
• No cast is needed when b*b=i, because b is promoted to int when the
expression is evaluated.
• The same sort of situation also occurs when performing operations on
char.
• Without the cast, the resulting of adding ch1 and ch2 would be int, which
can’t be assigned to a char.
EX:
public class Test {
public static void main(String[] args) {
int i = 100; //occupies 4 bytes
long l = i; // occupies 8 bytes
double f = l; // occupies 8 bytes
System.out.println("Int value "+i); System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
OUTPUT
Int value 100
Long value 100 Float value 100.0
Explicit conversions:
• If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
• The general form of cast is (target-type)expression
• Here, target-type specifies the desired type to convert the specified value to.
• The thumb rule is, on both sides, the same data type should exist.
• EX:
class Test
{
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; int i = (int)l;
System.out.println("Double value "+d); //100.04
System.out.println("Long value "+l); // 100
System.out.println("Int value "+i); // 100
}
}
Control Statements
• There are three types of control statements:
o Selection statements
o Iteration statements
o Jump statements
• Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
• Iteration statements enable program execution to repeat one or more statements.
• Jump statements allow your program to execute in a nonlinear fashion.
Selection statements:
Java if Statement:
• The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}
EX:
public class IfExample {
public static void main(String[] args) {
int age=20; if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Ex:
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a){
System.out.println(“BANGALORE");
}
elseif(a>b){
System.out.println(“DELHI");
} else {
System.out.println(“HYDERABAD");
}
}
}
Nested if statement:
public class Test {
public static void main(String args[]) {
int x = 30; int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print(“BANGALORE"); }
}
}
}
Switch Statement
• The switch statement is Java’s multiway branch statement.
• It provides an easy way to dispatch execution to different parts of your code based
on the value of an expression.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant.
Here is the general form of a switch statement:
switch (expression)
{
case value1:
// statement sequence break;
case value2:
// statement sequence break;
..
case valueN:
// statement sequence
break; default:
// default statement sequence
}
EX:
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<5; i++) switch(i)
{
case 0:
System.out.println(“JAVA"); break;
case 1:
System.out.println(“DBMS"); break;
case 2:
System.out.println(“WEB");
break; case 3:
System.out.println(“UID"); break;
default:
System.out.println(“SOFWARE");
}
}
}
EX2:
• The break statement is optional.
• If you omit the break, execution will continue on into the next case.
• It is sometimes desirable to have multiple cases without break statements between
them.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++) switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4: System.out.println(“MOBILE"); break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println(“APPLICATIONS"); break;
default:
System.out.println(“ENGINEERING"); }
}
}
EX3:
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
Iteration statements:
• Java’s iteration statements are for, while, and do-while.
• These statements create what we commonly call loops.
while
• The while loop is Java’s most fundamental loop statement.
• It repeats a statement or block while its controlling expression is true.
• Here is its general form:
while(condition)
{
// body of loop
}
• The condition can be any Boolean expression.
• The body of the loop will be executed as long as the conditional expression is true.
• When condition becomes false, control passes to the
• next line of code immediately following the loop.
• The curly braces are unnecessary if only a single statement is being repeated.
EX:
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0)
{
System.out.println("tick " + n); n--;
}
}
}
• The body of the while (or any other of Java’s loops) can be empty.
• This is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.
EX2 :
class NoBody {
public static void main(String args[]) {
int i, j; i = 100; j = 200;
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
OUTPUT
It generates the following output:
Midpoint is 150
do-while:
• The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop.
• Its general form is
do
{
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression.
• If this expression is true, the loop will repeat. Otherwise, the loop terminates
EX:
class DoWhileExample {
public static void main(String[] args) {
int i=11;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
• Once the condition becomes false, the loop will exit and program execution will
resume on the statement following of for.
• A for loop is most commonly used when you know that a loop will execute a
predetermined number of times.
• The general form of the for loop for repeating a single statement is
• Missing pieces:
• Some interesting for loop variations are created by leaving pieces of the loop
definition empty .
• In java, it is possible for any or all of the initialization, condition or iteration portions
of the for loop to be blank.
EX:
int i; for(i=0,i<10;)
{
System.out.println(“value of i:“ + i ); i++;
}
Ex2:
class Big {
public static void main (String [] arg) {
int [] myArr = { 45, 5, 34, 8 } ;
int big = myArr[0];
for( int num : myArr)
if ( big<num )
big = num;
System.out.println(“Bigest = ” + big) ;
}
}
EX:
class ForEachExample {
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{
System.out.println(i);
}
}
}
Jump Statements:
• Java supports three jump statements: break, continue, and return.
• These statements transfer control to another part of your program. Break:
• In Java, the break statement has three uses.
• First, as you have seen, it terminates a statement sequence in a switch statement.
• Second, it can be used to exit a loop.
• Third, it can be used as a “civilized” form of goto.
--------------------------------------------------
class BreakLoop4 {
public static void main(String args[]) {
outer:
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++)
{
if(j == 4) break outer; System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
------------------------------------------------
• Keep in mind that you cannot break to any label which is not defined for an
enclosing block.
class BreakErr {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": "); }
for(int j=0; j<100; j++) {
if(j == 10)
break one; // WRONG
System.out.print(j + " ");
}
}
}
Using continue
• The continue statement is used in loop control structure when you need to jump
to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
• The Java continue statement is used to continue the loop.
• It continues the current flow of the program and skips the remaining code at the
specified condition.
EX1:
class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++) {
if(i==5) {
continue;
}
System.out.println(i);
}
}
}
EX2:
class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
• As with the break statement, continue may specify a label to describe which
enclosing loop to continue.
EX3:
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
if(j > i) {
System.out.println(); continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
• The continue statement in this example terminates the loop counting j and
continues with the next iteration of the loop counting i.
Return:
• The last control statement is return.
• The return statement is used to explicitly return from a method.
• That is, it causes program control to transfer back to the caller of the
method.
• At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method.
• Thus, the return statement immediately terminates the method in
which it is executed.
EX:
public class SampleReturn1 {
public int CompareNum() {
int x = 3; int y = 8;
System.out.println("x = " + x + "\ny = " + y);
if(x>y)
return x;
else
return y;
}
public static void main(String ar[]) {
SampleReturn1 ob = new SampleReturn1();
int result = ob.CompareNum();
System.out.println("The greater number am ong x and y is: " + result);
}
}
Java Identifiers:
• All Java components require names. Names used for classes, variables and
methods are called identifiers.
• In Java, there are several points to remember about identifiers. They are as follows:
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
• After the first character identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value
Ex:
public class Test {
public static void main(String[] args) {
int a = 20;
}
}
• In the above java code, we have 5 identifiers namely :
Test : class name.
main : method name.
String : predefined class name.
args : variable name.
a : variable name.
Literals
• In java, literals refer to fixed values that are represented in their human-readable
form.
• Literals are also commonly called constants.
• Java literals can be any of the primitive data types.
• The way each literal is represented depends on its type.
• Character constants are enclosed in single quotes.
Ex:
• char g=‘a’
• char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
• In java, single and double quotes have special meaning is there. So you cannot
use them directly.
• You have to refer backslash(\) character constants.
Ex:
char ch=‘\’’;
• Java supports other type of literal: the string
• The string literal is a set of characters enclosed by double quotes.
Ex:
String s=“mca rnsit”;
String a= "he said \"Hello\" to me."
}
}
class Rectangle {
double length;
double breadth;
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
Rectangle r3 = r2;
r1.length = 20;
r2.length = 25;
System.out.println("Value of R1's Length : " + r1.length);
System.out.println("Value of R2's Length : " + r2.length);
System.out.println("Value of R2's Length : " + r3.length);
}
}
Methods
• A method contains the statements that define its actions.
• In well-written java code, each method performs only one task.
• You can give a method whatever name you please as long as it is a valid identifier.
• Remember that main() is reserved for the method that begins execution of your
program.
• A method will have parentheses after its name.
• For example, if a method’s name is getval,it will written getval() when its name is
used in a sentence
• The general form of a method is,
return-type name(parameter-list) {
//body of method }
• Here, ret-type specifies the type of data returned by the method.
• This can be any valid type, including class types that you can create.
• If the method does not return a value, its return type must be void.
Returning a value
• Returns values are used for a variety of purposes in programming.
• In some cases, such as sqrt(), the return value contains the outcome of some
calculation.
• In other cases, the return value simply indicate success or failure.
• In still others, it may contain a status code.
• Methods return a value to the calling routine using this form of return:
return value:
class Vehicle {
int passengers;
int fuelCap; int mpg;
int range() {
return mpg * fuelCap;
}
}
class RetMeth {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
minivan.passengers = 7;
minivan.fuelCap = 16;
minivan.mpg = 21;
sportscar.passengers = 2;
sportscar.fuelCap = 14;
sportscar.mpg = 12;
range1 = minivan.range();
range2 = sportscar.range();
System.out.println("Minivan can carry " + minivan.passengers + " with
range of " + range1 + " miles");
System.out.println("Sportscar can carry " + sportscar.passengers + "
with range of " + range2 + " miles");
}
}
Constructors
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar
to a method.
• Once defined, the constructor is automatically called immediately after the object
is created, before the new operator completes.
• Constructors look a little strange because they have no return type, not even void.
• This is because the implicit return type of a class constructor is the class type itself.
• It constructs the values i.e. provides data for the object that is why it is known as
constructor.
• Typically ,you will use a constructor to give initial values to the instance variables
defined by the class.
Types of java constructors
• There are two types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
Java Default Constructor
• A constructor that have no parameter is known as
Default constructor
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]) {
Bike1 b=new Bike1();
}
}
Default constructor provides the default values to the object like 0, null etc.
depending on the type.
Ex:
class Student3 {
int id; String name;
void display() {
System.out.println(id+" "+name); }
public static void main(String args[]) {
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Ex1:
class Student4 {
int id; String name;
Student4(int i,String n) {
id = i; name = n;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student4 s1 = new Student4(111,"Kiran");
Student4 s2 = new Student4(222,"Arya");
s1.display();
s2.display();
}
}
EX2:
class Box {
double width; double height; double depth;
Box(double w, double h, double d) {
width = w; height = h;
depth = d;
}
double volume() {
return width * height * depth; }
}
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Ex:1
class Student10{
int id; String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student10 s1 = new Student10(111,“kiran");
Student10 s2 = new Student10(321,"Ajay");
s1.display();
s2.display();
}
}
• In the above example, parameters(formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable
and instance variable.
Ex 1:
class Student11
{
int id; String name;
Student11(int id,String name) {
this.id = id; this.name = name;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student11 s1 = new Student11(111,"Kiran");
Student11 s2 = new Student11(222,"Ajay");
s1.display();
s2.display();
}
}
Ex2:
class A {
void m() {
System.out.println("hello m");
}
void n() {
System.out.println("hello n"); this.m();
}
}
class TestThis4 {
public static void main(String args[]){
A a=new A();
a.n();
}
}
Arrays:
• array is a collection of similar type of elements that have contiguous memory
location.
• Java array is an object that contains elements of similar data type.
• It is a data structure where we store similar elements. We can store only fixed set
of elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index.
A One Dimensional Array is a list of related variables. Such lists are common in
programming .
• To declare a one-dimensional array, you will use this general form:
type[] array-name=new type[size];
• Here, type declares the element type of the array.(The element type is also
sometimes referred to as the base type).
• The element type determines the data type of each element contained in the array.
• The number of elements that the array will hold is determined by size.
• Since arrays are implemented as objects,
• The creation of array is two-step process.
• First, you declare an array reference variable.
• Second, you allocate memory for the array, assigning the reference to that memory
to the array variable.
• Thus, arrays are dynamically allocated using the new operator.
Ex:
int[] sample=new int[10];
• This declaration works like an object declaration.
• The sample variable hold a reference to the memory allocated by new.
• This memory is large enough to hold 10 elements of type int.
• It is possible to break the preceding declaration in two.
int[] sample;
sample=new int[10];
Ex:
class ArrayDemo {
public static void main(String[] args) {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
System.out.println("This is sample[" + i + "]: " + sample[i]);
}
}
}
• Ex2:
class MinMax {
public static void main(String[] args) {
int[] nums = new int[5];
int min, max;
nums[0] = 99;nums[1] = 200;nums[2] = 100; nums[3] = 18;nums[4] = -978;
min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) { if(nums[i] < min) min = nums[i]; if(nums[i] > max) max =
nums[i];
}
System.out.println("min and max: " + min + " " + max); }
}
Contd….
• Arrays can be initialized when they are created.
• The general form for initializing a one-dimensional
array is,
type[] array-name={val1,val2,val3…..valN}
• Here, the initial value are specified by val1 through
valN.
• They are assigned in sequence, left to right, in index
order.
• Java automatically allocates an array large enough to
hold the initializers that you specify.
• There is no need to explicitly use the new operator.
• Ex:
class MinMax2 {
public static void main(String[] args) {
int[] nums = { 99,5623, 463, 287, 49 };
int min, max; min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) {
if(nums[i] < min) min = nums[i]; if(nums[i] > max) max = nums[i];
}
System.out.println("Min and max: " + min + " " + max); }
}
Multidimensional arrays
• In java, multidimensional array or two dimensional
array is a array of arrays.
• A two-dimensional array can be thought of as
creating a table of data, with the data organized by
row and column.
• An individual item of data is accessed by specifying
its row and column position.
• To declare a two-dimensional array, you must specify
the size of both dimensions.
• int [][] table=new int[10][20];
Here table is declared to be a two-dimensional array of int with the size 10 and
20.
Ex:
class TwoD {
public static void main(String[] args) { int t, i;
int[][] table = new int[3][4]; for(t=0; t < 3; t++) {
for(i=0; i < 4; i++) {
table[t][i] = (t*4)+i+1; System.out.print(table[t][i] + " ");
} System.out.println();
class Testarray3 {
public static void main(String args[]) {
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
----------------------------
class Test5 {
public static void main(String args[]) {
int[][] a={{1,3,4},{3,4,5}};
int[][] b={{1,3,4},{3,4,5}}
int c[][]=new int[2][3];
for(int i=0;i<2;i++) {
for(int j=0;j<3;j++) {
c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Ex:
class LengthDemo {
public static void main(String[] args) {
int[] list = new int[10];
int[] nums = { 1, 2, 3 };
int[][] table = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
System.out.println("length of list is " + list.length);
System.out.println("length of nums is " + nums.length);
System.out.println("length of table is " + table.length);
System.out.println("length of table[0] is " + table[0].length);
System.out.println("length of table[1] is " + table[1].length);
System.out.println("length of table[2] is " + table[2].length);
System.out.println();
}
}
Overloading Methods
• If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
• There are two ways to overload the method in java By changing number of
arguments By changing the data type
EX:1
class OverloadDemo {
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
void test(double a)
{
System.out.println("double a: " + a*a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
ob.test(123.25);
}
}
• In some cases, Java’s automatic type conversions can play a role in overload
resolution.
EX:2
class OverloadDemo {
void test()
{
System.out.println("No parameters");
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
void test(double a)
{
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i);
ob.test(123.2);
}
}
EX:3
class mca10 {
int arun(int a)
{
return a;
}
double arun(double a, double b)
{
return a*b;
}
}
class mca85 {
public static void main(String args[]) {
mca10 s=new mca10();
System.out.println(s.arun(10));
System.out.println(s.arun(20.6, 12.5));
}
}
Overloading Constructors
• In addition to overloading normal methods, you can also overload constructor
methods.
EX:
class Box {
double width; double height; double depth;
Box(double w, double h, double d)
{
width = w; height = h;
depth = d; }
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len; }
double volume()
{
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Recursion
• Java supports recursion. Recursion is the process of defining something in terms of
itself.
• As it relates to Java programming, recursion is the attribute that allows a method
to call itself.
• A method that calls itself is said to be recursive.
Ex 1:
class Factorial {
int fact(int n) {
I nt result; if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Ex 2:
class StarDrawer {
void drawStars(int n) {
if(n == 1)
System.out.print("*");
else {
System.out.print("*");
drawStars(n-1);
}
}
}
class StarDrawingDemo {
public static void main(String[] args) {
StarDrawer d = new StarDrawer();
d.drawStars(1);
System.out.println();
d.drawStars(2);
System.out.println();
d.drawStars(3);
System.out.println();
d.drawStars(10);
System.out.println();
}
}
Understanding static
• Normally, a class member must be accessed only in conjunction with an object of
its class.
• However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
• To create such a member, precede its declaration with the keyword static.
• We can apply java static keyword with variables, methods, blocks.
• The static can be: variable (also known as class variable) method (also known as
class method) block
• Methods declared as static have several restrictions:
Ex 1:
Static variables
class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya"); //Student8.college="BBDIT";
s1.display(); s2.display();
}
}
Static Methods
• If you apply static keyword with any method,it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
Ex:2 //TestStatic.java
class Student9 {
int rollno; String name;
static String college = “BMSIT";
static void change()
{
college = “RNSIT";
}
Student9(int r, String n) {
rollno = r; name = n;
}
void display () {
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student9.change();
Student9 s1 = new Student9 (111,"Kiran");
Student9 s2 = new Student9 (222,“Ravi");
Student9 s3 = new Student9 (333,“Ajay");
s1.display();
s2.display();
s3.display();
}
}
Ex 2:
class UseStatic {
static int a = 3; static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically.
• In other words, it is a way to destroy the unused objects.
• To do so, we were using free() function in C language and delete() in C++.
• But, in java it is performed automatically.
• So, java provides better memory management.
• when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed.
finalize() method
• The finalize() method is invoked each time before the object is garbage collected.
• This method is called finalize(),and it can be used in very specialized case to ensure
that an object terminates cleanly.
• To add a finalizer to class, you must define the finalize() method.
• The general form:
protected void finalize()
{
//code
}
• It is important to understand that finalize( ) is only called just prior to garbage
collection.