GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — Java Cheatsheet
Selected Reading
Java CheatsheetJava Program Structure// Package Declaration (Optional)
// Example: package mypackage;
// Import Statements (Optional)
// Example: import java.util.Scanner;
// Class Declaration
public class Class_name{
// Main Method
public static void main(String[] args) { }
}
Printing Hello WorldThe following code prints Hello World on the console − public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
public static void mainThe main() method is the starting point where JVM (Java Virtual Machine) begins executing the Java program. public static void main(String[] args) Output - System.out.println()We can use System.out.println() to print something to the output console in Java. public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
The println() methodThe println() method is used to print text in Java. A new line will be added after each call. System.out.println("Hello World");
Double QuotesIn Java, double quotes are used to define string literals. System.out.println("If you forget the double quotes, a compilation error will occur");
The Print() MethodThe println() method is used to print text in Java. A new line will be added after each call. System.out.print("Hello World");
User InputIn Java, we use the Scanner class to get input from the user. It is in the java.util package. import java.util.Scanner;
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
Java CommentsJava comments are two types: single-line and multi-line comments. Single Line commentSingle-line comments in Java start with double forward slashes // and text between them are ignored by the Java compiler. // This is a comment
System.out.println("Hello World");
Multi-line CommentsMulti-line comments in Java start with /* and end with */ and text between is ignored by the Java compiler. Access Modifiers in JavaIn Java, access modifiers are keywords used to set the accessibility of classes, methods, constructors, and fields. Types of Access Modifiers
VariablesJava Variables are containers that hold data values, with each variable being defined according to its assigned data type. Types of Variables
Built-in Type VariablesThe eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char. bytebyte is a primitive data type that only takes up 8 bits of memory. It can store numbers from -128 to 127. longLong is another primitive data type related to integers that can store whole numbers from -9223372036854775808 to 9223372036854775808. long takes up 64 bits of memory. floatThe float keyword is a data type that can store fractional numbers from 3.4e038 to 3.4e+038. charChar is a 16-bit integer representing a Unicode-encoded character. intThe int keyword is a primitive data type that can store numbers from -2147483648 to 2147483647. shortThe short keyword is a data type that can store numbers from -32768 to 32767. Control FlowIf-Else StatementIn Java, an if-else statement executes a block of code based on a condition. if (x > 0) {
// code block }
else {
// code block }
Switch StatementThe switch statement selects one of many code blocks to be executed. It is similar to the if-else-if ladder statement. switch (day) {
case 1:
// code block
break;
case 2:
// code block
break;
default:
// code block
}
For LoopThe Java for loop is used to iterate a block of code a specified number of times. for (int i = 0; i < 10; i++) {
// code block
}
While LoopThe Java while loop is used to iterate a block of code while a condition is true. while (x < 10) {
// code block
}
Break StatementThe Java break statement is used to terminate the current flow of the program at specified conditions. public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
//Using Break Statement
break;
}
System.out.println(i);
}
}
}
Continue StatementThe Java continue statement is used to continue the current flow of the program. It is used to jump to the next part of the program. public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
continue;//it will jump to the next statement
}
System.out.println(i);
}
}
}
Java OOP Concepts1. Classes and Objects
2. InheritanceInheritance allows a class to inherit fields and methods from another class. Example class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat says meow!");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.eat(); // Output: This animal eats food.
cat.meow(); // Output: Cat says meow!
}
}
3. PolymorphismPolymorphism allows methods to do different things based on the object it is acting upon. Example class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}
4. EncapsulationEncapsulation is the technique of wrapping data (variables) and code (methods) together as a single unit. Example class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(100.0);
System.out.println("Balance: " + account.getBalance()); // Output: Balance: 100.0
}
}
5. AbstractionAbstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. Example abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw(); // Output: Drawing a circle
rectangle.draw(); // Output: Drawing a rectangle
}
}
ConstructorsIn Java, a constructor is a code block that initializes a new class instance. It is called when an object is created, allocating memory for it. Types of Constructors
ArraysArrays are data structures that store multiple values of the same data type in contiguous memory locations. Single-Dimensional Arraysint arr[] = new int[20]; int[] arr = new int[20]; Example public class SingleDimensional {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (int i = 0; i < arr.length; i++) {
System.out.println("arr[" + i + "] : " + arr[i]);
}
}
}
Multi-Dimensional ArraysArrays can also be multi-dimensional, allowing the storage of data in a matrix format. int[][] arr = new int[3][3]; int arr[][] = new int[3][3]; Here is a Java program to implement 2-Dimensional arrays − public class MultiDimensional {
public static void main(String args[]) {
int arr[][] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
StringsJava strings represent a sequence of characters. String Methods
String ConcatenationString concatenation is the process of combining two or more strings into a single string. The + Operator String str1 = "Hello, "; String str2 = "world!"; String result = str1 + str2; The concat() Method String str1 = "Hello, "; String str2 = "world!"; String result = str1.concat(str2); String ComparisonWhen comparing strings in Java, you need to be aware of the difference between comparing string references and string content. Using equals() Method String str1 = "Hello"; String str2 = "Hello"; boolean areEqual = str1.equals(str2); Using == Operator String str1 = new String("Hello");
String str2 = new String("Hello");
boolean areSameReference = (str1 == str2);
Using compareTo() Method String str1 = "apple"; String str2 = "banana"; int comparisonResult = str1.compareTo(str2); Exception HandlingJava exception handling is a process to handle runtime errors to maintain the flow of the program. Java try-catch blockThe Try-catch block is used to handle the code that may throw the exception. Syntax try {
// code that may throw an exception
} catch (Exception e) {
// code to handle the exception
}
Java finally blockThe finally block is used to execute the specific code whether the exception is handled or not. Example public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block.");
int result = 10 / 0; // This will cause an exception
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
Java throw ExceptionThe Java throw keyword is used to throw an exception explicitly. Syntax throw new exception_class("error statement ");
Example public class ThrowExample {
public static void main(String[] args) {
try {
checkAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
}
Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |