1 . What is Java (programming language)

What is Java?

   
(pic by wikipedia)

What is Java?

Java is a computer programming language and run time environment developed by Sun Microsystems.
The Java environment is composed of a number of system components. You use these components at compile time to create the Java program and at run time to execute the program.
Java is a programming language: a language that you can learn to write, and the computer can be made to understand.The most current is Java SE 11.
Java is Object-Oriented--that means everything in the language behaves like an object. What exactly that means will be explained in the coming Lessons.

The History of Java?

Java began as a simple research project at Sun Microsystems.In 1991, James Gosling and Patrick Naughton started working on a simplified programming language that could be used for control processors such as those found in cable TV devices. 
Such a language had to be modern, compact, easy to use, and independent of specific hardware.
Gosling first chose C++.But he soon gave up on C++,which was incapable of doing what he wanted.So, he started to modify C++ and soon, Gosling was writing a new language, which he named “Oak”.Oak became “Java”.
The original version of Java 1.0 was useful, but limited. In early 1996, Sun formed a new division to extend and improve Java.
In early 1997, the JDK 1.1 was released. The JDK 1.1 included many new features.By mid-1997, there were also Java-enabled devices and network computers.

Java Platform.

The Java Platform consists of more than just the original components of the JDK.The Java Software Development Kit (SDK) and the Java  Runtime Environment together make up the Java  Platform.
The Java Platform provides developers with a powerful, robust, and extensible platform for developing applets, applications, and reusable software components.

Pls Referr This Blog  Wikipedia  W3School

Features of Java

Java Is Small And Beautiful
Left out all the redundant features of programming languages.
The result is a language that has all the necessary features, combined in an elegant and logical way.
It is easy to learn but powerful.

Java Is Object-Oriented

 Object-oriented languages are the latest and most successful approach to programming.
 Object-oriented programming (OOP) is the most popular approach to programming in the late 1990s and into the new millennium.
 Java is completely object-oriented from the ground up.

Java Is General-Purpose

Java is general-purpose language.

Java’s Major Advantage over C & C++
Because pointers were a major source of bugs in C and C++, Gosling omitted pointers entirely from Java.
Actually, pointers are still an important part of the language. all objects are referenced by pointers but the language handles them, not the programmer.

Java Architecture

Java’s Architecture comes from four separate but intertwined technologies:
 Java Programming Language
 Java class file
 Java API
 Java Virtual Machine 


Java Supports The Internet

 Java enables people to develop programs that use the Internet and the World-Wide Web.
 The main motivation for Java was to enable people to develop programs that use the Internet and the World-Wide Web. 
 Java programs can easily be invoked from Web browsers like Netscape Navigator and Internet Explorer to provide valuable and spectacular facilities. 
 Also Java program can be easily transmitted   around the Internet and run on any computer.
 
Java Is Robust

If a Java program goes wrong it won’t create disorder, damage an uncertainty. Because Java programs run inside a protective ‘cage’, the effects of any errors are confined and controlled. 
java programs are even protected against infiltrations by viruses.Safeguards to ensure reliable code as follows:
Forces the user to find errors in the early stages of the programme development.
Checks the code at compile time and run time.
Memory Management by providing Garbage Collection.
Handles exceptional conditions by providing Exceptional Handling.

Java is Secure

 Java programs are even protected against infiltrations by viruses.
Java checks array boundaries
Java halts Buffer Overflows
 It verifies all memory access.
Because there are no pointers it ensures that programs cannot gain access to memory locations without proper authorization. 

Java is Distributed

 Can create applications on networks and has the ability to share both data and programs. 
 Java applications can open and access remote objects on Internet as easily as they can do in a local system. 

Java is Multithreaded and Interactive
Java supports multithreaded programming.
Allows the user to write programs that perform many functions simultaneously.
Eg: Listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer. 
This improves the interactive performance of graphical applications.

Java has High Performances

 Java was designed to perform well on very low-power CPUs.
 Java bytecode was carefully designed so that it can be easily interpreted.
 Java architecture is designed to reduce overheads during runtime.
 Multithreading enhances the overall execution speed of Java programs.

