0% found this document useful (0 votes)
25 views

JAVA Introduction

The document discusses Object Oriented Programming in Java. It introduces key OOP concepts like abstraction, encapsulation, inheritance and polymorphism. It also covers Java features like being platform independent, secure, robust and object-oriented. The document provides an overview of how to write, compile and execute a basic Java program. It describes primitive data types in Java like boolean, char, byte and others.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

JAVA Introduction

The document discusses Object Oriented Programming in Java. It introduces key OOP concepts like abstraction, encapsulation, inheritance and polymorphism. It also covers Java features like being platform independent, secure, robust and object-oriented. The document provides an overview of how to write, compile and execute a basic Java program. It describes primitive data types in Java like boolean, char, byte and others.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Object Oriented Programming (Java Programming Language )

James Gosling
What you will be able to do after Learning Java
Programming??

• Develop programs by applying Object-Oriented Programming (OOP)


concepts of JAVA to solve real-world problems.
• Achieve Robustness and Concurrency while developing programs.
• Design Graphical User Interface(GUI) using swing.
Module: 1

Introduction to Java as Object Oriented


Programming Language
 Fundamentals of Java Programming:
 Overview of procedure and object-oriented programming,
 Features of Java,
 Java Virtual Machine
 Principles of OOP: Object, Class, Encapsulation, Abstraction, Inheritance, Polymorphism
 Basic Constructs: Constants, variables and data types, Wrapper classes, Operators and Expressions
 Input & Output in Java: command line arguments, BufferedReader class and Scanner class
Fundamentals of Java Programming:
• Overview of procedure and object-oriented programming:
Fundamentals of Java Programming:
• Overview of procedure and object-oriented programming:
Fundamentals of Java Programming:
• C Programming Vs Java Programming
Fundamentals of Java Programming:
• C Programming Vs Java Programming
Features of Java
Java is Object Oriented

Java Object:
Java object is any real time entity in the world associated with
some states/properties and different behaviours/ Methods where
states are represented using data types(static/instance variables)
and behaviours are represented using methods/functions.
Modification in the states achieve the correct behaviours of any
object.
4 main OOPS of java:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Java does support Abstraction & Encapsulation
Java does support Polymorphism

Polymorphism: One Form(Method) with many possibly different behaviours


Java is Multithreaded
Enables a program to perform several tasks simultaneously.
Java is Secure language
• JVM • No Concept of Pointers
JVM plays a vital role to provide security. It verifies the Java does not provide support for pointers concept. It is the
byte-code. The JVM provides guarantees that there is no main security features of Java. The use of pointers may lead
unsafe operation going to execute. It also helps to to unauthorized read or write operations. Therefore, the user
diminish the possibilities of the programmers who suffer cannot point to any memory locations.
from memory safety flaws.
• Security API's • Memory management
Java class libraries provide several API that leads to Java automatically manages memory which is known as
security. These APIs contain cryptographic algorithms garbage collection. The JVM manages memory itself. The
and authentication protocols that lead to secure programmers are free from memory management. Hence,
communication. there is no chance to fault in memory management.
• Byte Code
Every time when a user compiles the Java program, the • Compile-time checking
Java compiler creates a class file with Bytecode, which
are tested by the JVM at the time of program execution
for viruses and other malicious files. • Compile-time checking also makes the Java secure.
• Security Manager Consider a scenario in which an unauthorized method is
trying to access the private variable, in this case, the JVM
The security manager is responsible for checking the gives the compile-time error. It prevents the system from
permissions and properties of the classes. It monitors the crash.
the system resources accessed by the authorized classes.
It also controls socket connections.
Java Virtual Machine Interpreter
The interpreter reads and executes the bytecode
instructions line by line. Due to the line by line
execution, the interpreter is comparatively slower.
JIT Compiler
The JIT Compiler overcomes the disadvantage of the
interpreter. The Execution Engine first uses the interpreter to
execute the byte code, but when it finds some repeated code,
it uses the JIT compiler.
The JIT compiler then compiles the entire bytecode and
changes it to native machine code. This native machine code
is used directly for repeated method calls, which improves
the performance of the system.
Garbage Collector
The Garbage Collector (GC) collects and removes
unreferenced objects from the heap area. It is the process of
reclaiming the runtime unused memory automatically by
destroying them.
Garbage collection makes Java memory efficient because it
removes the unreferenced objects from heap memory and
makes free space for new objects. It involves two phases:
Mark – in this step, the GC identifies the unused objects in
memory
Sweep – in this step, the GC removes the objects identified
during the previous phase
Object Oriented Programming
• Abstraction
Denotes the extraction of essential characteristics of an object that distinguish
from all other kinds of objects.
• Encapsulation
Hiding the implementation details of a class.
Forces the user to use an interface to access the data.
• Inheritance
Process by which one class acquires the properties and functionalities of the
other.
• Polymorphism
Means the ability of methods to exist in several different forms
Java is a Robust Language
• Two main hurdles which cause program failures i.e memory
management mistakes and mishandled runtime errors can be
overcome.

