What is Java
Java was developed by James Gosling at Sun Microsystems in 1991.
Gosling's goals were to implement a virtual machineand a language that had a familiar C/C++ styleof notation.
Java is a popular programming language.
It is now owned by Oracle, and more than 3 billion devices run Java.
JVM (Java Virtual Machine)
Software from Oracle that converts a program in Java bytecode (intermediate language) into machine language and executes it. The Java Virtual Machine (JVM) is the runtime engine of the Java Platform, which allows any program written in Java or other language compiled into Java bytecode to run on any computer that has a native JVM. JVMs run in both clients and servers, and the Web browser can activate the JVM when it encounters a Java applet.
The JVM includes a just-in-time (JIT) compiler that converts the bytecode into machine language so that it runs as fast as a native executable. The compiled program can be cached in the computer for reuse.
Java Runtime Environment (JRE)
JRE is the part of the Java Development Kit (JDK). It is a freely available software distribution which has Java Class Library, specific tools, and a stand-alone JVM. It is the most common environment available on devices to run java programs. The source Java code gets compiled and converted to Java bytecode. JRE is required to run bytecode. The JRE loads classes, verify access to memory, and retrieves the system resources. JRE acts as a layer on the top of the operating system.
Java Development Kit (JDK)
The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets.
It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
For developers who wish to work in an integrated development environment (IDE), a JDK bundled with Netbeans can be downloaded from the Oracle website. Such IDEs speed up the development process by introducing point-and-click and drag-and-drop features for creating an application.
Advantages of Java
- Java is easy to learn.
- Java is object-oriented.
- Java is platform-independent.
- Java is cheap and economical to maintain.
- Java provides Automatic Garbage Collection.
- Java supports Multithreading.
- Java is a distributed language.
- Java is secure
- Java is compact
Disadvantages of Java
- Java is slow and has a poor performance.
- Java provides not so attractive look and feels of the GUI.
- Java provides no backup facility.
- Java requires significant memory space.
- Verbose and Complex codes.
Variables and Data Types
The Data Type of a Variable can be either a Primitive Data Type , Reference Data Type or array Data types.
Variables with Primitive Data Types store simple data like integers, reals, booleans and characters.
Variables with Reference Data Types store Java objects that are instances of classes.
Variables with array data types store data of that particular array type.
Primitive Data Types
Type | Bits |
---|---|
byte | 8 |
short | 16 |
int | 32 |
long | 64 |
float | 32 |
double | 64 |
char | 16 |
boolean |
Naming Variables
Can only Start with a Letter, the Underscore _or the Dollar Sign $.
score or the Dollar Sign, but cannot include Symbols such as %, @, * and so on.
Names are Case Sensitive. Hence Value, VALUE, value, vALuEmay all be used as names for different variables.
It is a convention to start a variable name with a lower case letter. (ex : age, month, address, location...)
If the variable name is made up of several words, then from the second word onwards the first letter of each word is in upper case. (empName, empDOB, custName..)
Arrays
Arrays provide a way of storing a list of variables of the same data type, one after the other.
Arrays must be declared. For example, an array of 10 integers might be declared as:
int[] a = new int[10];
Elements of an array can be accessed by indicating the index (position) of the element in the array inside square brackets. Indexing (Position numbering) begins with 0.
For example, to access the first element in an array, a[0], the second element a[1], and so on.
Multi Dimensional Arrays
In Java Multi Dimensional Arrays are just Arrays of
inttwoDMatrix[ ][ ] = new int[4][6];
inttwoDMatrix[ ][ ] ={ {5,1,2,8,6,9}, {8,4,1,6,2,1}, {3,9,2,5,8,9}, {1,7,3,6,4,3} };
intthreeD[][][]=new int[4][5][3];
Examples1 public class MyArr1D { public static void main(String[] args) { int[] mark={30,50,78,45,30}; //define array int i; for (i=0;i <mark.length;i++) System.out.println(mark[i]); } } Examples2 public class MyArr2D { //Two dimention Array public static void main(String[] args) { int[][] mark={{10,20,30},{5,15,25},{11,22,33}}; //define array int i,j; //display for (i=0;i <3;i++) for(j=0;j <3;j++) System.out.println(mark[i][j]); } } Examples3 public class NewMain { public static void main(String[] args) { int[] mark={30,50,78,45,30}; //define array int i; for (i=0;i <mark.length;i++) System.out.println(mark[i]); } }
Operators
An operator is a function that has a special symbolic name and is invoked by using that symbol with an expression.
Java has several kinds of Operators
Arithmetic Operators: These are used to perform standard arithmetic operations performed on numbers. ( + - Addition, - Subtraction, * Multiplication, / Division, % Modulus)
Assignment Operator: This is used to assigns a variable with a value ( =)
Logical (Boolean) Operators: These are used to perform standard logical operations on Boolean values (&& - And, || - Or, ! Not)
Bitwise Operators: These perform operations on the individual bits of integers (& - BitWise And, | - BitWise Or, ^ - BitWise Xor, << - Left Shift, >> - Right Shift, ~ - Bitwise Complement)
Conditional Operator:This acts as a shorthand for if-then-else ( ?: )
Relational Operator: ( == - Equal to, != - Not Equal, > - Greater than, < - Less than, >= - Greater than or equal, <= - Less than or equal)
Comments in Java
Comments are additional text included in programs, strictly for the benefit of the person reading the program. Comments are not compiled or executed.
Types of Comments
Single-line comments: //This is my first program
Multi-line comments: /*This method prints “Hello World!!!” to the command line*/
Javadoc comments: /** @author John Smith @date 2007 January 1 */
Flow Control
Control flow refers to the order in which statements are executed in an algorithm.
Usually, an algorithm executes sequentially; that is the first statement executes, then the second and so on. However, it is often useful to be able to alter this flow.
A flow control statements a statement that changes the order of execution of subsequent statements.
main types of flow control statements are Selection Statements , Iterative Statements and Jump Statements
Iterative Statements
Iterative statements execute a set of statements over and over again, until some condition is satisfied.
Iterative/Repetitions in Java
There are three repetitions/loops in java
for
do...while
while
while public class JavaApplication1 { public static void main(String[] args) { int x; x=1; while (x <=100) { System.out.println(x); x=x+1; } } } do ... while public class JavaApplication1 { public static void main(String[] args) { int x; x=1; do { System.out.println(x); x=x+1; } while (x <=100); } } for public class JavaApplication1 { public static void main(String[] args) { int x; for(x=1;x <=100;x=x+1) System.out.println(x); } }
Selection Statements
A Selection Statement, evaluates some expression, and depending on the expression’s value, selects one of several possible sets of statements to execute.
In java, we have two types of selection statements: (If, Switch)
Selections in Java
if else public class JavaApplication1 { public static void main(String[] args) { int x; x=30; if (x>=40) System.out.println("Pass"); else System.out.println("Fail"); } } Switch public class JavaApplication1 { public static void main(String[] args) { char c; c='B'; switch (c) { case 'A': System.out.println("Excelent"); break; case 'B': System.out.println("Very Good"); break; case 'C': System.out.println("Good"); break; case 'S': System.out.println("Pass"); break; default: System.out.println("Fai"); } } }
Jump Statements
Jump statements move the point of execution in a program from one place to another place.
In java we have 3 types of Jump Statements. (Break, Continue, Return, labelled break and continue statements)
public class MyBreak { public static void main(String[] args) { int x; x=1; while (x <=100) { System.out.println(x); if (x==50) break; x=x+1; } } } public class LabeledBreak { public static void main(String[] args) { int counter = 0; start: { for (int i = 0; i <= 10; i++) { if (i == 5) break start; counter+=1; } } System.out.println(counter); } }
Data scope
Global : Data with Global scope are accessible by a number of procedures. Global data defined within an outer procedure & may then be shared by the inner procedures. Care should be taken when using data with Global scope.
Local: Data with Local scope can be accessed only within the procedure inside which it is defined. This removes the possibility of data being corrupted by other procedures. It is possible for a number of procedures to each have different variables, each with the identical name.
Program Structure and Modular Design
Top down decomposition
Top down decomposition is the breaking down of a large, complex procedure into a number of smaller procedures is referred to as top-down decomposition.
The aim of this decomposition is to progressively simplify large and/or complex procedures by breaking them up into smaller, simpler procedures.
This is repeated until these procedures are well understood, relate to a single task and are simple enough to express in program code.
Principles for decomposition
- Improved Understandability
- Clear identification of tasks
- Eliminate duplication of coding.
- Ease of Maintenance
- Code reusability
Communication between procedures
Procedures communicate with another by sharing global data and/or by passing parameters between them.
At the same time, some of the sub procedures into which we decompose a program may be able to operate in complete isolation from the rest of the events within the program.
Global data: Declared to be accessible by the procedure in which it is defined, and all the sub-procedures defined within that defining procedure. This data is only available to internal sub procedures, not to external sub-procedures.
Passed Parameters
Parameters may be specifically passed between a calling and a called procedure. They may pass data from a calling procedure to a called procedure.
They may pass data back from a called procedure to its calling procedure.
They may passed between the calling and called procedures by being included in the definition amended in some way & passed back again to the calling procedure.
Example 1: public class Main { static void myCalc(int x, int y) { System.out.println(x+y); } public static void main(String[] args) { myCalc(20,30); myCalc(100,500); } } Example 2: public class Main2 { static String myGrade(int marks) { if (marks > 50) return "Pass"; else return "Fail"; } public static void main(String[] args) { System.out.println(myGrade(30)); System.out.println(myGrade(70)); } } Examples 3: public class Main3 { static int x,y,tot; //Global Data static void myTot() { tot=x+y; } static void myPrint() { System.out.println(tot); } public static void main(String[] args) { x=100; y=200; myTot(); myPrint(); } }
Object Oriented Concepts and Techniques
The central idea of Object Oriented Programming is to organize your programs in a way that mirrors the way objects are organized in the real world.
Object oriented programming is, at its root, a way to conceptualize a computer program.
This is a way to look at a program is as a set of objects that work together in predefined ways to accomplish tasks.
Using OOP, your overall program is made up of different objects.
Objects
An object is a self-contained element of a computer program that represents a related group of features and is designed to accomplish specific tasks.
Also known as instances.
Each object has a specific role in a program, and all objects can work with other objects in specifically defined ways.
A ‘thing’ may have a physical presence such as a ‘table’ ,‘chair’or an abstract concept such as ‘a job’.
An object is an abstract representation of a ‘thing’in the real world.
We simulate a problem domain in the real -world through objects.
An object has a unique identity, attributes (What it knows or data about it), and behavior (What it can do).
Classes
A Class is a template used to create multiple objects with similar features.
When we write a program in an OO language, we don’t need to define individual objects. Instead, we define classes of objects. Classes embody all features of a particular set of objects.
Every class written in java made up of two components: Attributes (what it knows) and Behavior (what it can do)
Instance variables and Class variables
Instance variables
An instance variable is an item of information that defines an attribute of one particular object.
The object’s class defines what kind of attribute it is, and each instance object stores its own value for that attribute.
Instance variables also known as object variables.
Class variables
A Class variables is an item of information that defines an attribute of an entire class.
The variable applies to the class itself and to all of its instances.
Methods
Methods are group of related statements in a class of objects that act on themselves and on other classes and objects.
Methods are used to accomplish specific tasks. Objects communicate with each other using methods.
It is possible to define two ore more methods with the same name within the same class with different signatures. This is known as Method Overloading.
Instance methods: Apply to an instance object of the class. If the method makes a change to an individual object, it must bean instance method.
Class methods: Apply to the class itself.
Recursion: A method calling itself is known as recursion.
Constructor
These methods are used to initialize objects.
They have the same name as the class and have no return type.
These methods are called automatically when the new operator is used to allocate memory for an object.
A class can have multiple Constructors (Overloaded Constructors). They have either different number of arguments or different types of arguments (that is, they have different signatures)
Examples: Classes in Java //define class class Customer { //data member of class int code; String cname; //method of class public void datain(int c,String s) { this.code=c; this.cname=s; } public void dataout() { System.out.print(this.code); System.out.println(this.cname); } //main method public static void main(String[] args) { //create object Customer c1=new Customer(); c1.datain(10, "Peter"); c1.dataout(); Customer c2=new Customer(); c1.datain(20, "David"); c1.dataout(); } } Constructors In Java //define class class Cust { int code; String cname; //deefine default constructor Cust() { this.code=0; this.cname=" "; } //define constructor overloading with parameters Cust(int c,String s) { this.code=c; this.cname=s; } public void dataout() { System.out.print(this.code); System.out.println(this.cname); } //main method public static void main(String[] args) { Cust c1=new Cust(); //create object c1.dataout(); Cust c2=new Cust(20,"Ganesh"); c2.dataout(); } } Inheritance in Java //inherit class cust class NewCust extends Cust { String address; NewCust() { super(); //call parent constructor this.address=""; } NewCust(int c,String s,String add) // define new constructor with 3 parameters { super(c,s); this.address=add; } public void dataout() // override method of cust class { super.dataout(); System.out.println(address); } //main method public static void main(String[] args) { Cust c1=new Cust(); c1.dataout(); Cust c2=new Cust(20,"Ganesh"); c2.dataout(); NewCust c3=new NewCust(30,"Akshaya","Main Road"); //create new object c3.dataout(); } } Interface in Java //define interface interface Myinter { public void myPrint(); public void MyRun(); } //using interface and override all methods public class InterTest implements Myinter { public void myPrint() //method override { System.out.println("Implement ok"); } public void MyRun() { System.out.println("MYrun ok"); } //main method public static void main(String[] args) { InterTest t1=new InterTest(); t1.myPrint(); t1.MyRun(); } } Thread in Java //inherits the Thread class public class MyThread extends Thread { int x; public void run() //override run method { for (x=1; <=10;x++) { System.out.println(x); } } //main method public static void main(String[] args) { MyThread t1=new MyThread(); //create object t1.start(); MyThread t2=new MyThread(); t2.start(); } } By implement runnable interface public class MyThread implements Runnable { int x; public void run() { for (x=1;x <=10;x++) { System.out.println(x); } } } //main method public static void main(String[] args) { MyThread t1=new MyThread(); Thread tt1=new Thread(t1); MyThread t2=new MyThread(); Thread tt2=new Thread(t1); tt1.start(); tt2.start(); }
Java Exercises
1)
Print numbers between 1 and 100 and state whether the number is prime or not prime.
public static void main(String[] args) { int Number; for(Number=2;Number <=100;Number++) { int x=0; for(int i=2; i <=Number-1;i++) { if(Number%i==0) x=x+1; } if(x>0) { System.out.println(Number + "\tThe number is not prime"); } else { System.out.println(Number + "\tThe number is Prime"); } } }
No comments:
Post a Comment