0% found this document useful (0 votes)
91 views53 pages

OOPs With Java - Introduction To Java

This document provides an introduction and syllabus for an "OOPs with Java" course. The syllabus covers topics like introduction to Java, objects and classes, inheritance, interfaces, exception handling, and GUI programming. It also lists textbooks, evaluation criteria, and online resources. The course aims to teach object-oriented programming concepts in Java, including classes, objects, methods, encapsulation, inheritance, and polymorphism. It will cover both command-line and graphical user interface applications. Students will be evaluated based on quizzes, assignments, a midterm, final exam, and project.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
91 views53 pages

OOPs With Java - Introduction To Java

This document provides an introduction and syllabus for an "OOPs with Java" course. The syllabus covers topics like introduction to Java, objects and classes, inheritance, interfaces, exception handling, and GUI programming. It also lists textbooks, evaluation criteria, and online resources. The course aims to teach object-oriented programming concepts in Java, including classes, objects, methods, encapsulation, inheritance, and polymorphism. It will cover both command-line and graphical user interface applications. Students will be evaluated based on quizzes, assignments, a midterm, final exam, and project.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 53

OOPs with Java

Introduction to Java
Syllabus

● Introduction to Java, Program structure, Class Libraries, Using Java class libraries, data
types, control structures in Java, simple Java programs,
● Java applications and Applets, Drawing graphical shapes,
● Objects and Classes, Attributes, Methods, Visibility, Class Diagram Class Relationships,
Association, Aggregation, Composition
● Inheritance and Polymorphism, Base class, Derived class, Redefined methods, Abstract
methods and classes
● Java Interfaces
● Exception Handling, try, catch, and finally blocks, Types of Exceptions, Creating exception
classes I/O streams, Character streams, Byte Streams, File Streams, Reading and writing
to a file, Persistent objects, Object streams, Reading and writing objects to a file
● GUI Programming-1: Components, containers, events, listeners, dialog boxes, menu
items
● GUI Programming-2: Frames, Layouts, Swing components and Hierarchies
Evaluation Pattern:
Quizzes (10%), Lab Internals (30%), Mid term (20%),
End term (30%), Project (10%)
Text books:
1. Java 7 Programming - Black Book, By Kogent Learning Solutions Inc., Freamtech Publications
2. Head First Java 2nd Edition by Kathy Sierra, Oreilly Publication
3. T.Budd “Understanding OOP with Java” updated Edition, pearson education, ISBN:10:0201612739
4. Herbert schildt “Java the complete reference”, 7th Edition, TMH,ISBN:0072263857
REFERENCE BOOKS:
1. Y. Daniel Liang “Introduction to Java programming” 6th Edition, pearson education,ISBN:10:0132221586
2. R.A. Johnson-An introduction to Java programming and object oriented application development,
Thomson, ISBN:-10:0619217464
WEB LINKS:
1. www.tatamcgrawhill.com/html/9780070636774.html
2. http://nptel.iitm.ac.in
3. https://www.cl.cam.ac.uk/teaching/0910/OOProg/OOP.pdf
What is Java

● Java is a high Level programming language and it is also called as a platform.


● Java is a secured and robust high level object-oriented programming
language.
● Platform: Any software or hardware environment in which a program runs is
known as a platform. Java has its own runtime environment (JRE) and API so
java is also called as platform.
● Java fallows the concept of Write Once, Run Anywhere.
Application of java

1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc
History of Java
Features of Java:

● Object Oriented
● Platform Independent
● Simple
● Secure
● Architecture-neutral
● Portable.
● Robust
● Multithreaded
● Interpreted
● High Performance
● Distributed
● Dynamic
Object Oriented Programming System(OOPS)
Object means a real word entity such as pen, chair, table etc. Object- Oriented Programming is a
methodology or paradigm to design a program

using classes and objects. It simplifies the software development and maintenance by providing some
concepts:

● Object

● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
Procedure to write simple java Program

To write a java program First we install the JDK.

To create a simple java program, you need to create a class that contains
main method. Let's understand the requirement first.

Download Java from:

https://www.oracle.com/in/java/technologies/downloads/

● download the JDK and install it.


● set path of the jdk
● create the java program
● compile and run the java program
Setting Up the Path for Windows

● Assuming you have installed Java in c:\Program Files\java\jdk directory −


● Right-click on 'My Computer' and select 'Properties'.
● Click the 'Environment variables' button under the 'Advanced' tab.
● Now, alter the 'Path' variable so that it also contains the path to the
● Java executable. Example, if the path is currently set to
● 'C:\WINDOWS\SYSTEM32', then change your path to read
● 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Go to MyComputer properties -> advanced tab -> environment variables -> new
tab of user variable -> write path in variable name -> write path of bin folder in
variable value -> ok -> ok -> ok
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation, if you have trouble doing this.
For Example if you use bash as your shell, then you would add the following line
to the end of your '.bashrc:

