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

Java Capter 1&2

The document provides an introduction to object-oriented programming concepts and Java programming language concepts. It discusses the differences between structured and object-oriented programming, with OOP focusing on data and having features like inheritance, encapsulation, and polymorphism. Key Java concepts are discussed like it being platform independent, object-oriented, and its basic Hello World program. It also covers Java variables and data types.

Uploaded by

Magarsaa Qana'ii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Java Capter 1&2

The document provides an introduction to object-oriented programming concepts and Java programming language concepts. It discusses the differences between structured and object-oriented programming, with OOP focusing on data and having features like inheritance, encapsulation, and polymorphism. Key Java concepts are discussed like it being platform independent, object-oriented, and its basic Hello World program. It also covers Java variables and data types.

Uploaded by

Magarsaa Qana'ii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CHAPTER 1: INTRODUCTION TO OOPS CONCEPTS

Difference between structured programming and object oriented programming:

Object Oriented Programming


Structured Programming
1.Structured Programming is designed which
1.Object Oriented Programming is designed
focuses on process/ logical structure and then data
which focuses on data.
required for that process.
2.Structured programming follows top-down 2.Object oriented programming follows
approach. bottom-up approach.
3.Structured Programming is also known as 3.Object Oriented Programming supports
Modular Programming and a subset of inheritance, encapsulation, abstraction,
procedural programming language. polymorphism, etc.
4.In Object Oriented Programming,
4.In Structured Programming, Programs are
Programs are divided into small entities
divided into small self contained functions.
called objects.
5.Structured Programming is less secure as there is 5.Object Oriented Programming is more
no way of data hiding. secure as having data hiding feature.
6.Structured Programming can solve moderately 6.Object Oriented Programming can solve
complex programs. any complex programs.
7.Structured Programming provides less 7.Object Oriented Programming provides
reusability, more function dependency. more reusability, less function dependency.

8.More abstraction and more flexibility


8.Less abstraction and less flexibility.

Object
This is the basic unit of object oriented programming. That is both data and function that operate
on data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place.
While working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you framework to place the data and the
relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called as derived class. This is a very
important concept of object-oriented programming since this feature helps to reduce the code
size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers to many.
That is a single function or an operator functioning in many ways different upon the usage is
called polymorphism.
CHAPTER 2: INTRODUCTION TO JAVA CONCEPTS
Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and
its widespread popularity, multiple configurations were built to suite various types of platforms.
Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.

Java is:

 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.

 Platform independent: Unlike many other programming languages including C and


C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.

 Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP
Java would be easy to master..

 High Performance: With the use of Just-In-Time compilers, Java enables high
performance.

 Distributed: Java is designed for the distributed environment of the internet.

 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to


adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.

Tools you will need:


 Linux 7.1 or Windows xp/7/8 operating system.

 Java JDK 8
 Microsoft Notepad or any other text editor(IDE:NETBEANS OR ECLIPSE)

First Java Program:


Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.

* This will print 'Hello World' as the output

*/

public static void main(String []args) {

System.out.println("Hello World"); // prints Hello World

Let's look at how to save the file, compile and run the program. Please follow the steps given
below:

 Open notepad and add the code as above.

 Save the file as: MyFirstJavaProgram.java.

 Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.

 Type ' javac MyFirstJavaProgram.java' and press enter to compile your code. If there are
no errors in your code, the command prompt will take you to the next line (Assumption :
The path variable is set).

 Now, type ' java MyFirstJavaProgram ' to run your program.

 You will be able to see ' Hello World ' printed on the window.
 C:\> javac MyFirstJavaProgram.java
 C:\> java MyFirstJavaProgram
 Hello World
About Java programs, it is very important to keep in mind the following points.

 Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.

 Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.

Example class MyFirstJavaClass

 Method Names - All method names should start with a Lower Case letter.

If several words are used to form the name of the method, then each inner word's first
letter should be in Upper Case.

Example public void myMethodName()

 Program File Name - Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
d0 not match your program will not compile).

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'

 public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.
