Java basics By Mahesh Sarangapani

Views:
 
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Java: 

Java Write Once, Run Anywhere Mahesh Sarangapani +91-7204408752 maheshsthattil2007@gmail.com

Java Architecture: 

Java Architecture After you write a Java program, you use a compiler that reads the statements in the program and translates them into a machine independent format called bytecode. Bytecode files, which are very compact, are easily transported through a distributed system like the Internet. The compiled Java code (resulting byte code) will be executed at run time.

Java source code: 

Java source code public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }//End of main }//End of HelloWorld Class

Java Main method Declarations : 

Java Main method Declarations class MainExample1 {public static void main(String[] args) {}} class MainExample2 {public static void main(String []args) {}} class MainExample3 {public static void main(String args[]) {}} All the 3 valid main method’s shown above accepts a single String array argument

Compiling and Running an Application: 

Compiling and Running an Application Steps for Saving, compiling and Running a Java Step 1:Save the program With .java Extension. Step 2:Compile the file from DOS prompt by typing javac <filename>. Step 3:Successful Compilation, results in creation of .class containing byte code Step 4:Execute the file by typing java <filename without extension>

Basic Language Elements: 

Basic Language Elements Identifiers Keywords Literals white spaces comments

Keywords: 

Keywords There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case. Keywords are reserved words that are predefined in the language

Examples for Keywords: 

Examples for Keywords

Comments: 

Comments Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program. Java supports three comment styles. Block style comments begin with /* and terminate with */ that spans multiple lines. Line style comments begin with // and terminate at the end of the line. (Shown in the above program) Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc.

Variable, Identifiers and Data Types: 

Variable, Identifiers and Data Types Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers . An Identifier must be unique within a scope of the Java program. Variables have a data type , that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.

Sample Program: 

Sample Program public class localVariableEx { public static int a; public static void main(String[] args) { int b; System.out.println("a : "+a); System.out.println("b : "+b);//Compile error } }

data types : 

data types Java has four main primitive data types built into the language. We can also create our own data types. Integer: byte, short, int, and long. Floating Point: float and double Character: char Boolean: variable with a value of true or false.

Rules: 

Rules When we declare a variable we assign it an identifier and a data type. For Example String message = “hello world” Identifier Naming Rules Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character. Must begin with a letter, dollar sign, or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope, each user defined item must have a unique identifier Can be of any length.

Java Operators : 

Java Operators Java operators fall into eight different categories: Assignment Arithmetic Relational Logical Bitwise compound assignment Conditional type .

Operators: 

Operators

Conditional operators: 

Conditional operators The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement.

Example: 

Example

Operator Precedence: 

Operator Precedence

Java Control Flow Statements: 

Java Control Flow Statements Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements; Selection statements: if, if-else and switch. Loop statements: while, do-while and for. Transfer statements: break, continue, return, try-catch-finally etc.

Selection Statements - If: 

Selection Statements - If

If - Else: 

If - Else

Switch: 

Switch public class MainClass { public static void main(String[] args) { int choice = 2; switch (choice) { case 1: System.out.println("Choice 1 selected"); break ; case 2: System.out.println("Choice 2 selected"); break ; case 3: System.out.println("Choice 3 selected"); break ; default : System.out.println("Default"); break ; } } }

Iteration Statements - While: 

Iteration Statements - While

Do-while Loop Statement : 

Do-while Loop Statement

For Loops : 

For Loops

Transfer Statements - Continue: 

Transfer Statements - Continue

Break: 

Break

Java Access Specifiers: 

Java Access Specifiers Access Modifiers 1. private 2. protected 3. default 4. public

Public: 

Public Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

Private: 

Private The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class.

Protected: 

Protected The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Java Classes and Objects: 

Java Classes and Objects A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.

Class - Example: 

Class - Example

Final Variable, Methods and Classes: 

Final Variable, Methods and Classes In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed. Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Method Overloading: 

Method Overloading Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist.

Slide 36: 

public class MethodOverloadDemo { void sum() { // First Version System.out.println("No parameters"); } void sum(int a) { // Second Version System.out.println("One parameter: " + a); } int sum(int a, int b) { // Third Version System.out.println("Two parameters: " + a + " , " + b); return a + b; } double sum( double a, double b) { // Fourth Version System.out.println("Two double parameters: " + a + " , " + b); return a + b; } public static void main(String args[]) { MethodOverloadDemo moDemo = new MethodOverloadDemo(); int intResult; double doubleResult; moDemo.sum(); System.out.println(); moDemo.sum(2); System.out.println(); intResult = moDemo.sum(10, 20); System.out.println("Sum is " + intResult); System.out.println(); doubleResult = moDemo.sum(1.1, 2.2); System.out.println("Sum is " + doubleResult); System.out.println(); } }

Method Overriding: 

Method Overriding class A { int i, j; A( int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B( int a, int b, int c) { super (a, b); k = c; } void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } }

Java Constructors: 

Java Constructors A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value. Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition. Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

Thank You: 

Thank You Mahesh Sarangapani +91-7204408752 maheshsthattil2007@gmail.com