510 likes | 1.08k Views
Java Language Basics. Shawn Mandik. Program Structure. Basic structure: public class ClassName { public static void main(String[] args) { program statements } user defined methods }. Class Notes. “public” classes and methods can be called from any class
E N D
Java Language Basics Shawn Mandik
Program Structure Basic structure: public class ClassName { public static void main(String[] args) { program statements } user defined methods }
Class Notes • “public” classes and methods can be called from any class • Static methods incompatible with objects • Array “arg” of main method holds command line arguments
File Notes • Filename must be the same as the single public class • example: file containing public class ThisClass should be named ThisClass.java • Compiled file will be given extension “.class”
Variable Types • Similar to C++ • Examples: int, long, char, float • New data types: boolean (either true or false) byte (similar to int, but only 8-bit – saves memory)
String Handling • Strings are a standard class in Java • Concatenation performed with “+” Example: • String s=”Hello”; • String t=”world”; • System.out.println(s+” “+t);
Useful String Functions • int compareTo(String other) Returns negative or positive if strings are unequal, 0 if equal • boolean equals(Object other) Returns true if implicit and explicit arguments are equal • int length() Returns length of the string
Loops/Conditional • Same as C++ • if(argument) { ... } • while(argument) { … } • for(argument) { … }
Arrays • Arrays are also a standard class Syntax example: int[] numbers = new int[n]; for(int i=0; i<numbers.length; i++) numbers[i]=i;
Useful Array Functions • static void sort(type[] a) Runs quicksort algorithm on array a • static int binarySearch(type[] a, type v) Runs binary search on array a to find v • static boolean equals(type[] a, Object other) Returns true if object other is an array equal to a