[Go to site: main page, start]

0% found this document useful (0 votes)
7 views3 pages

Java Basics: OOP and Programming Concepts

Its good begginer codes for Java

Uploaded by

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

Java Basics: OOP and Programming Concepts

Its good begginer codes for Java

Uploaded by

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

/**

* Java Programming Notes: Fundamentals and OOP Basics


* Compiled for Copy-Paste Use
*/

// 1. Basic Structure (The Hello World Program)


public class HelloWorld {
// The main method is the entry point of the application
public static void main(String[] args) {
// [Link] is used for output
[Link]("Hello, Java World!");
}
}

// 2. Variables and Primitive Data Types


public class DataTypes {
public static void main(String[] args) {
// Primitives (Value Types)
int wholeNumber = 100; // 32-bit integer
double decimalNumber = 10.5; // 64-bit floating point
char singleCharacter = 'A'; // 16-bit Unicode character
boolean isTrue = true; // Boolean (true/false)

// Non-Primitive (Reference Types)


String text = "This is a string."; // String is an immutable class

// Final keyword makes a variable a constant


final int MAX_VALUE = 500;
// MAX_VALUE = 501; // This would cause a compile-time error

[Link]("Integer: " + wholeNumber);


}
}

// 3. Type Casting (Converting between types)


public class Casting {
public static void main(String[] args) {
// Widening Casting (Automatic: smaller to larger type)
int myInt = 9;
double myDouble = myInt; // myDouble is now 9.0

// Narrowing Casting (Manual: larger to smaller type)


double myOtherDouble = 9.78;
int myOtherInt = (int) myOtherDouble; // myOtherInt is now 9 (data loss)

[Link](myOtherInt);
}
}

// 4. Control Flow: If/Else and Switch


public class ControlFlow {
public static void main(String[] args) {
int x = 20;

// If-Else-If Structure
if (x > 30) {
[Link]("X is greater than 30.");
} else if (x > 10) {
[Link]("X is greater than 10 but not 30."); // This runs
} else {
[Link]("X is 10 or less.");
}

// Switch Statement (Useful for selecting one of many possibilities)


int day = 3;
String dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 3:
dayName = "Wednesday"; // This runs
break;
default:
dayName = "Another day";
break;
}
[Link]("Day: " + dayName);
}
}

// 5. Loops: For, While, Do-While


public class Loops {
public static void main(String[] args) {
// For Loop (Initialisation; Condition; Update)
for (int i = 0; i < 3; i++) {
[Link]("For Loop Count: " + i); // 0, 1, 2
}

// While Loop (Executes while the condition is true)


int j = 0;
while (j < 3) {
[Link]("While Loop Count: " + j);
j++;
}

// Do-While Loop (Executes the body at least once)


int k = 0;
do {
[Link]("Do-While Count: " + k);
k++;
} while (k < 1); // Only runs once

// Break and Continue


for (int l = 0; l < 5; l++) {
if (l == 2) {
continue; // Skips to the next iteration (2 is skipped)
}
if (l == 4) {
break; // Exits the loop entirely
}
[Link]("Loop l: " + l); // 0, 1, 3
}
}
}

// 6. Methods (Functions)
public class Calculator {
// Static method: Belongs to the class, not an instance
public static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


int result = add(5, 7);
[Link]("Sum: " + result);
}
}

// 7. Object-Oriented Programming (OOP) - Classes and Objects


class Dog {
// Attributes (Variables)
String breed;
String name;
int age;

// Constructor (A special method to initialize objects)


public Dog(String breed, String name, int age) {
[Link] = breed; // 'this' refers to the current object instance
[Link] = name;
[Link] = age;
}

// Method (Functionality)
public void bark() {
[Link](name + " says Woof!");
}
}

public class OOPExample {


public static void main(String[] args) {
// Creating an Object (Instantiating the class)
Dog myDog = new Dog("Labrador", "Buddy", 5);

// Accessing attributes and methods


[Link]("Dog's Breed: " + [Link]);
[Link]();
}
}