export PATH = /path/to/java:$PATH'


Popular Java Editors

Notepad − On Windows machine, you can use any simple text editor like Notepad
(Recommended for this tutorial), TextPad.

Netbeans − A Java IDE that is open-source and free

Eclipse − A Java IDE developed by the eclipse open- source community


JDK, JVM and JRE

● JDK and JRE physically exists but JVM is abstract machine it means it does
not exists physically.
JAVA VIRTUAL MACHINE
JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed. JVMs are
available for many hardware and software platforms (i.e. JVM is platform
dependent).

It is:
1. A specification: where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation: Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance: Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
What it does:

The JVM performs following operation:


● Loads code
● Verifies code
● Executes code
Provides runtime environment
● JVM provides definitions for the:
● Memory area
● Class file format
● Register set
● Garbage-collected heap
● Fatal error reporting etc.
Running Java program

Steps for compile Java Program


● First Save Java program with same as class name with .java extension.
○ Example: Sum.java
● Compile: javac Filename.java
○ Example, javac Sum.java
● Note: Here javac is tools or application programs or exe files which is
used for Compile the Java program.
Steps for Run Java Program
● To run java program use java tool.
● Run by: java Filename
○ Example: java sum
CLASS, OBJECT AND METHODS
class classname
● Java program is a collection of objects that communicate via {
invoking each other's methods.
type instance-variable1; type
● Class − A class can be defined as a template/blueprint that instance-variable2;
describes the behavior/state that the object of its type
supports. // ... type instance-variableN;

type methodname1(parameter-list)
● A class is declared by use of the class keyword. A simplified
general form of a class definition is shown here: { // body of method }

● The data, or variables, defined within a class are called type methodname2(parameter-list)
instance variables.
{ // body of method }
● The code is contained within methods. Collectively, the
// ... type methodnameN(parameter-list)
methods and variables defined within a class are called
members of the class. In most classes, the instance variables { // body of method }
are acted upon and accessed by the methods defined for that
}
class
Simple Class

Class Sample
{
int len, float ht
void get()
{ // body

}}
Here a class Sample contains two variable len and ht
Object in Java

● Object is the physical as well as logical entity whereas class is the logical entity only.

● An object has three characteristics:

○ state: represents data (value) of an object.

○ behavior: represents the behavior (functionality) of an object such as deposit,


withdraw etc.

○ identity: Object identity is typically implemented via a unique ID. The

● value of the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.
Object is an instance of a class. Class is a template or blueprint from
which objects are created. So object is the instance(result) of a class.
Object Definitions:
Object is a real world entity.
Object is a run time entity.
Object is an entity which has state and behavior.
Object is an instance of a class.
Sample s=new Sample() here s is an object for the class Sample
new operator is used to create an object
Methods
A method is basically a behavior. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.

1. class Sample{

2. public static void main(String args[]){

3. System.out.println("How are you ");

4. }

5. }

save this file as Sample.java

To compile: javac Sample.java

To execute: java Sample


Java Identifiers

● All Java components require names. Names used for classes, variables, and
methods are called identifiers.

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

○ Examples of illegal identifiers: 123abc, -salary.


Java Modifiers:

There are two categories of modifiers −

Access Modifiers − default, public , protected, private

Non-access Modifiers − final, abstract, strictfp


DATA TYPES

There are two data types available in Java −

Primitive Data Types

Non Primitive Types


Primitive Data Types
Data Meaning Size Range Example
Type (in Bytes)
byte 2’s complement integer 1 -128 to 127 byte a = 100, byte b = -50

short 2’s complement integer 2 -32K to 32K short s = 10000, short r =


-20000
int 2’s complement Integer 4 -2B to 2B int a = 100000, int b =
numbers -200000
long 2’s complement integer 8 -9,223,372,036,854,775,808 long a = 100000L, long b =
to 9,223,372,036,854,775,807 -200000L
(larger values)
float Floating-point 4 Upto 7 decimal digits float f1 = 234.5f
double Double Floating-point 8 Upto 16 decimal digits double d1 = 123.4

char Character 2 a, b, c .. char letterA = 'A'


A, B, C ..
@, #, $ ..
bool Boolean 1 True, false boolean one = true
Non Primitive Data Types

These are of variable size & are usually declared with a ‘new’ keyword.
Eg. Array, String

String name = new String("ABC");


int[] marks = new int[3];
marks[0] = 97;
marks[1] = 98;
marks[2] = 95;
Java Structure

public class Main {

public static void main(String[] args) {


// Variables
int num = 30;

System.out.println(“number ”+ num);
System.out.println(num +”is the number”);
}
}
User Input

Different classes:

● Scanner class: java.util.Scanner;


● BufferdReader: Java.io.BufferedReader
Input:- Scanner Class

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
Practice Problems

1. With respect to each data type, declare meaningful variables.


Eg - age should be defined only with integer not byte.
2. Make a program that takes the length and breadth of a
rectangle as user input, and calculates its area and prints it as
output to the user.
3. Make a program that prints the table of a number that is input
by the user.
Variable
● 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 an instance variable. It
is not declared as static.
○ It is called an instance variable because its value is instance-specific and is not shared among instances.
○ It cannot be declared static, abstract, striftp, synchronized, and native.
○ It can be declared final and transient.
○ It can be of any of the four access modifiers available in Java (private, public, protected, and default).

● Static variable:
○ A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Example
1. public class A
2. {
3. static int m=100;//static variable
4. public int data1=50;//instance variable
5. void method()
6. {
7. int n=90;//local variable
8. }
9. public static void main(String args[])
10. {
11. int data=50;//instance variable
12. }
13. }//end of class
Java Tokens

Java Tokens are the smallest individual building block or smallest unit of a Java
program, it is used by the Java compiler for constructing expressions and
statements. Java program is collection different types of tokens, comments, and
white spaces.
○ Keywords
○ Identifiers
○ Literals
○ Operators
○ Separators
○ Comments
Java Literals

A literal is a source code representation of a fixed value. Literals can be assigned


to any primitive type variable.

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"xyzabc" String

null any reference type


Keywords
pre-defined reserved words of any programming language
Java Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>


Separators

also known as punctuators. There are nine separators in Java, are as follows:

separator <= ; | , | . | ( | ) | { | } | [ | ]

○ Square Brackets []: It is used to define array elements. A pair of square brackets represents the
single-dimensional array, two pairs of square brackets represent the two-dimensional array.
○ Parentheses (): It is used to call the functions and parsing the parameters.
○ Curly Braces {}: The curly braces denote the starting and ending of a code block.
○ Comma (,): It is used to separate two values, statements, and parameters.
○ Assignment Operator (=): It is used to assign a variable and constant.
○ Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two statements.
○ Period (.): It separates the package name form the sub-packages and class. It also separates a variable or
method from a reference variable.
Comments
specify information about the program inside our Java code. Java compiler recognizes these comments as tokens but
excludes it from further processing. The Java compiler treats comments as whitespaces. Java provides the following two
types of comments:

○ Single Line: It begins with a pair of forwarding slashes (//).


○ Multi line: It begins with /* and continues until it founds */.
○ Documentation:
○ Documentation comments are usually used to write large programs for a project or software application as it
helps to create documentation API.
○ These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used in the code.
○ To create documentation API, we need to use the javadoc tool. The documentation comments are placed
between /** and */.
Control Statement

1. Decision Making statements


○ if statements
○ switch statement
2. Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
3. Jump statements
○ break statement
○ continue statement
If Statement
1. Simple if statement

2. if-else statement

3. if-else-if ladder

4. Nested if-statement
If Statement
1.
2.

3. if-else-if ladder

4. Nested if-statement
Switch Statement
Loop Statements

1. for loop
2. while loop
3. do-while loop
for loop

Syntax:
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }

Example:
1. for(int j = 1; j<=10; j++) {
2. sum = sum + j;
3. }
for-each loop
traverse the data structures like array or collection. In the for-each loop, we don't need to
update the loop variable

Syntax:
1. for(data_type var : array_name/collection_name){
2. //statements
3. }

Example:
1. String[] names = {"Java","C","C++","Python","JavaScript"};
2. System.out.println("Printing the content of the array names:\n");
3. for(String name:names) {
4. System.out.println(name);
5. }
While loop

Syntax:
1. while(condition){
2. //looping statements
3. }

Example:
1. while(i<=10) {
2. System.out.println(i);
3. i = i + 2;
4. }
do-while loop
Syntax: 1. do
2. {
3. //statements
4. } while (condition);

Example: 1. do {
2. System.out.println(i);
3. i = i + 2;
4. }while(i<=10);
Jump Statements
break statement: break the current flow of the program and transfer the control to the next statement outside a loop
or switch statement. However, it breaks only the inner loop in the case of the nested loop.

Example:

continue statement: it skips the specific part of the loop and jumps to the next iteration of the loop immediately.

Example:

You might also like