• Memory management mistakes can be overcome by garbage collection.


Garbage collection is automatic de-allocation of objects which are no longer
needed.

• Mishandled runtime errors are resolved by Exception Handling procedures.


How to WriteCompile Execute Java Code/Program

• Download & install jdk from below link


https://www.oracle.com/java/technologies/downloads/#jdk20-windows

javac - The Java Compiler


java - The Java Interpreter
How to WriteCompile Execute Java Code/Program

1. Create folder on any drive on the PC


2. In the folder create notepad file and write java code in it and save
the file with Classname.java

import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello This is my First Java Code");
}

}
How to WriteCompile Execute Java Code/Program

• Step1: Save the source file as HelloWorld.java

• Step2: Open command prompt and navigate to the directory where you have stored the file.

• Step 3: To compile, type javac HelloWorld.java and press Enter.

• Step 4: On successful compilation, you will see the command prompt and HelloWorld.class file in
the same folder where HelloWorld.java is stored. This is the byte code of the program.

• Step 5: To execute, type java HelloWorld Do not type the extension while executing.

• Step 6: See the output Hello This is my First Java Code displayed on the console.
How to WriteCompile Execute Java Code/Program
1. Create folder on any drive on the PC
2. In the folder create notepad file and write java code in it and save
the file with Classname.java
3. Compile java program using command: javac HelloWorld.java
4. Execute java program using command: java HelloWorld
Setting Path one time to run java program on any drive
any folder:
Basic Constructs:

• Constants
• variables and data types
• Wrapper classes
• Operators and Expressions
Java Constants
Data Types

There are two data types available in Java:

• Primitive Data Types

• Reference/Object Data Types


