Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

OOP Through Java Programming Unit-1

intro to oops
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

OOP Through Java Programming Unit-1

intro to oops
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

OOP Through

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

 Basic knowledge of Logical Thinking

 Basics of procedural oriented programming.

 Basics of Object Oriented Programming.


Course Objectives

 This 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.
Course Outcomes
On completion of the course, the students will be able to

 Learn the structure of Java Program and its applications

 Develop a software/application using Java Programming language

 Synthesize the give problem and implement it in Java

 Choose an engineering approach to solve problems using Java


Part-1 Course Contents
 History of JAVA

 Java Virtual Machine

 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

Java source code

Java compilers compile


source code into bytecode.

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

 Slower than compiled language such as C


– an experiment in 1999 showed that Java was 3 or 4 times slower than
C or C++
title of the article: “Comparing Java vs. C/C++ Efficiency Issues to
Interpersonal Issues” (Lutz Prechelt)
– adequate for all but the most time-intensive programs

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

There is a provision in Java that allows you to declare your classes in a


collection called package. There can be only one package statement in a
Java program and it has to be at the beginning of the code before
any class or interface declaration. This statement is optional, for example,
take a look at the statement below.

 Example: package student;


Import Statement
 Import Statement
Many predefined classes are stored in packages in Java, an import
statement is used to refer to the classes stored in other packages. An import
statement is always written after the package statement but it has to be
before any class declaration.
 We can import a specific class or classes in an import statement. Take a
look at the example to understand how import statement works in Java.
 Examples:
import java.util.Date; //imports the date class
import java.applet.*; //imports all the classes from the java applet
Interface Section
 Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritance in Java. An interface is a lot similar
to a class in Java but it contains only constants and method declarations.
 An interface cannot be instantiated but it can be implemented by classes or
extended by other interfaces.
 Example:
interface stack{
void push(int item);

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{

int data=50;//instance variable

static int m=100;//static variable

void method(){

int n=90;//local variable

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

Long 8 bytes -9223372036854775808 to 9223372036854775807

Data Type Memory size Range

Float 4 bytes -34e38 to 34e38


Double 8 bytes -17e308 to 17e308

Data Type Memory size Range


Char 2 bytes 0 to 65535
Java Identifiers
 In programming languages, identifiers are used for identification purposes. In Java, an identifier can
be a class name, method name, variable name, or label. For example :
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.
Cont...
Rules for defining Java Identifiers
 There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we get
compile-time error. These rules are also valid for other languages like C,C++.
 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar
sign) and ‘_‘ (underscore).For example “geek@” is not a valid java identifier as it contain ‘@’ special
character.
 Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters
only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as
while is a reserved word. There are 53 reserved words in Java.
Java keywords
Java Keywords List

abstract assert boolean break byte

case catch char class const

continue default do double else

enum extends final finally float

for goto if implements import

instanceof int interface long native

new package private protected public

return short static strictfp super

switch synchronized this throw throws

transient try void volatile while


Java literals
 Literals are data used for representing fixed values. They can be used directly in the code.
 For example, int a = 1; float b = 2.5; char c = 'F';Here, 1, 2.5, and 'F' are literals.
 Here are different types of literals in Java.
 Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store two values: true and
false.
 Integer Literals
An integer literal is a numeric value(associated with numbers) without any fractional or exponential part.
 Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponential form.
 Character Literals
Character literals are unicode character enclosed inside single quotes.
 String literals
A string literal is a sequence of characters enclosed inside double-quotes.
Type Casting/Type conversion
 Type Casting/type conversion
Converting one primitive datatype into another is known as type casting (type conversion) in
Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing.
 Widening − Converting a lower datatype to a higher datatype is known as widening. In this
case the casting/conversion is done automatically therefore, it is known as implicit type
casting. In this case both datatypes should be compatible with each other.

 Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this


case the casting/conversion is not done automatically, you need to convert explicitly using the
cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both
datatypes need not be compatible with each other.
Flow of control

 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.

 Decision-making statements : if-then, if-then-else, switch

 Looping statements : for, while, do-while

 Branching statements : break, continue, return


Cont...
 The if-then Statement

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 object is a runtime entity.

 The object is an entity which has state and behavior.

 The object is an instance of a class.


Syntax:

Class_name variable_name; // declare reference to object

variable_name = new Class_name ( ); // allocate an object


Methods
 A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions.
 Why use methods? To reuse code: define the code once, and use it many times.
 Call a Method To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
 Syntax
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
Constructor
 In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory. It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
 There are two types of constructors in Java:
 no-arg constructor
 parameterized constructor.
 There are rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
Cont...
Default Constructor
 A constructor is called "Default Constructor" when it doesn't have any parameter.
 Syntax of default constructor:
<class_name>(){}
 The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type
Parameterized Constructor
 A constructor which has a specific number of parameters is called a parameterized constructor.
 Why use the parameterized constructor? The parameterized constructor is used to provide different
values to distinct objects. However, you can provide the same values also.
 Syntax of parameterized constructor:
<class_name>(returnType argument list){}
Constructor overloading
 Constructor Overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
 Copy constructor
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++. There are many ways to copy the values of one object
into another in Java. They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
Garbage collector
 Automatic garbage collection is the process of looking at heap memory, identifying which
objects are in use and which are not, and deleting the unused objects.

 An in use object, or a referenced object, means that some part of your program still maintains
a pointer to that object.

 An unused object, or unreferenced object, is no longer referenced by any part of your


program. So the memory used by an unreferenced object can be reclaimed.

 In a programming language like C, allocating and deallocating memory is a manual process.


In Java, process of deallocating memory is handled automatically by the garbage collector.
Cont...
 Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
 The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing
 The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Static keyword
 The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.

 The static can be:


 Variable (also known as a class variable)

 Method (also known as a class method)


Cont...
1) Java static variable
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable


 It makes your program memory efficient (i.e., it saves memory).
Syntax:
static variable name;
Cont...
2) Java static method
 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.
Restrictions for the static method
There are two main restrictions for the static method. They are:
 The static method can not use non static data member or call non-static method directly.
 this and super cannot be used in static context.
This keyword
 There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
 The 6 usage of java this keyword.
 this can be used to refer current class instance variable.

 this can be used to invoke current class method (implicitly)

 this() can be used to invoke current class constructor.

 this can be passed as an argument in the method call.

 this can be passed as argument in the constructor call.

 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.

You might also like