Variables and data types in Java:
Variables are nothing but names, which we can declare to store some values.

The syntax for variables definition is:

VariableType variablename=value;

integer
This group includes byte , short , int , long

byte : It is 8 bit integer data type. Value range from -128 to 127. Default value zero.
example: byte b=10;

short : It is 16 bit integer data type. Value range from -32768 to 32767. Default value zero.
example: short s=11;

int : It is 32 bit integer data type. Value range from -2147483648 to 2147483647. Default value
zero. example: int i=10;

long : It is 64 bit integer data type. Value range from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. Default value zero. example: long l=100012;

Floating-Point Number
This group includes float , double

float : It is 32 bit float data type. Default value 0.0f. example: float ff=10.3f;

double : It is 64 bit float data type. Default value 0.0d. example: double db=11.123;

Characters
This group represent char , which represent symbols in a character set, like letters and numbers.

char : It is 16 bit unsigned unicode character. Range 0 to 65,535. example: char c='a';
Boolean
This group represent boolean , which is a special type for representing true/false values. They
are defined constant of the language. example: boolean b=true;

Java Operators
Java provides a rich set of operators enviroment. Java operators can be devided into following
categories

 Arithmetic operators
 Relation operators
 Logical operators
 Assignment operators
 Conditional operators

Arithmetic operators

Arithmetic operators are used in mathematical expression in the same way that are used in
algebra.

operator description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division
++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one

Relation operators

The following table shows all relation operators supported by Java.

operator description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators

Java supports following 3 logical operator. Suppose a=1 and b=0;

operator description example

&& Logical AND (a && b) is false


|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Assignment Operators

Assignment operator supported by Java are as follows

operator description example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same as
a=a+b

-= subtracts right operand from the left operand and assign the result to a-=b is same as a=a-
left operand b

*= mutiply left operand with the right operand and assign the result to a*=b is same as
left operand a=a*b

/= divides left operand with the right operand and assign the result to a/=b is same as a=a/b
left operand

%= calculate modulus using two operands and assign the result to left a%=b is same as
operand a=a%b

Conditional operator

It is also known as ternary operator and used to evaluate Boolean expression


epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3
In while loop first check the condition if
Looping statement
condition is true then control goes inside

Looping statement are the statements the loop body otherwise goes outside of

execute one or more statement repeatedly the body. while loop will be repeats in clock

several number of times. In java wise direction.

programming language there are three

types of loops; while, for and do-while.

Why use loop ?

When you need to execute a block of code

several number of times then you need to

use looping concept in Java language.

Advantage with looping statement

 Reduce length of Code

 Take less memory space.

 Burden on the developer is


reducing.

 Time consuming process to execute


the program is reduced.
Syntax

Difference between conditional and


looping statement while(condition)

Conditional statement executes only once {

in the program where as looping Statement(s)


statements executes repeatedly several
Increment / decrements (++ or --);
number of time.
}

While loop
Example while loop
}
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i);
i++;
}
 Initialization: This step is execute
first and this is execute only once
Output
when we are entering into the loop
first time. This step is allow to
1
declare and initialize any loop
2
control variables.
3  Condition: This is next step after

4 initialization step, if it is true, the


body of the loop is executed, if it is
5
false then the body of the loop does
not execute and flow of control goes
for loop outside of the for loop.

for loop is a statement which allows code


 Increment or Decrements: After

to be repeatedly executed. For loop


completion of Initialization and

contains 3 parts Initialization, Condition


Condition steps loop body code is

and Increment or Decrements