Common questions

Powered by AI

Methods that return values are used when a certain computation or operation needs to provide feedback to the main program flow, such as retrieving a calculated value. Non-void methods explicitly return a value of declared data type using the return statement inside the method, like the add method returning an int. Void methods, which do not return a value, are used when the task completes within the method's scope itself or for operations that inherently contribute side effects, such as updating a user interface. The decision on method type depends on whether the result of an operation needs to be reused or transferred back to the caller .

The final keyword in Java is used to declare constants. A variable declared as final cannot be reassigned once it has been initialized. This means its value is constant throughout the program. Attempting to change the value of a final variable later causes a compile-time error, thereby preventing accidental modification and enhancing program stability .

Widening type casting in Java automatically converts a smaller type into a larger type (e.g., int to double), and no data is lost as the conversion is straightforward. For example, converting an int value of 9 to double results in 9.0. Narrowing type casting is a manual way to convert a larger type to a smaller type (e.g., double to int) and might involve data loss, as seen when converting 9.78 to an int results in 9 because the decimal part is truncated .

Using classes in Java to model real-world entities allows encapsulation of data and behavior, fostering code organization and reusability. Real-world entities are represented by classes where attributes (fields) and behaviors (methods) are logically grouped. Encapsulation hides the internal state and requires all interaction to occur through publicly exposed methods, which promotes modularity, reduces dependencies, and enhances maintainability. For example, a Dog class encapsulates attributes like breed and name and behaviors like bark(), aligning with the principles of Object-Oriented Programming .

In Java, the 'break' statement is used to completely exit a loop, terminating its execution. It is typically used when a certain condition is met, and no further iterations are needed. On the other hand, 'continue' skips the current iteration and moves to the next iteration in the loop, useful for cases where, under certain conditions, the remaining code in that iteration should not be executed. For example, within a for loop counting from 0 to 5, 'break' would stop the loop entirely at a specified condition, while 'continue' might skip printing a particular number if it meets a condition .

In Java, the static keyword indicates that a method belongs to the class rather than any instance of the class. Static methods can be called without creating an instance of the class. They are typically used when a method is not dependent on instance variables or needs to be used frequently across different parts of a program, such as utility or helper methods. For example, math operations that do not rely on instance data might be defined as static, like the add(int a, int b) method in a Calculator class .

Creating an object in Java involves instantiating a class using the new keyword, which calls the class's constructor. For example, using the Dog class: Dog myDog = new Dog("Labrador", "Buddy", 5); initializes the attributes breed, name, and age through the constructor. The 'this' keyword differentiates instance variables from parameters. Attributes can be accessed using the dot operator, such as myDog.breed, and methods can be invoked similarly, for example, myDog.bark().

Switch statements are preferable over if-else statements when you need to select one among many possible options, especially when dealing with a single expression that matches against a list of possible constants. They enhance readability when there are multiple conditions based on the same variable and can be more efficient in execution since modern compilers optimize them better. If-else statements are more suitable when evaluating complex, non-constant expressions or conditions that do not directly relate to a single variable's value .

Do-while loops execute the code block at least once, regardless of the condition, because the condition is evaluated after the execution of the block. This is useful when you want to ensure that the loop body executes at least once before checking a condition. For loops are more suitable when the number of iterations is known beforehand and involve initialization, condition checking, and updating the loop variable in a single line, which enhances readability. However, do-while lacks this structured initialization and update mechanism and can be less intuitive in terms of knowing when the loop will terminate .

Primitive data types in Java (such as int, double, char, and boolean) are basic types that store the actual value directly in memory, and are defined by the language itself. They are not objects and are immutable, meaning their values cannot be changed once set. Non-primitive data types (like Strings, Arrays, and Classes) are objects that hold references to data, not the data itself. These types are defined by the programmer and reside on the heap. While String is an immutable non-primitive data type, most other objects can have mutable data .

You might also like