An Introduction to Java – Part I, language basics By: Mihir Shah
Overview Basic Structrue Source code, Compilation, Execution Data Types, Operators, Strings Variables If statements, Loops Arrays
Basic Structure The basic structure of Java programs: public class ClassName { public static void main(String[] args) { program statements } User defined methods Explanations: Public classes are accessible from any class. Classes, which are not declared public are accessible only within their package Public methods may be called from any class. Static methods do not operate on objects. The keyword void indicates that the method does not return a value. The array args of the main method stores command line arguments.
Source code, Compilation, Execution Source code should be same name as the public class File must be saved with the extension .java Ex. Public class TestFile File name: TestFile.java To run the command type java then the file name Ex. Java TestFile
Data Types, Operators, Strings Integers: int, short, long, byte Floating-Point Types: float, double The Character Type: char The Boolean Type: boolean (values: true, false) Operators Arithmetic Operators: +, -, *, /, % Relational Operators: ==, !=, <, >, <=, >= Logical Operators: &&, ||, ! Strings Enclosed in “” Concatenate with + Int Length();
Variables Need to be declared Ex: Int n = 5; System.out.println(n); Output: 5 String s = “Hello”; String t = “World”; System.out.println(s+“ ”+t); Output: Hello World
If statements, Loops If statements While loop For Loops if(…) { … } else { … } While loop while(….) { … } For Loops for(initialization; condition; update) { … }
Arrays Standard class in java Defined by specifying the array type followed by [] Create objects with operator new Array count is from 0 to length-1 arrayName.length Examples int n = 5; int[] numbers = new int[n]; for(int i=0; i<numbers.length; i++) numbers[i]=n-i; for(int i=0; i<numbers.length; i++) system.out.println(numbers[i]);