0% found this document useful (0 votes)
62 views10 pages

Unit - 1 Object Oriented Programming Through Java (B.Tech II-I)

The document discusses Java programming concepts including its history, data types, variables, keywords, arrays, input/output, and object-oriented features. It provides definitions of key Java terms like simple, secure, portable, object-oriented, robust, architecture-neutral, multi-threaded, interpreted, high performance, and distributed. Examples are given for declaring variables of different data types like int, double, float, and char. String handling in Java is also briefly covered.

Uploaded by

Raju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views10 pages

Unit - 1 Object Oriented Programming Through Java (B.Tech II-I)

The document discusses Java programming concepts including its history, data types, variables, keywords, arrays, input/output, and object-oriented features. It provides definitions of key Java terms like simple, secure, portable, object-oriented, robust, architecture-neutral, multi-threaded, interpreted, high performance, and distributed. Examples are given for declaring variables of different data types like int, double, float, and char. String handling in Java is also briefly covered.

Uploaded by

Raju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit - 1

Object Oriented Programming Through Java (B.Tech II-I)


UNI T-1: Introduction to java: Java programming – History Java Buzz Words:
of Java, comments, data types, variables, constants, scope Java is the most popular object-oriented programming language.
and life time of variables, keywords of java, arrays, console Java has many advanced features, a list of key features is known as
input and output, formatting output, constructors, methods, Java Buzz Words. The java team has listed the following terms as
parameter passing, static fields and methods, access control, java buzz words.
this reference, garbage collection, building strings, exploring  Simple
string class.  Secure
Introduction to java:  Portable
Java is a programming language created by James Gosling  Object-oriented
from Sun Microsystems (Sun) in 1991. The target of Java is  Robust
to write a program once and then run this program on  Architecture-neutral (or) Platform Independent
multiple operating systems. The first publicly available  Multi-threaded
version of Java (Java 1.0) was released in 1995.  Interpreted
History of Java:  High performance
Java was started as a project called "Oak" by James Gosling
 Distributed
in June 1991. Gosling's goals were to implement a virtual
 Dynamic
machine and a language that had a familiar C-like notation
Simple
but with greater uniformity and simplicity than C/C++.
Java programming language is very simple and easy to learn,
JDK Versions:
understand, and code. Most of the syntaxes in java follow basic
• JDK 1.02 (1995)
programming language C and object-oriented programming
• JDK 1.1 (1996)
concepts are similar to C++. In a java programming language,
• Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
many complicated features like pointers, operator overloading,
• Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
structures, unions, etc. have been removed. One of the most useful
• Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002) features is the garbage collector it makes java more simple.
• J2SE 5.0 (September 30, 2004) Secure
• Java SE 6 (December 11, 2006)
Java is said to be more secure programming language because it
• Java SE 7 (July 28, 2011)
does not have pointers concept, java provides a feature "applet"
• Java SE 8 (March 18, 2014) which can be embedded into a web application. The applet in java
• Java SE 9 (September 21, 2017)
does not allow access to other parts of the computer, which keeps
• Java SE 10 (March, 20, 2018)
away from harmful programs like viruses and unauthorized access.
• Upcoming Java Version : Java SE 11 Portable
JDK Editions:
Portability is one of the core features of java which enables the
 Java Standard Edition (J2SE)
java programs to run on any computer or operating system. For
 J2SE can be used to develop client-side standalone example, an applet developed using java runs on a wide variety of
applications or applets. CPUs, operating systems, and browsers connected to the Internet.
 Java Enterprise Edition (J2EE) Object-oriented
 J2EE can be used to develop server-side Java is said to be a pure object-oriented programming language. In
applications such as Java servlets and Java java, everything is an object. It supports all the features of the
ServerPages. object-oriented programming paradigm. The primitive data types
 Java Micro Edition (J2ME). java also implemented as objects using wrapper classes, but still, it
 J2ME can be used to develop applications for allows primitive data types to archive high-performance.
mobile devices such as cell phones. Robust
Java IDE Tools: Java is more robust because the java code can be executed on a
• Forte by Sun Microsystems variety of environments, java has a strong memory management
• Borland JBuilder mechanism (garbage collector), java is a strictly typed language, it
• Microsoft Visual J++ has a strong set of exception handling mechanism, and many more.
• WebGain Café Architecture-neutral (or) Platform Independent
• IBM Visual Age for Java Java has invented to archive "write once; run anywhere, any time,
• Netbeans forever". The java provides JVM (Java Virtual Machine) to to
• Eclipse archive architectural-neutral or platform-independent. The JVM
• Intellij Idea allows the java program created using one operating system can be
• Bluej executed on any other operating system.
• Jcreator

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.

byte (number, 1 byte) You can also concat string to primitives:


short (number, 2 bytes) int num = 5;
int (number, 4 bytes) String s = "I have " + num + " cookies"; //Be sure not to use ""
long (number, 8 bytes) with primitives.
float (float number, 4 bytes)
double (float number, 8 bytes) Boolean
char (a character, 2 bytes) Every comparison operator in java will return the type boolean.
boolean (true or false, 1 byte) Unlike other languages, it only accepts two special values: true or
Java is a strong typed language, which means variables need false.
to be defined before we use them.
boolean b = false;
b = true;

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 }
};

// Nested loops to print the array in tabular form.


for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 3; col++)
{
System.out.print(values[row][col] + " ");
}

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(); }
} }
}

Static Block: Advantages of static variable:


class JavaExample{
• It makes your program memory efficient (i.e., it saves
static int num; memory).
static String mystr;
• Suppose there are 500 students in my college, now all
static{
instance data members will get memory each time when
num = 97; the object is created. All students have its unique rollno
mystr = "Static keyword in Java"; and name, so instance data member is good in such case.
}
Here, "college" refers to the common property of all
public static void main(String args[])
objects. If we make it static, this field will get the
{
memory only once.
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}

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:

public class StringDemo {


public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString ); Example:
}
}

• Java defines one operator for String objects: +.


• It is used to concatenate two strings. For example,
this statement
• String myString = "I" + " like " + "Java.";
• results in myString containing "I like Java.“ public class StringOperations{
char[] ch={'j','a','v',’a'}; public static void main(String args[]){
String s=new String(ch); int value=20;
is same as: String s1="hello";
String s="java"; String s2="hello";
Constructing Strings; String s3="hemlo";
• Strings are objects of class String. String s4="flag";
Example: String s5="spaces ";
// all 3 statements create new String objects String s6="HELLO HOW Are You?";
• String s1 = "hello"; System.out.println(s1.compareTo(s2));
• String s2 = new String("hello"); System.out.println(s1.compareTo(s3));
• String s3 = new String(s2); System.out.println(s1.compareTo(s4));
Methods of Java String s1=s1.concat("how are you");
System.out.println(s1);
System.out.println(s1.isEmpty());
System.out.println(s5.trim()+"blankspaces are removed");
String s6lower=s6.toLowerCase();
System.out.println(s6lower);
String s6upper=s6.toUpperCase();
System.out.println(s6upper);
String s7=String.valueOf(value);
System.out.println(s7+20);
String replaceString=s1.replace('h','t');
System.out.println(replaceString);
String s="Welcome to java";
char[] ch=s.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.print(ch[i]);
}
String s8="ABC";
byte[] b=s8.getBytes();
for(int i=0;i<b.length;i++){
System.out.println("\n"+b[i]);
}
}
}

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

You might also like