BASIC JAVA
Hello World
n // Hello world program public class MyFirstJavaProgram { public static void main(String args[]) { char c = 'H'; String s = c + "ello \nWorl"; int last = 'd'; s = s + (char)last; System.out.println(s); } }
Java Comments n // for the java one liner n /* for a multi-line n comment */ n /** for a javadoc comment n */
Simple output n System.out.println(“Hello World”); n System.out.print(“No new line”); n System.out.print(6); n System.out.print(true); n System.out.println(6+10); displays 16 n System.out.println(“”+6+10); displays 610
Primitive Types n byte there are no byte literals 8 bits n short there are no short literals 16 bits n int literals(23, -98, 077, 0xAF) 32 bits n long lierals(23L, -9L) 64 bits n float literals (34F, -4.5f) 32 bits n double literals (34.0, 5e2,.4) 64 bits n char literals (‘A’, ‘\n’, ‘\377’, ‘\u0041’) 16 bits unsigned n boolean literals (true, false) 16 bits
Assignment and types n short m = 5; // int to short is ok if it fits n short m = ; // compiler error int to short not ok n float m = 50.0; // compiler error need to cast double to float n float m = (float)50.0; // ok cast the double to float n byte b = 4L; // compiler error cast to byte
More on Assignment and types n double m = 6; // int to double is fine n int m = 6.0; // compiler error need to cast the double to int n int m = (int)6.0; // works fine n double c = ‘\n’; // ok but strange n char c = ‘A’ + 1; // c now holds ‘B’ n System.out.println(‘A’ + 1); // displays 66 n System.out.println((char)(‘A’ + 1)); // displays B
The String Type n String s = "Peanut"; // or, see below n String s = new String(“Peanut”); // same as above n Use concatenation for long strings n System.out.println("This is " + "a very long string"); n Many string operations exist n System.out.println(s.length()); n System.out.println("Hello".length());