Java is Dynamic and Extensible

 Java programs carry lot of run-time information that is used to verify and access objects at run time.
 This concept makes it possible to dynamically link code.
   New class libraries, methods, and objects.
 Java programs support functions written in other languages such as C and C++.
   Known as native methods. 

Why Java ?

  It arose from the need to construct software for consumer electronics – VCRs, TVs, telephones, pagers and perhaps (one day) toaster. 

  C and C++, had drawbacks – it was not easy to transport software onto a new processor chip 

  Java was born with the objectives of creating very small, fast, reliable and transportable programs 

  It arose from the need to construct software for consumer electronics – VCRs, TVs, telephones, pagers and perhaps (one day) toaster. 


Object-Oriented Programming –OOP

  Everything in Java is an object.All program code and data reside within objects and classes.The Object Model makes Java simple and easy to extend.
  
  Programs are constructed from modules called objects.

  These are the building blocks that allow complex programs to be created. 

  An object is a grouping of some data together with the instructions that act on the data.

  So objects are made up of data and their associated methods. 

  OOP is about simulating or modeling real-world problems. 

  A model is built from objects that interact with each other by messages. 

  The programmer attempts to write the program in such a way as to model the real problem.

  closer the model is to reality, the better the program will do.

Java is both Compiled and Interpreted 

 First, Java compiler translates source code into bytecode instructions. 
 Secondly Java interpreter generates machine code that can be directly executed by particular machine that is running the Java program. 

Java is Platform Independent and Portable

 Java can be compiled once and run on any   platform that has a Java Virtual Machine (JVM).
 “Write once – run anywhere”
 Java ensures portability in two ways. 
 Java compiler generates bytecode.
 The size of the primitive data types are machine-independent.




Java Programs

   Java programs are two distinct types 

  Applications 

  Applets. 

Applets And Applications

Both types are programs. 

The difference is that an application is a completely free-standing program – it is not part of any other program and it doesn’t need any other program to launch it. 

In contrast, an applet is invoked as part of a Web page and therefore needs either a Web browser or an applet viewer to invoke it.

Java Applications

Java applications run through a Java Interpreter. 
Execution begins with the main() method of the Java application.

Java Environment

Before running a Java  Applications set some of the system variables.

Java Application

    class First
{
     public static void main (String args[])
{
  System.out.Println("Hello World");
}
}

Java Applet
  import java.awt.*;
  import java.applet.Applet;
 
     public class FirstApplet extends Applet 
        {
   public void paint (Graphics g)  
{
    g.drawString(“Hello World”,50, 50);
}
       } 

Tips :Java includes standard software libraries called packages, which execute specific commands. The import statement loads a Java package. 

Example in Some methods of Graphics class

setColor(Color c)   
    // Sets this graphics context's current color to the specified color 
g.setColor (Color.red);

drawLine(int x1, int y1, int x2, int y2) 
          // Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. 
g.drawLine(0,0,100,100);

drawRect(int x, int y, int width, int height) 
// Draws the outline of the specified rectangle. 
g.drawRect(30,0,80,40);
g.fillRect(30,0,80,40);

drawOval(int x, int y, int width, int height)
  // Draws the outline of an oval and fits within the rectangle specified by the x, y, width, and height arguments. 
g.drawOval(120,100,50,50);
g.drawOval(120,100,50,50);
Compiling and running

  After you write a Java program, you pass the program through the Java compiler. 
Java Source  ==>  java Compiler  ==> Bytecode File
  
 The compiler reads the statements in the program and translates them into a machine independent format called bytecode.
  Bytecode files are very compact, 
  They are easily transported through a distributed system like the Internet. You load and run the resulting bytecode file to execute the Java program. 
  Java bytecode is interpreted by the Java Virtual Machine - JVM
    
    Bytecode File -----> interpreter

To compile the application, use javac (command Pront CMD)
C:\MyJava> javac FirstJava.java

Java compiler generates intermediate “bytecode”. 

To run the class file, use java

C:\MyJava> java FirstJava

An interpreter is developed for each platform to interpret the bytecode.
Interpreter called the Java Virtual Machine or JVM 