Primitive Data Types:
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key
word. Let us now look into detail about the eight primitive data types.
• boolean: boolean data type represents one bit of information.
• There are only two possible values : true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example : boolean one = true
• char: char data type is a single 16-bit Unicode character.
• Minimum value is '\u0000' (or 0).
• Maximum value is '\uffff' (or 65,535 inclusive).
• Char data type is used to store any character.
• Example . char letterA ='A'
• byte: Byte data type is a 8-bit signed two's complement integer.
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
• Example : byte a = 100 , byte b = -50
Primitive Data Types:
• short: Short data type is a 16-bit signed two's complement integer.
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767(inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
• Default value is 0.
• Example : short s= 10000 , short r = -20000
• int: Int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648. (-2^31)
• Maximum value is 2,147,483,647. (2^31 -1)
• Int is generally used as the default data type for integral values unless there is a concern about memory.
• The default value is 0.
• Example : int a = 100000, int b = -200000
• long: Long data type is a 64-bit signed two's complement integer.
• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
• Example : int a = 100000L, int b = -200000L
Primitive Data Types:
float: Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example : float f1 = 234.5f
double: double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values. generally the default
choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example : double d1 = 123.4
Identifiers
• Important Note:
• Java identifiers are case-sensitive – this means that upper and lower case
letters are considered to be different – be careful to be consistent!
• Ex: AccountNo and accountno are NOT the same
• Naming Convention:
• Many Java programmers use the following conventions:
• Classes: start with upper case, then start each word with an upper case letter
• Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException
• Methods and variables: start with lower case, then start each word with an upper
case letter
• Ex: compareTo, lastIndexOf, mousePressed
Literals
• Values that are hard-coded into a program
• They are literally in the code!
• Different types have different rules for specifying literal values
• They are fairly intuitive and similar across most programming languages
• Integer
• An optional +/- followed by a sequence of digits
• Ex: 1024, -78, 1024786074
• Character
• A single character in single quotes
• Ex: ‘a’, ‘y’, ‘q’
• String
• A sequence of characters contained within double quotes
• Ex: “This is a string literal”
• See p. 75-77 for more literals
Variables Type casting in Java
• Note: For numeric types, you even get an error if the
value assigned will “lose precision” if placed into the
variable
• Generally speaking this means we can place “smaller”
values into “larger” variables but we cannot place
“larger” values into “smaller” variables
• Ex: byte < short < int < long < float < double
• Ex: int i = 3.5;

possible loss of precision found : double


required: int
int i = 3.5;
^

– Ex: double x = 100;


» This is ok
Variables
• Floating point literals in Java are by default double
• If you assign one to a float variable, you will get a “loss of precision
error” as shown in the previous slide
• If you want to assign a “more precise” value to a “less precise”
variable, you must explicitly cast the value to that variable type

int i = 5;
int j = 4.5;
float x = 3.5;
float y = (float) 3.5;
Error check each of the
double z = 100;
statements in the box to
i = z;
the right
y = z;
z = i;
j = (long) y;
j = (byte) y;
Operators and Expressions

• Numeric operators in Java include


+, –, *, /, %
• These are typical across most languages
• A couple points, however:
• If both operands are integer, / will give integer division, always producing an integer result –
discuss implications
• The % operator was designed for integer operands and gives the remainder of integer division
• However, % can be used with floating point as well
int i, j, k, m;
i = 16; j = 7;
k = i / j; // answer?
m = i % j; // answer?
Operators and Expressions
Operators and Expressions
Operators and Expressions
How to Take input in java (Using Scanner Class)
How to Take input in java (Using Scanner Class)

Method Description

it returns the next token from the


public String next()
scanner class.

it moves the Scanner position to


public String nextLine() the next line and returns the
value as a string

public byte nextByte() it reads the next token as a byte.

public int nextInt() it reads the next token as an int.

public float nextFloat() it reads the next token as a float.

public short nextShort() it reads the next token as a short.

public long nextLong() it reads the next token as a long.

it reads the next token as a


public double nextDouble()
double.

public boolean nextBoolean() it reads the boolean value.


How to Take input in java (Using Command Line Argument)
How to Take input in java (Using Command Line Argument)
Command Line Arguments in Java
If any input value is passed through the command prompt
at the time of running of the program is known
as command line argument by default every command
line argument will be treated as string value and those are
stored in a string array of main() method.
Wrapper class and their methods to convert default string
type args[] command line input into respective data type
Wrapper class and their methods to convert default string
type args[] command line input into respective data type
Conversion From String To Number Using Wrapper Class

Sr No Convert from string to Method

1 Byte Byte.ParseByte()

2 Short Short.valueOf()

3 Integer Integer.shortInt()

4 Long Long.parseLong()

5 Float Float.parseFloat()

6 Double Double.parseDouble()
Input through BufferedReader class
BufferedReader is another way to take the input
from the user, but it’s a bit more complex than the
Scanner class. java.io.BufferedReader reads text
from the character-input stream.

BufferedReader is a bit faster than Scanner as


Scanner does the parsing of input data, and
BufferedReader simply reads the sequence of
characters.

Wrapper classes and its methods are used to


convert input string by BufferedReader class
method readLine() in to its respective primitive
BufferReader vs Scanner class in Java

Scanner class BufferedReader class

The scanner class is not synchronous and does not support The BufferedReader class is synchronous and Widely used
threads. with multiple threads.

Scanner breaks its input into tokens using a Delimiter BufferedReader simply reads the sequence of characters in a
pattern. portion that depends on the buffer size.

It has a significantly larger buffer memory than Scanner.(8KB


The scanner has a little buffer(1KB byte buffer).
byte buffer)

Unlike Scanner, BufferedReader simply reads the sequence


The scanner is slow as it does the parsing of input data.
of characters. Hence it is faster than the Scanner Class. It
Moreover, It hides IOException.
throws an IOException.
Oral questions exercise
• What is bytecode? What is its significance ?
• How java is platform independent?
• List features of java?
• What is abstraction and encapsulation means?
• How to define constants in java
• List different ways to read input in java
• Differentiate Scanner vs. BufferedReader
• List methods of Scanner Class & Methods of Wrapper classes
• Should I use a scanner or BufferedReader in Java?
• What is data typecasting how it is carried out in java
• What is JVM?

You might also like