executed and then Increment or
Syntax Decrements steps is execute. This
statement allows to update any loop
for ( initialization; condition; increment )
control variables.
{
Flow Diagram
statement(s);
Hello Friends !
Control flow of for loop Hello Friends !

Hello Friends !

 First initialize the variable

 In second step check condition

 In third step control goes inside


do-while
loop body and execute.

 At last increase the value of variable A do-while loop is similar to a while loop,

except that a do-while loop is execute at


 Same process is repeat until
least one time.
condition not false.
Improve your looping conceptFor Loop A do while loop is a control flow statement

that executes a block of code at least


Display any message exactly 5
times. once, and then repeatedly executes the

Example of for loop block, or not, depending on a given

condition at the end of the block (in while).


class Hello
{
public static void main(String args[])
{ When use do..while loop
int i;
for (i=0: i<5; i++) when we need to repeat the statement

{ block at least one time then ues do-while


System.out.println("Hello Friends !"); loop. In do-while loop post-checking
}
process will be occur, that is after
}
} execution of the statement block condition

part will be executed.


Syntax
Output

do
Hello Friends !

{
Hello Friends !
Statement(s) {public static void main(String args[])
{
int i=0;
increment/decrement (++ or --) do
{
}while();
System.out.println(+i);
i++;
}
In below example you can see in this
while(i<5);
program i=20 and we chech condition i is
}
less than 10, that means conditon is false }
but do..while loop execute onec and print

Hello world ! at one time. Output

Example do..while loop


1

class dowhileDemo 2
{
public static void main(String args[]) 3
{
4
int i=20;
do 5
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}
Array in java
Output
Array is a collection of similar
type of data. It is fixed in size that
Hello world !
means you can't increase the size of
Example do..while loop array at run time. It is collection of
homogeneous data elements. It
class dowhileDemo
store the value on the basis of There are two types of array in
index value. java.

 Single Dimensional Array


Advantage of Array  Multidimensional Array

One variable can store multiple Array Declaration


value: The main advantage of array
is we can represent multiple value Single dimension array declaration.
under the same name. Syntax
Code Optimization: No, need to
declare a lot of variable of same 1. int[] a;
type data, We can retrieve and 2. int a[];
short data easily. 3. int []a;
Random access: We can retrieve
any data from array with the help
Note: At the time of array
of index value.
declaration we can not specify the
size of array. For Example int[5] a;
Disadvantage of Array
this is wrong.
The main limitation of array is Size
2D Array declaration.
Limit when once we declare array
there is no chance to increase and Syntax
decrease the size of array according
1. int[][] a;
to our requirement, Hence memory
2. int a[][];
point of view array concept is not
recommended to use. To over come 3. int [][]a;
this limitation in java introduce 4. int[] a[];
collection concept. 5. int[] []a;

Types of Array
6. int []a[]; public static void main(String
[]args)
{
int arr[] = {10,20,30};
Array creation for (int i=0; i < arr.length; i++)
{
Every array in a java is an object, System.out.println(arr[i]);
Hence we can create array by }
}
using new keyword. }
Syntax

int[] arr = new int[10]; // The Output


size of array is 10.
or 10
int[] arr = {10,20,30,40,50};
20
39
Accessing array elements
Access the elements of array by Note:
using index value of an elements. 1) At the time of array creation we
must be specify the size of array
Syntax
otherwise get an compile time
arrayname[n-1]; error. For Example
int[] a=new int[]; Invalid.
Access Array Elements int[] a=new int[5]; Valid
int[] arr={10,20,30,40}; 2) If we specify array size as
System.out.println("Element at
negative int value, then we will get
3th place"+arr[2]);
run-time error,
Example of Array NegativeArraySizeException.

public class ArrayEx 3) To specify array size the allowed


{ data types are byte, short, int, char
If we use other data type then we
will get an Compile time error.

4) The maximum allowed size of


array in java is 2147483647 (It is
maximum value of int data type)

length vs length()
length: It is a final variable and
only applicable for array. It
represent size of array.
Example

int[] a=new int[10];


System.out.println(a.length); //
10
System.out.println(a.length()); //
Compile time error

length(): It is final method


applicable only for String objects.
It represent number of character
present in String.
Example

String s="Java";
System.out.println(s.length()); //
4
System.out.println(s.length); //
Compile time error

You might also like