0% found this document useful (0 votes)
5 views7 pages

Java Basics and Quick Reference Guide

The document provides an overview of basic Java programming concepts including data types, loops, arrays, conditionals, and user input. It includes code examples demonstrating how to declare variables, use loops, perform type casting, and handle string comparisons. Additionally, it covers the use of conditional statements and various array manipulations.

Uploaded by

yaminsheikh711
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

Java Basics and Quick Reference Guide

The document provides an overview of basic Java programming concepts including data types, loops, arrays, conditionals, and user input. It includes code examples demonstrating how to declare variables, use loops, perform type casting, and handle string comparisons. Additionally, it covers the use of conditional statements and various array manipulations.

Uploaded by

yaminsheikh711
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

public class Hello {

// main method

public static void main(String[] args)

// Output: Hello, world!

[Link]("Hello, world!");

Varriables
int num = 5;

float floatNum = 5.99f;

char letter = 'D';

boolean bool = true;

String site = "[Link]";

loops

String word = "QuickRef";

for (char c: [Link]()) {

[Link](c + "-");

// Outputs: Q-u-i-c-k-R-e-f-

arrays

char[] chars = new char[10];

chars[0] = 'a'

chars[1] = 'b'

String[] letters = {"A", "B", "C"};

int[] mylist = {100, 200};

boolean[] answers = {true, false};


swap

int a = 1;

int b = 2;

[Link](a + " " + b); // 1 2

int temp = a;

a = b;

b = temp;

[Link](a + " " + b); // 2 1

Type casting

int i = 10;

long l = i; // 10

// Narrowing

double d = 10.02;

long l = (long)d; // 10

[Link](10); // "10"

[Link]("10"); // 10

[Link]("10"); // 10.0

conditional

int j = 10;

if (j == 10) {

[Link]("I get printed");

} else if (j > 10) {

[Link]("I don't");

} else {

[Link]("I also don't");

}
User input

Scanner in = new Scanner([Link]);

String str = [Link]();

[Link](str);

int num = [Link]();

[Link](num);

String basic

String str1 = "value";

String str2 = new String("value");

String str3 = [Link](123);

Concetenation

String s = 3 + "str" + 3; // 3str3

String s = 3 + 3 + "str"; // 6str

String s = "3" + 3 + "str"; // 33str

String s = "3" + "3" + "23"; // 3323

String s = "" + 3 + 3 + "23"; // 3323

String s = 3 + 3 + 23; // 29

Comparision

String s1 = new String("QuickRef");

String s2 = new String("QuickRef");

s1 == s2 // false

[Link](s2) // true

"AB".equalsIgnoreCase("ab") // true
Immutable

String str = "hello";

[Link]("world");

// Outputs: hello

[Link](str);

Java arrays

Declare

int[] a1;

int[] a2 = {1, 2, 3};

int[] a3 = new int[]{1, 2, 3};

int[] a4 = new int[3];

a4[0] = 1;

a4[2] = 2;

a4[3] = 3;

modify

int[] a = {1, 2, 3};

[Link](a[0]); // 1

a[0] = 9;

[Link](a[0]); // 9

[Link]([Link]); // 3
Loop read and Modify

int[] arr = {1, 2, 3};

for (int i=0; i < [Link]; i++) {

arr[i] = arr[i] * 2;

[Link](arr[i] + " ");

// Outputs: 2 4 6

Loop read

String[] arr = {"a", "b", "c"};

for (int a: arr) {

[Link](a + " ");

// Outputs: a b c

Multidimentional array

int[][] matrix = { {1, 2, 3}, {4, 5} };

int x = matrix[1][0]; // 4

// [[1, 2, 3], [4, 5]]

[Link](matrix)

for (int i = 0; i < [Link]; ++i) {

for(int j = 0; j < a[i].length; ++j) {

[Link](a[i][j]);

// Outputs: 1 2 3 4 5 6 7
Java Conditional

If else

int k = 15;

if (k > 20) {

[Link](1);

} else if (k > 10) {

[Link](2);

} else {

[Link](3);

Switch

int month = 3;

String str;

switch (month) {

case 1:

str = "January";

break;

case 2:

str = "February";

break;

case 3:

str = "March";

break;

default:

str = "Some other month";

break;

// Outputs: Result March

[Link]("Result " + str);


Java loops

for (int i = 0; i < 10; i++) {

[Link](i);

// Outputs: 0123456789

int[] numbers = {1,2,3,4,5};

for (int number: numbers) {

[Link](number);

// Outputs: 12345

While loop

int count = 0;

while (count < 5) {

[Link](count);

count++;

// Outputs: 01234

Continue

for (int i = 0; i < 5; i++) {

if (i == 3) {

continue;

[Link](i);

// Outputs: 01245

Common questions

Powered by AI

Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. For example, calling concat() on a string creates a new string without modifying the original one: `String str = "hello"; str.concat("world");` results in the original `str` remaining "hello" . Unlike strings, mutable objects like arrays can have their values altered after creation, e.g., `int[] a = {1, 2, 3}; a[0] = 9;` changes the first element to 9 .

Arrays can be declared using array literals, which initializes the array with predefined values, e.g., `int[] a = {1, 2, 3};` and using the new keyword with explicit size or predefined values, e.g., `int[] a = new int[]{1, 2, 3};` or `int[] a = new int[3];` where elements can be assigned later . Using literals is more concise and preferred when initial values are known.

A for-each loop simplifies iteration over arrays, enhancing readability by abstracting loop counters and index handling. It eliminates index-out-of-bounds errors since it automatically iterates over all elements. For instance, `for (int number: numbers) { System.out.print(number); }` automatically covers each element without manual index management, unlike a traditional loop that requires managing counters explicitly .

When the input month is 3 in a switch statement, it outputs "March": `switch (month) { case 3: str = "March"; break; }` . If no case matches the input, the default case executes, e.g., `default: str = "Some other month";` ensures some output regardless of input .

The continue statement skips the current iteration, jumping to the loop's next iteration start. It's effective for bypassing specific conditions without exiting the loop. For example, in `for (int i = 0; i < 5; i++) { if (i == 3) { continue; } }` the iteration for `i == 3` is skipped, maintaining control flow and aiding in cleaner code by avoiding additional boolean checks .

Swapping variables in Java with a temporary variable, e.g., `int temp = a; a = b; b = temp;`, ensures that data isn't lost through overwriting in the swap process. This method sequentially transfers values, preventing any intermediate loss typical in techniques like adding and subtracting values, which might result in overflow or require explicit type casting .

The == operator checks if two string references point to the same object in memory, whereas the equals() method compares the actual content of the strings. For instance, `String s1 = new String("QuickRef"); String s2 = new String("QuickRef");` results in `s1 == s2` being false, as they are different objects, but `s1.equals(s2)` is true, as they contain the same characters .

Java performs implicit widening conversions when necessary, promoting smaller types to larger compatible data types during expressions. For instance, in expressions involving int and double, Java implicitly casts int to double to avoid data loss, as in `int i = 5; double d = i + 2.0;` . Such widening conversions ensure that operations are performed on the most suitable data type to maintain precision and avoid errors.

Java handles console input using the `Scanner` class. For string input, it uses `in.nextLine()` and for integer input `in.nextInt()`. For example, `Scanner in = new Scanner(System.in); String str = in.nextLine(); int num = in.nextInt();` reads a string and an integer from the console, then prints them respectively .

Widening casting, such as converting an int to a long (`int i = 10; long l = i;`), automatically converts a smaller data type to a larger one without data loss . Narrowing casting explicitly converts a larger data type to a smaller one, which might lead to data loss, e.g., converting a double to a long (`double d = 10.02; long l = (long)d;`) results in truncating the decimal part .

You might also like