Running an applet

we cannot run an applet directly, it has to be called from a ‘web document’ . So to do this we create a  web page which does that.
<html>
<head>
<title>First Applet</title>
</head>
<body>
<h1>First Applet</h1><hr>
<applet code=FirstApplet.class width=100 height=50></applet>
<hr>
</body>
</html>

C:\MyJava> appletviewer FirstApplet.html

Java Keywords

Keywords are a set of words reserved by computer programming languages such as Java for use                 within the language. 
Keywords help tell the compiler what your program is supposed to do. 
Keywords can't be used for other purposes such as variable names, class names, or method names.

Naming Variables

 Can be of any length. 

  Must start with a letter, _ or $

  Rest of the name can consists of any character  except operators

 Java identifiers are case sensitive. 

 Can not use any keyword in Java

Declaring variables

Type Name;
Eg.
int age;
boolean isTall;
String name;

Data Types

Primitive types

Reference Type

There are eight basic data types (Primitive Types) in Java. 

  Belongs to three categories

> Numeric Values (Integer & floating point)

> Variables that store single Unicode Character

> Logical Variable ( true or false)

Initialization
   Local & member variables can be initialize at the time of declaration.

e.g. int count = 20;
boolean found = true;

   Final Variables

final int pi = 3.14;

Operators
------------------------------------------------------------------------------------------------------------------------

 Arithmetic operators

+ *

Increment & decrement operators

++ e.g.  x++, ++x
- - e.g.  a- - , --a

Assignment operator
     e.g.  a=10,   x=y=10

Shorthand operator
        x += y  x = x + y
x -= y  x = x - y
x *= y  x = x * y
x /= y  x = x / y

Comparison operators

> < >= <= == !=

Relational operators

&& AND
|| OR
! NOT

Bitwise operators

  e.g. x = 31, y = 15;

& bitwise AND x & y 15
| bitwise OR x | y 31
^ bitwise XOR x ^ y 16
~ bitwise NOT ~ x -32
<< Left Shift x<<1 62
>> Right Shift x>>1 15


Bitwise Operators Example
    
  public class Lang
         {
        public static void main (String args[])   
{
        //11111=31 - 1111=15
int x=31, y=15, r;
r= x & y;
        System.out.println("x =  " + x + " y = " + y); 
System.out.println("x & y =" + r); 
r= x | y;       
System.out.println("x | y =" + r); 
r= x ^ y;       
System.out.println("x ^ y =" + r); 
r= x <<1;       
System.out.println("x << 1 =" + r); 
r= x >>1;       
System.out.println("x>> 1 =" + r);
r= ~x ;       
System.out.println("~ x =" + r);
      }
  }

Control Structures

 Selection Structures
        If Statement
If ….else Statement
Nested if … else Statements
Switch Statement
Conditional Operator

 Looping Structures

For Loop
While & do while loops


If Statement
if (condition) Statement 1
e.g :

if (marks>=50)  System.out.println(“Pass”); // Print Pass

if (condition)
{
  Statement 1;
Statement 2;
}
Code e.g:

if (x>5)
{
  int y=0;
y=x-5;
System.out.println(“y is “ + y);
}

The form of the condition has to be something that has only two possible answers -  true  or  false .

If ….else Statement
if (condition)
Statement 1;
else
Statement 2;

e.g.

if (marks>=50) {
System.out.println(“Pass”);
}else{
System.out.println(“Fail”);
}

Nested if … else Statements

e.g.
 int marks;
 
char grade;

if (marks>=70){
grade=‘A’;
}else if (marks>=55){
grade=‘B’;
}else if (marks>=40){
grade=‘C’;
}else{
grade=‘B’;
}
    System.out.println(grade);


Switch Statement
  
  switch (expression)
{
case Constant 1: Statement1;
case Constant 2: Statement2;
default : default Statement;
        }
e.g:

char opr;
int x,y,result;
switch (opr)
{
case ‘+’:
result=x+y;
break;
case ‘-’:
result=x-y;
break;
}


Q1. Find out a number between 1 and 9 is odd or even

