[go: up one dir, main page]

0% found this document useful (0 votes)
49 views23 pages

CH 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

CHEPTER: 1

INTRODUCTION TO JAVA & ELEMENTRY OF


PROGRAMMING

 JAVA LANGUAGE SPECIFICATION API:

 The Java language specification is a technical definition of the Java programming


language's syntax and semantics.
 API stands for Application Program Interface.
 The application program interface (API), also known as library, contains predefined
classes and interfaces for developing Java programs.

 FEATURES OF JAVA:

 There are also some excellent features which play an important role in the popularity
of this language. The features of java are also known as java buzzwords.

1
 Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

1. Java syntax is based on C++ (so easier for programmers to learn it after C++).
2. Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
3. There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

 Object-oriented

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

 Platform independent

Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.

2
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms.
It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere(WORA).

 Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

1. No explicit pointer
2. Java Programs run inside a virtual machine sandbox

3
1. Class loader: Class loader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
2. Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
3. Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.

 Robust:

Robustsimply means strong. Java is robust because:

1. It uses strong memory management.


2. There is a lack of pointers that avoids security problems.
3. There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.

4
4. There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

 Architecture-neutral:

Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.

 Portable:

Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

 High-performance:

Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.

 Distributed:

Java is distributed because it facilitates users to create distributed applications in Java.


RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.

 Multi-threaded:

A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.

5
 Dynamic:

Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

 JDK [ JAVA DEVLOPMENT KIT]:


The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications and applets. It physically exists. It contains JRE +
development tools.

JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

1. Standard Edition Java Platform


2. Enterprise Edition Java Platform
3. Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc.

6
 IDE [ INTEGRATED DEVLOPMENT ENVIRONMENT]:

Most of us get confused when we heard the term IDE, what the hell is that, where it come
from. So, to make it simple, you can compare it to your school time copy or registers
where you use them to write down the school topics or notes but actually it is more
than register.

Examples:

1. Eclipse
2. Bordland
3. NetBeans
4. BlueJ

 CREATING, COMPILING AND EXECUTING A SIMPLE JAVA CODE:

class Simple {
public static void main(String args []) {
System.out.println("Hello Java");
}
}

save this file asSimple.java

To compile:javac Simple.java

To execute: java Simple

7
 PARAMETERS USED IN JAVA:

 Class: keyword is used to declare a class in java.


 Public: keyword is an access modifier which represents visibility. It means it is
visible to all.
 Static: is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create
an object to invoke the static method. The main method is executed by the JVM,
so it doesn't require to create an object to invoke the main method. So, it saves
memory.
 Void: is the return type of the method. It means it doesn't return any value.
 Main: represents the starting point of the program.
 String[] args: is used for command line argument. We will learn it later.
 System.out.println(): is used to print statement. Here, System is a class, out is
the object of PrintStream class, println() is the method of PrintStream class. We
will learn about the internal working of System.out.println statement later.

 DOCUMENTATION IN JAVA:

We can create document api in java by the help of Javadoc tool. In the java file, we must
use the documentation comment /**... */ to post information for the class, method,
constructor, fields etc.

package com.abc;
/** This class is a user-defined class that contains one methods cube.*/
public class M{
/** The cube method prints cube of the given number */
public static void cube (int n){
System.out.println(n*n*n);}
}

On the command prompt, you need to write:

javadoc M.java

8
 READ INPUT FROM CONSOLE:

 Buffered-reader class:

This strategy is utilized by wrapping the System.in (standard information stream) in an


InputStreamReader which is wrapped in a Java Buffered Reader.

Example:

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[]args) throws IOException
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
}
}

9
 Scanner class:

Helpful strategies for parsing natives (nextInt(), nextFloat(), … ) from the tokenized
input.
General articulations can utilize to discover tokens.

Example:

import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

 Console class:
Reading secret word without reverberating the entered characters.
Reading strategies that are synchronized.
Format string sentence structure can utilize.

Example:

public class Sample


{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);
}
}

 JAVA NAMING CONVENTION:

10
Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method, etc.

 Class:
o It should start with the uppercase letter.
o It should be a noun such as Colour, Button, System, Thread, etc.
o Use appropriate words, instead of acronyms.

Example:

public class Employee


{
//code snippet
}

 Interface:

o It should start with the uppercase letter.


o It should be an adjective such as Runnable, Remote, ActionListener.
o Use appropriate words, instead of acronyms.

Example:

interface Printable
{
//code snippet
}

 Method:
o It should start with lowercase letter.
o It should be a verb such as main(), print(), println().
o If the name contains multiple words, start it with a lowercase letter followed by an
uppercase letter such as actionPerformed().

Example:

11
class Employee
{
//method
void draw()
{
//code snippet
}
}

 Variable:

o It should start with a lowercase letter such as id, name.


o It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
o If the name contains multiple words, start it with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
o Avoid using one-character variables such as x, y, z.

Example:

class Employee
{
//variable
int id;
//code snippet
}

 Package:

o It should be a lowercase letter such as java, lang.


o If the name contains multiple words, it should be separated by dots (.) such as
java.util, java.lang.

Example:

12
package com.javatpoint; //package
class Employee
{
//code snippet
}

 Constant:
o It should be in uppercase letters such as RED, YELLOW.
o If the name contains multiple words, it should be separated by an underscore (_) such
as MAX_PRIORITY.
o It may contain digits but not as the first letter.

Example:

class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}

 DATATYPES IN JAVA:

There are two types of data types in Java:

1. Primitive data types: The primitive data types include Boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

13
 Boolean Data Type:

The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example: Boolean one = false

 Byte Data Type:

The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is
most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.

Example: byte a = 10, byte b = -20

 Short Data Type:

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value
is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

14
Example: short s = 10000, short r = -5000

 Int Data Type:

The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there
is no problem about memory.

Example: int a = 100000, int b = -200000

 Long Data Type:

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum valueis -9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

 Float Data Type:

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating-point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

 Double Data Type:

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range
is unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.

Example: double d1 = 12.3

15
 Char Data Type:

The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example: char letterA = 'A'

 JAVA OPERATOR PROCEDURE:


 Java unary Operator:

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o Incrementing/decrementing a value by one


o Negating an expression
o Inverting the value of a Boolean.

Example: ++ & --

class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}

Output:

10
12
12
10

Example: ~& !

16
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//11 (minus of total positive value which st
arts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts
from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Output:

-11
9
false
true

 Java Arithmetic Operator:

Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Example:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0

17
}
}

Output:

15
5
50
2
0

 Java left shift Operator:

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Example:

class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}

Output:

40
80
80
240

 Java right shift Operator:

The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.

Example:

18
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}

Output:

2
5
2

Example: >> vs >>> Shift operator

class OperatorExample
{
public static void main(String args[])
{
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}

Output:

5
5
-5
1073741819
 Java AND Operator example: Logical&& vs Bitwise&

The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true.

19
The bitwise & operator always checks both conditions whether first condition is true or
false.

Example 1:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}

Output 1:

false
false

Example 2:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}

Output 2:

false
10
false
20
11

 Java OR Operator: Logical || vs Bitwise |

The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or
false.

Example:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condi. is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Output:

true
true
true
10
true
11
 Java ternary Operator:

Java Ternary operator is used as one liner replacement for if-then-else statement and
used a lot in Java programming. it is the only conditional operator which takes three
operands.

21
Example:

class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

Output:

 Java Assignment Operator:

Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.

Example:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}

Output:

14
16

22
Example: Adding short

class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}
}

Output:

Compile time error

After type cast:

class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}
}

Output:

20

23

You might also like