Unit - 1 Object Oriented Programming Through Java (B.Tech II-I)
Unit - 1 Object Oriented Programming Through Java (B.Tech II-I)
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 1
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Multi-threaded Numbers
Java supports multi-threading programming, which allows us To declare and assign a number use the following syntax:
to write programs that do multiple operations int myNumber;
simultaneously. myNumber = 5;
Interpreted
Java enables the creation of cross-platform programs by Or you can combine them:
compiling into an intermediate representation called Java int myNumber = 5;
bytecode. The byte code is interpreted to any machine code To define a double floating point number, use the following
so that it runs on the native machine.
High performance syntax:
Java provides high performance with the help of features like double d = 4.5;
JVM, interpretation, and its simplicity. d = 3.0;
Distributed If you want to use float, you will have to cast:
Java programming language supports TCP/IP protocols
which enable the java to support the distributed environment float f = (float) 4.5;
of the Internet. Java also supports Remote Method Or, You can use this:
Invocation (RMI), this feature enables a program to invoke float f = 4.5f; // (f is a shorter way of casting float)
methods across a network.
Dynamic Characters and Strings
Java is said to be dynamic because the java byte code may be In Java, a character is it's own type and it's not simply a number, so
dynamically updated on a running system and it has a it's not common to put an ascii value in it, there is a special
dynamic memory allocation and deallocation (objects and
garbage collector). syntax for chars:
Java Comments: char c = 'g';
Comments can be used to explain Java code, and to make it String is not a primitive. It's a real type, but Java has special
more readable. It can also be used to prevent execution when treatment for String.
testing alternative code.
Single-line comments start with two forward slashes (//). Here are some ways to use a string:
Any text between // and the end of the line is ignored by Java // Create a string with a constructor
(will not be executed). String s1 = new String("Who let the dogs out?"); // String
This example uses a single-line comment before a line of object stored in heap memory
code: // Just using "" creates a string, so no need to write it the previous
Example way.
// This is a comment String s2 = "Who who who who!"; // String literal
System.out.println("Hello World"); stored in String pool
// Java defined the operator + on strings to concatenate:
DataTypes & Variables: String s3 = s1 + s2;
Although Java is object oriented, not all types are objects. It String is the only class where operator overloading is supported in
is built on top of basic variable types called primitives. java rest There is no operator overloading in Java! We can concat
two strings using + operator. The operator + is only defined for
Here is a list of all primitives in Java: strings, you will never see it with other objects, only primitives.
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 2
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Example Program:
boolean toBe = false; class GalToLit {
b = toBe || !toBe; public static void main(String[] args) {
if (b) { double gallons; // holds the number of gallons
System.out.println(toBe); double liters; // holds conversion to liters
}
gallons = 10; // start with 10 gallons
int children = 0;
b = children; // Will not work liters = gallons * 3.7854; // convert to liters
if (children) { // Will not work
// Will not work System.out.println(gallons + " gallons is " +
} liters + " liters.");
}
int a; }
boolean b = true;
boolean c = false;
a = b + c; //The following line will give an error
System.out.println(a);
Constants in java: Keywords of Java:
A constant is a variable whose value cannot change once it
has been assigned. Java doesn't have built-in support for
constants.
Defining Constants With Final:
To define a variable as a constant, we just need to add the
keyword “final” in front of the variable declaration.
Syntax
final float pi = 3.14f;
Defining Constants With Integers
One of the most common ways to define constants in Java is Arrays:
through integers, where the integer variables are static. An array is a group of liked-typed variables referred to by a
common name, with individual variables accessed by their index.
public static int MONDAY = 0; Arrays are:
Defining Constants With Enums 1) declared
One other alternative to defining constants in Java is by 2) created
using enums. 3) initialized
4) used
When using enums, our constants class will look something Also, arrays can have one or several dimensions.
like this: Array Declaration:
public enum WeekDay { • Array declaration involves:
MONDAY, 1) declaring an array identifier
TUESDAY, 2) declaring the number of dimensions
WEDNESDAY, 3) declaring the data type of the array elements
THURSDAY, • Two styles of array declaration:
FRIDAY, • type array-variable[];
SATURDAY, or
SUNDAY • type [] array-variable;
} Array Creation:
• After declaration, no array actually exists.
• In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
• This creates a new array to hold size elements of type,
which reference will be kept in the variable array-
variable.
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 3
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Array Indexing: System.out.println(); // Print new line.
array through their indexes: }
• array-variable[index] }
• The array index always starts with zero! }
• The Java run-time system makes sure that Output :
all array indexes are in the correct range, otherwise raises a
run-time error. 10 20 30
Array Initialization:Arrays can be initialized when they are 40 50 60
declared: 70 80 90
int monthDays[] ={31,28,31,30,31,30,31,31,30,31,30,31}; 11 21 31
Note:
1) there is no need to use the new operator Java Console Class
2) the array is created large enough to hold all The Java Console class is be used to get input from console. It
specified elements. provides methods to read texts and passwords.
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays: The java.io.Console class is attached with system console
1) declaration: int array[][]; internally. The Console class is introduced since 1.5.
2) creation: int array = new int[2][3]; The Console’s methods for input and output
3) initialization Then we can use the following methods for dealing with the
int array[][] = { {1, 2, 3}, {4, 5, 6} }; standard input/output streams:
Example Program 1 Dimensional array: format(String fmt, Object... args): works same as
public class PrintArray { System.out.format()
public static void main(String[] args) { printf(String format, Object... args): works same as
//Initialize array System.out.printf()
int [] arr = new int [] {1, 2, 3, 4, 5}; readLine() : works same as BufferedReader.readLine()
System.out.println("Elements of given array: "); readLine(String fmt, Object... args): prints a formatted string
//Loop through the array by incrementing value of i and reads input
for (int i = 0; i < arr.length; i++) { readPassword(): reads a password to a char array
System.out.print(arr[i] + " "); readPassword(String fmt, Object... args): prints a formatted
} string and reads a password to a char array
}
} Java Scanner
Output: Scanner class in Java is found in the java.util package. Java
provides various ways to read input from the keyboard, the
Elements of given array: java.util.Scanner class is one of them.
1 2 3 4 5
Example Program 2 Dimensional array: import java.util.*;
public class ScannerExample {
public class TwoDimArray public static void main(String args[]){
{ Scanner in = new Scanner(System.in);
public static void main(String[] args) System.out.print("Enter your name: ");
{ String name = in.nextLine();
// Array of size 4x3 to hold integers. System.out.println("Name is: " + name);
int[][] values = in.close();
{ } }
{ 10, 20, 30 }, { 40, 50, 60 }, { 70, 80, 90 },
{ 11, 21, 31 }
};
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 4
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
import java.util.*; Parameterized Constructor:
public class ScannerExample { class Box {
public static void main(String args[]){ double width;
int a,b,c; double height;
b=10; double depth;
Scanner input = new Scanner(System.in); Box(double w, double h, double d) {
System.out.print("Enter integer: "); width = w; height = h; depth = d;
a=input.nextInt(); }
c=b*a; double volume()
System.out.println("input after multiplication is : " + c); { return width * height * depth;
} } }}
Example Program:
class Main {
int i;
// constructor with no parameter
Other datatypes and usage in Scanner: private Main() {
Method Inputs i = 5;
nextInt() Integer System.out.println("Constructor is called");
nextFloat() Float }
nextDouble() Double public static void main(String[] args) {
nextLong() Long // calling the constructor without any parameter
nextShort() Short Main obj = new Main();
next() Single word System.out.println("Value of i: " + obj.i);
nextLine() Line of Strings }
nextBoolean() Boolean }
Constructor:
A constructor initializes the instance variables of an object.
It is called immediately after the object is created but before
the new operator completes. class Main {
1) it is syntactically similar to a method: String languages;
2) it has the same name as the name of its class // constructor accepting single value
3) it is written without return type; the default Main(String lang) {
return type of a class languages = lang;
• constructor is the same class System.out.println(languages + " Programming Language");
• When the class has no constructor, the default }
constructor public static void main(String[] args) {
automatically initializes all its instance variables with zero. // call constructor by passing a single value
Example: Constructor Main obj1 = new Main("Java");
class Box { Main obj2 = new Main(“JSP");
double width; Main obj3 = new Main(“STRUCTS");
double height; }
double depth; }
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}}
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 5
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Default Constructor:
class Main {
int a;
boolean b; Static blocks:
public static void main(String[] args) { class JavaExample2{
// A default constructor is called static int num;
Main obj = new Main(); static String mystr;
System.out.println("Default Value:"); static{
System.out.println("a = " + obj.a); System.out.println("Static Block 1");
System.out.println("b = " + obj.b); num = 68;
} mystr = "Block1";
} }
static{
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}
Static keyword in java: public static void main(String args[])
• The static keyword in Java is used for memory {
management mainly. We can apply static keyword System.out.println("Value of num: "+num);
with variables, methods, blocks and nested classes. System.out.println("Value of mystr: "+mystr);
• 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. Java Static Methods:
class SimpleStaticExample class JavaExamples{
{ static int i = 10;
static void myMethod() static String s = "Beginnersbook";
{ //This is a static method
System.out.println("myMethod"); public static void main(String args[])
} {
public static void main(String[] args) System.out.println("i:"+i);
{ System.out.println("s:"+s);
myMethod(); }
} }
}
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 6
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
class Student{ Box(double width, double height, double depth) {
int rollno;//instance variable this.width = width;
String name; this.height = height;
static String college ="JNTU";//static variable this.depth = depth;
//constructor }
Student(int r, String n){ Program:
rollno = r; public class MyClass {
name = n; int x;
} // Constructor with a parameter
//method to display the values public MyClass(int x) {
void display (){System.out.println(rollno+" "+name+" this.x = x;
"+college);} }
} // Call the constructor
public static void main(String[] args) {
public class TestStaticVariable1{ MyClass myObj = new MyClass(5);
public static void main(String args[]){ System.out.println("Value of x = " + myObj.x);
Student s1 = new Student(111,"Karan"); }
Student s2 = new Student(222,"Aryan"); }
s1.display();
s2.display();
} Garbage Collection:
} • Garbage collection is a mechanism to remove objects
from memory when they are no longer needed.
• Garbage collection is carried out by the garbage
collector:
1) The garbage collector keeps track of how many
references an object has.
Access Modifiers: 2) It removes an object from memory when it has no
Public, Private, Protected: longer any references.
Public: keyword applied to a class, makes it 3) Thereafter, the memory occupied by the object can be
available/visible everywhere. Applied to a method allocated again.
or variable, completely visible. 4) The garbage collector invokes the finalize method.
• Default(No visibility modifier is specified): it finalize() method:
behaves like public in its package and private in • The finalize() method is invoked each time before the
other packages. object is garbage collected. This method can be used to
• Default Public keyword applied to a class, makes it perform cleanup processing. This method is defined in
available/visible everywhere. Applied to a method Object class as:
or variable, completely visible. • protected void finalize(){}
• Private : Private fields or methods for a class only gc() method:
visible within that class. Private members are not • The gc() method is used to invoke the garbage collector
visible within subclasses, and are not inherited. to perform cleanup processing. The gc() is found in
• Protected :Protected members of a class are visible System and Runtime classes.
within the class, subclasses and also within all • public static void gc(){}
classes that are in the same package as that class.
Keyword this: How can an object be unreferenced?
• Can be used by any object to refer to itself in any There are ways:
class method • By nulling the reference.
• Typically used to • By assigning a reference to another
• Avoid variable name collisions • By anonymous object etc.
• Pass the receiver as an argument 1) By nulling a reference:
• Chain constructors Employee e=new Employee();
• Keyword this allows a method to refer to the object e=null;
that invoked it. 2) By assigning a reference to another:
• It can be used inside any method to refer to the Employee e1=new Employee();
current object: Employee e2=new Employee();
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 7
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
e1=e2;//now the first object referred by e1 is available for public class MemoryDemo {
garbage collection public static void main(String[] args) throws
3) By anonymous object: InterruptedException {
new Employee(); Runtime r = Runtime.getRuntime();
Advantage of Garbage Collection long mem1, mem2;
• It makes java memory efficient because garbage String someints[] = new String[10000];
collector removes the unreferenced objects from System.out.println("Total memory is: " + r.totalMemory());
heap memory. mem1 = r.freeMemory();
• It is automatically done by the garbage collector(a System.out.println("Initial free memory: " + mem1);
part of JVM) so we don't need to make extra efforts. r.gc();
public class TestGarbage1{ mem1 = r.freeMemory();
public void finalize(){System.out.println("object is garbage System.out.println("Free memory after garbage collection: " +
collected");} mem1);
public static void main(String args[]){ for (int i = 0; i < 10000; i++)
TestGarbage1 s1=new TestGarbage1(); someints[i] = i+""; // allocate integers
TestGarbage1 s2=new TestGarbage1(); mem2 = r.freeMemory();
s1=null; System.out.println("Free memory after allocation: " + mem2);
s2=null; System.out.println("Memory used by allocation: " + (mem1 -
System.gc(); mem2));
} // discard Integers
} for (int i = 0; i < 10000; i++)
someints[i] = null;
r.gc(); // request garbage collection
Thread.sleep(100);
mem2 = r.freeMemory();
System.out.println("Free memory after collecting discarded String:
public class GJavaExample{
" + mem2);
public static void main(String args[]){
}
GJavaExample obj=new GJavaExample();
}
obj=null;
GJavaExample a = new GJavaExample();
GJavaExample b = new GJavaExample();
b = a;
System.gc();
}
protected void finalize() throws Throwable
{ Building Strings:
System.out.println("Garbage collection is performed by • String is probably the most commonly used class in Java's
JVM"); class library. The obvious reason for this is that strings
} are a very important part of programming.
} • The first thing to understand about strings is that every
string you create is actually an object of type String. Even
string constants are actually String objects.
• For example, in the statement:
System.out.println("This is a String, too");
• the string "This is a String, too" is a String constant
The String class is immutable, so that once it is created a String
object cannot be changed. If there is a necessity to make a lot of
modifications to Strings of characters, then you should use String
Buffer & String Builder Classes.
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 8
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Program:
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 9
Unit - 1
Object Oriented Programming Through Java (B.Tech II-I)
Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 10