public class CheckNo {
public static void main(String args[]) {
int x;
x=4;
switch (x)
{
case 2:
case 4:
case 6:
case 8:
System.out.println(x + " is Even");
break;
default:
System.out.println(x + " is Odd");
break;
}
}
}

Conditional Operator

  Condition? True Result : false Result

e.g.

int x, y, smaller;
smaller = x>y? y : x;
For Loop

For (initialization; test; increment)
{
statements
}
e.g :

int a;
For (a=1; a<=10; a++)
{
System.out.println(a); 
}

While Loop

While (condition)
{
statement;
}

e.g.

int x=1;
While (x<=10)
{
System.out.println(a);
x++; 
}

Do while Loop

do
{
statement;

}while (condition);

e.g:

int x=1;
{
System.out.println(a); 
x++;
} While (x<=10)

Arrays

Declaring

int ages[]={25,28,45,12,78}; or int [] ages={25,28,45,12,78};

int [] ages=new int[10];

Accessing
ages[0]=21;
ages[1]=25;
ages[2]=28;

System.out.println(ages[0]);


Command line argument

class CmdLine
{
public static void main(String args[])
{
Integer sub1 = Integer.valueOf(args[0]);
Integer sub2 = Integer.valueOf(args[1]);
Integer sub3 = Integer.valueOf(args[2]);

int s1=sub1.intValue();
int s2=sub2.intValue();
int s3=sub3.intValue();

double total=s1+s2+s3;
System.out.println("Total Marks: " + total);
}
}


Example 1 – Getting Data from Keyboard (String)

public class GetName
 {
    public static void main (String args[])   
{
        byte buffer[] = new byte[120];        
        int count = -1;
        System.out.print("Please Enter Your Name: ");        
try
        {   
count = System.in.read(buffer);   
}
        catch (Exception e)
       
  System.out.println( e.toString());
}        
        String message = new String();       
        if (count > -1)
        {
            message = new String(buffer, 0, count);
        }
        System.out.print("Your Name is " + message);        
     }
}

Example 2 – Getting Data from Keyboard (String)

import java.io.*;
class GetNewName
{
public static void main (String args[])
{
try
{
String s="";
//DataInputStream d = new DataInputStream(System.in);  //in JDK 1.1
BufferedReader d = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter Name: ");
s=d.readLine();
System.out.println("Your name is : " + s);
}
catch (IOException e)
{
}

}
}


Example 3 – Getting Data from Keyboard (String)

import java.util.*;

class KbInput2
{
public static void main (String args[])
{
String name;
Scanner kb = new Scanner(System.in);
try
{
System.out.print("Enter Name: ");
name=kb.next();
System.out.println("Name is " + name);
}
catch (InputMismatchException e)
{
System.out.println(e.getMessage());
}
}
}

Example – Getting Data from Keyboard (Numbers)

import java.util.*;

class GetAge
{
public static void main (String args[])
{
long age;
Scanner kb = new Scanner(System.in);
try
{
System.out.print("Enter Age: ");
age=kb.nextLong();
System.out.println("Age is " + age);
}
catch (InputMismatchException e)
{
System.out.println(e.getMessage());
}
}
}

Example – Creating a new Class

class Box
{ // Instance Variables
private double w,h,d;
// Method
double getVolume()
{
return w*h*d;
}
void setDimen(double inW, double inH, double inD)
{
w=inW;
h=inH;
d=inH;
}
// Constructor for Box
Box(double inW, double inH, double inD)
{
w=inW;
h=inH;
d=inH;
}
}

Example – Creating a new object

class BoxDemo
{
public static void main (String args[])
{
Box b1 = new Box(10,10,10);
double vol;
vol=b1.getVolume();
System.out.println(vol);
b1.setDimen(5,5,5);
vol=b1.getVolume();
System.out.println(vol);
}
}

Object Oriented Programming

  Action Oriented vs. Object Oriented
In procedural languages, main unit of processing is function
The data and method that operate on data are kept separately.
In OOP, a program is made up of a set of objects.
Object is a single unit that combine data and method into a single unit
Two main concept of OOP are the concept of a class and object

Post a Comment

Previous Post Next Post

Featured Post