OOP Through Java Programming Unit-1
OOP Through Java Programming Unit-1
Java Programming
Presented By:
Mr.V.Ajay Kumar
Assistant Professor
Dept. Of CSE
Lecture Details:
GIET-(A), Rajahmundry
Unit-1 Topic Name: Java Basics
OOP Through Java Programming/CSE, II B.Tech I Sem
Outline
Scope of the Course
Course Pre-requisites
Course Objectives
Course Outcomes
Course Contents
Java Basics
Scope of the Course
OOP Through Java Programming course is intended to teach the object oriented
programming to develop solutions to problems demonstrating usage of control
structures, modularity, I/O. and other standard language constructs.
This course included applying object oriented techniques to solve bigger computing
problems.
Text Books:
MainReference:
The Complete Reference Java, 8ed, Herbert Schildt, TMH
SupplementaryReferences:
Programming in Java E.BalaguruSamy.
Course Pre-Requisites
Java Features
Program structures
Variables
History of JAVA
The history of Java starts from Green Team. Java team members (also known as Green Team),
initiated a revolutionary task to develop a language for digital devices such as set-top boxes,
televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991
• Initially Java is developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
• In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Cont...
Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Java is an island of Indonesia where first coffee was produced (called java coffee).
In 1995, Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 released in (January 23, 1996).
Java Virtual Machine
The Compilation Process for Java Programs
bytecode
When a Java program is run,
the JVM translates bytecode
to object code.
object code
Java Features
Java is simple
Java is object-oriented
Java is distributed
Java is interpreted
Java is robust
Java is secure
Java is architecture-neutral
Java is portable
Java’s performance
Java is multithreaded
Java is dynamic
Java Features
Simple
– fixes some clumsy features of C++
– no pointers
– automatic garbage collection
– rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
Object oriented
– focus on the data (objects) and methods manipulating the data
– all functions are associated with objects
– almost all datatypes are objects (files, strings, etc.)
– potentially better code organization and reuse
Dept of CSE 13
Java Features
Interpreted
– java compiler generate byte-codes, not native machine code
– the compiled byte-codes are platform-independent
– java bytecodes are translated on the fly to machine readable instructions in
runtime (Java Virtual Machine)
Portable
– same application runs on all platforms
– the sizes of the primitive data types are always the same
– the libraries define portable interfaces
Dept of CSE 14
Java Features
Reliable
– extensive compile-time and runtime error checking
– no pointers but real arrays.
– Memory corruptions or unauthorized memory accesses are impossible
– automatic garbage collection tracks objects usage over time
Secure
– usage in networked environments requires more security
– memory allocation model is a major defense
– access restrictions are forced (private, public)
Dept of CSE 15
Java Features
Robust (Strong/ Powerful)
Java programs will not crash because of its exception handling and its memory management
features
Architectural Neutral Language:
Java byte code is not machine dependent, it can run on any machine with any processor and
with any OS
High Performance
Along with interpreter there will be JIT (Just In Time) compiler which enhances the speed of
execution
Distributed:
Java is designed for use on network; it has an extensive library which works in agreement with
TCP/IP
Dept of CSE 16
Java Features
Multithreaded
– multiple concurrent threads of executions can run simultaneously
– utilizes a sophisticated set of synchronization primitives (based on monitors and
condition variables paradigm) to achieve this
Dynamic
– java is designed to adapt to evolving environment
– libraries can freely add new methods and instance variables without any effect on their
clients
– interfaces promote flexibility and reusability in code by specifying a set of methods an
object can perform, but leaves open how these methods should be implemented
– can check the class type in runtime
Dept of CSE 17
Java Disadvantages
Dept of CSE 18
JDK Editions
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone applications or
applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such as Java
servlets and Java ServerPages.
• Java Micro Edition (J2ME)
– J2ME can be used to develop applications for mobile devices such as
cell phones.
Dept of CSE 19
Java IDE Tools
Forte by Sun MicroSystems
Borland JBuilder
Microsoft Visual J++
WebGain Café
IBM Visual Age for Java
Dept of CSE 20
Program structures
Comments
Comments : Comments are description about the aim and features of the program
Comments increase readability of a program Three types of comments are there in
Java
Single line comments: These comments start with //
eg: // this is comment line
Multi line comments: These comments start with /* and end with */
eg: /* this is comment line*/
Java documentation comments: These comments start with /** and end with */
These comments are useful to create a HTML file called API (application
programming Interface) document This file contains description of all the features
of software
Package Statement
Package Statement
void pop();
}
Class Definition
Class Definition
A Java program may contain several class definitions, classes are an essential part
of any Java program. It defines the information about the user-defined classes in a
program.
A class is a collection of variables and methods that operate on the fields. Every
program in Java will have at least one class with the main method.
Public class
This creates a class called “Example” class name. You should make sure that the
class name starts with a capital letter, and the public word means it is accessible
from any other classes.
Only one public class is allowed inside the java program and file is saved with that
public class name
public static void main
public static void main
When the main method is declared public, it means that it can be used outside of this class as
well.
The word static means that we want to access a method without making its objects. As we
call the main method without creating any objects.
The word void indicates that it does not return any value. The main is declared as void
because it does not return any value.
Main is the method, which is an essential part of any Java program.
String[] args
It is an array where each element is a string, which is named as args. If you run the Java code
through a console, you can pass the input parameter. The main() takes it as an input
Java Variables
Variables are containers for storing data values.
Syntax:
type variable = value;
Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable
Cont...
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 instance variable. It
is not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) 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. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Cont...
Example to understand the types of variables in java
class A{
void method(){
}//end of class
Primitive Data types
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes
Cont...
Data Type Memory size Range
Byte 1 byte -128 to 127
Short 2 bytes -32768 to 32767
Int 4 bytes -2147483648 to 2147483647
Control flow statements, change or break the flow of execution by implementing decision
making, looping, and branching your program to execute particular blocks of code based on
the conditions.
There are 3 types of control flow statements supported by the Java programming language.
The if-then statement is the most basic of all the control flow statements. It enables your
program to execute a certain section of code depending on the state of variables, or values
returned from methods.
if(isCar)
System.out.println("I am a Car");
}
Cont...
The if-then-else Statement
The if-then-else statement provides a alternate path of execution when an "if" clause evaluates
to false.
if(isCar)
{
System.out.println("I am a Car");
}
else
{
System.out.println("I am a Truck");
}
Cont...
Switch statement
Another way to control the flow of your programs with decision-making statements is by a switch
statement. A switch statement gives you the option to test for a range of values for your variables. If you
think your if-else-if statements is long and complex, you can use switch statement instead.
Sytax:
switch <variable> {
Case <option 1>:
//block of statements
..
..
Case <option n>:
//block of statements
Default:
//block of statements
}
Cont...
for loop
In java, for loop is similar to C and C ++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. The syntax to use the for loop is given
below.
for(<initialization>, <condition>, <increment/decrement>)
{
//block of statements
}
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
for(type var : Array/collection)
{
//statements
}
Part-2 Course Contents
Java Class
Java Object
Methods
Constructors, constructor overloading
Garbage collector
Static, this keyword
Arrays
Command line arguments
Java class
Class: In object-oriented programming, a class is a programming language
construct that is used as a blueprint to create objects This blueprint includes
attributes and methods that the created objects all share Usually. Class is a
collection of objects. It is a logical entity/ structure or design.
Syntax:
class class_name
{
Properties (variables);
Actions (methods);
}
Object
Object: An object is a real-world entity.
An in use object, or a referenced object, means that some part of your program still maintains
a pointer to that object.
this can be used to return the current class instance from the method.
Cont...
this can be used to refer current class instance variable.
class Student
{
int pin;
Student(int pin)
{
this.pin=pin;
}
void display()
{
System.out.println("pin is "+pin);
}
}
public class Program OUTPUT:
{ pin is 123
public static void main(String[] args) {
Student s=new Student(123);
s.display();
}
}
Arrays
Arrays: An array represents a group of elements of same data type Arrays are generally
categorized into two types:
Single Dimensional arrays (or 1 Dimensional arrays)
Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)
Single Dimensional Arrays: A one dimensional array or single dimensional array represents
a row or a column of elements For example, the marks obtained by a student in 5 different
subjects can be represented by a 1D array
We can declare a one dimensional array and directly store elements at the time of its
declaration, as: int marks[] = {50, 60, 55, 67, 70};
Example:int marks[]; //declare
marks array marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as: int marks [] = new int [5];
Cont..
Multi-Dimensional Arrays (2D, 3D … arrays): Multi dimensional arrays represent 2D, 3D
… arrays A two dimensional array is a combination of two or more (1D) one dimensional
arrays A three dimensional array is a combination of two or more (2D) two dimensional arrays
Two Dimensional Arrays (2d array): A two dimensional array represents several rows and
columns of data To represent a two dimensional array, we should use two pairs of square
braces [ ] [ ] after the array name For example, the marks obtained by a group of students in
five different subjects can be represented by a 2D array
We can declare a two dimensional array and directly store elements at the time of its
declaration, as:
int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
int marks [ ][ ] = new int[3][5]; //allot memory for storing 15 elements
Cont..
//Displaying a 2D array as a matrix
class Matrix {
public static void main(String args[]) {
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} }; //take a 2D array
for (int i = 0 ; i < 2 ; i++) { // display the array elements
Systemoutprintln ();
for (int j = 0 ; j < 3 ; j++)
Systemoutprint(x[i][j] + “\t”);
}
}
}
OUTPUT: 1 2 3
456
Command line arguments.
The java command-line argument is an argument i.e. passed at the time of running the java
program.The arguments passed from the console can be received in the java program and it
can be used as an input.So, it provides a convenient way to check the behavior of the program
for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Example:
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Questions
Describe how to use break and continue statements in java?
Define Array in java?Explain how to declare an array of having size 20 in java?
Explain in detail the most significant features of JAVA programming.
Define a Constructor? Explain the main purpose of Constructors? How to invoke a
constructor in JAVA?
Give two control structures used in java for making decisions? Explain with an
example program.
Discuss how to perform type casting in java? Differentiate it from primitive type
conversion with an example program.