Introduction to Java Programming

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is Java?

Java is a programming language created in 1995 and owned by Oracle. It runs on many devices and is used for mobile apps, desktop apps, web apps, servers, and databases.

Java is case-insensitive.

False (B)

What is the main method in Java?

The main method is the entry point of a Java program.

Which of the following are examples of Java primitive data types?

<p>double (A), int (B)</p> Signup and view all the answers

What is object instantiation?

<p>Object instantiation is the creation of an object using the <code>new</code> keyword.</p> Signup and view all the answers

What is type casting in Java?

<p>Type casting is converting one data type to another. It can be widening (implicit) or narrowing (explicit).</p> Signup and view all the answers

What is the difference between widening and narrowing type casting?

<p>Widening casting is implicit and converts smaller data types to larger ones, while narrowing casting is explicit and converts larger data types to smaller ones, potentially losing precision. (A)</p> Signup and view all the answers

The ____ statement executes a block of code if a condition is true.

<p>if</p> Signup and view all the answers

What is the purpose of a switch statement?

<p>A <code>switch</code> statement selects one of many code blocks to execute based on the value of an expression.</p> Signup and view all the answers

The break statement is not important to exit the switch block after a match.

<p>False (B)</p> Signup and view all the answers

Describe the purpose of a for loop.

<p>A <code>for</code> loop is used when the number of iterations is known.</p> Signup and view all the answers

What is a while loop used for?

<p>A <code>while</code> loop continues as long as a condition is true.</p> Signup and view all the answers

What is the difference between a while loop and a do-while loop?

<p>A <code>do-while</code> loop executes at least once, then checks the condition, while a <code>while</code> loop checks the condition before executing.</p> Signup and view all the answers

What does the break statement do in a loop?

<p>The <code>break</code> statement terminates the loop prematurely.</p> Signup and view all the answers

What is the function of the continue statement in a loop?

<p>The <code>continue</code> statement skips the rest of the loop body for the current iteration.</p> Signup and view all the answers

Describe the use of an enhanced for loop (for-each loop).

<p>An enhanced <code>for</code> loop simplifies iteration over arrays and collections.</p> Signup and view all the answers

What are arrays used for?

<p>Arrays are used to store multiple values of the same data type in a single variable.</p> Signup and view all the answers

What is a single-dimensional array?

<p>A single-dimensional array is a linear array of elements.</p> Signup and view all the answers

What is a multi-dimensional array?

<p>A multi-dimensional array is an array of arrays, often used for matrices or tables.</p> Signup and view all the answers

What is a Java method?

<p>A Java method is a block of code that runs only when it is called. Methods are used to perform certain actions and are also known as functions.</p> Signup and view all the answers

The void keyword indicates that the method returns a value.

<p>False (B)</p> Signup and view all the answers

What is a parameter in a Java method?

<p>A parameter is a variable declared in a method's definition and acts as a placeholder for values passed into the method.</p> Signup and view all the answers

What are arguments in a Java method?

<p>Arguments are the actual values passed to a method when it is called.</p> Signup and view all the answers

What is Object-Oriented Programming (OOP)?

<p>Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating objects that interact with each other using classes and objects.</p> Signup and view all the answers

What is a class in OOP?

<p>A class is a blueprint for creating objects. It defines the attributes (variables) and behavior (methods) of an object.</p> Signup and view all the answers

What is an object in OOP?

<p>An object is an instance of a class. It is created from a class and has its own attributes and methods.</p> Signup and view all the answers

What is inheritance in OOP?

<p>Inheritance is one of the fundamental principles of OOP, allowing a subclass (child) to inherit properties and behavior from a superclass (parent).</p> Signup and view all the answers

What is polymorphism in OOP?

<p>Polymorphism is an important concept in OOP that means 'more than one form,' where the same entity can perform different operations in different scenarios.</p> Signup and view all the answers

What is abstraction in OOP?

<p>Abstraction is a process of hiding the implementation details from the user, only providing the functionality.</p> Signup and view all the answers

What is encapsulation in OOP?

<p>Encapsulation is a fundamental OOP principle that combines data and methods in a class, hiding the internal details and providing controlled access through methods.</p> Signup and view all the answers

Which of the following are key features of encapsulation?

<p>All of the above (D)</p> Signup and view all the answers

Which of the following are examples of data structures for storing elements?

<p>Both LinkedList and ArrayList (C)</p> Signup and view all the answers

ArrayList uses a doubly linked list to store elements?

<p>False (B)</p> Signup and view all the answers

LinkedList provides Random Access with O(1) time complexity to access elements using index?

<p>False (B)</p> Signup and view all the answers

Flashcards

What is Java?

A programming language created in 1995, used for mobile, desktop, and web applications.

Java Case Sensitivity

Java distinguishes between uppercase and lowercase characters.

Class Declaration

A Java program starts with a class definition.

Main Method

The entry point of a Java program.

Signup and view all the flashcards

Comments in Java

Explanatory notes in code, not executed by the compiler.

Signup and view all the flashcards

Variables

Storage locations with a data type and identifier.

Signup and view all the flashcards

Primitive Data Types

int, double, boolean, etc.

Signup and view all the flashcards

Reference Data Types

String, custom classes.

Signup and view all the flashcards

Control Flow

Control the order of execution (if, else, for, while, switch).

Signup and view all the flashcards

Object Instantiation

Creating an object from a class using 'new'.

Signup and view all the flashcards

Methods

Declared in classes; may return values.

Signup and view all the flashcards

Packages

Organize code and import classes.

Signup and view all the flashcards

Exception Handling

try, catch, finally, throw

Signup and view all the flashcards

Integral Types

byte, short, int, long

Signup and view all the flashcards

Character Types

char, String.

Signup and view all the flashcards

Boolean Type

boolean

Signup and view all the flashcards

Floating-Point Types

float, double

Signup and view all the flashcards

Widening (Implicit) Casting

Automatically converts smaller data types to larger ones

Signup and view all the flashcards

Narrowing (Explicit) Casting

Converts larger data types to smaller ones, requires explicit casting, may lose precision

Signup and view all the flashcards

If-Else Statement

Executes a block of code if a condition is true (can include an optional else block)

Signup and view all the flashcards

Switch Statement

Selects one of many code blocks to execute based on the value of an expression

Signup and view all the flashcards

For Loop

Used when the number of iterations is known

Signup and view all the flashcards

While Loop

Continues to execute as long as a condition is true.

Signup and view all the flashcards

Do-While Loop

Executes a block of code at least once, then checks the condition to continue

Signup and view all the flashcards

Break Statement

Terminates the loop prematurely.

Signup and view all the flashcards

Continue Statement

Skips the rest of the loop body for the current iteration.

Signup and view all the flashcards

Enhanced For Loop (for-each)

Simplifies iteration over arrays and collections.

Signup and view all the flashcards

Arrays

Used to store multiple values of the same data type in a single variable. Fixed in size once initialized.

Signup and view all the flashcards

Single-Dimensional Array

An array with elements accessed using a single index.

Signup and view all the flashcards

Multi-Dimensional or 2D Array

An array that is an array of arrays, often used for matrices or tables.

Signup and view all the flashcards

Arrays Class

Java's utility class for performing common array operations.

Signup and view all the flashcards

Varargs

Using three dots (...) after the data type in a method parameter.

Signup and view all the flashcards

Java Method

A block of code that runs only when it's called.

Signup and view all the flashcards

Method Overloading

Allows multiple methods to have same name but different parameters.

Signup and view all the flashcards

Parameter

A variable declared in a method's definition.

Signup and view all the flashcards

Arguments

The actual values passed to a method when it is called.

Signup and view all the flashcards

Study Notes

Basic of Java

  • Java was created in 1995 and is owned by Oracle
  • Java runs on over 3 billion devices
  • Java is used for mobile apps (Android), desktop apps, web apps, servers, databases, etc

Java Syntax

  • Java is case-sensitive
  • A Java program begins by the definition of a class using class declaration
  • The keyword public makes the class accessible outside its package
  • The main method is the point where the program starts executing

Core Elements

  • Comments are single-line (//) or multi-line (/* */)
  • Variables hold data and needs to be declared with a type and an identifier
  • Data types can be primitive (int, double, boolean, etc.) or reference types (String, custom classes)
  • Control flow statements include if, else, for, while, switch
  • Object instantiation uses the new keyword
  • Methods are declared in classes and can return values
  • Packages organize code and import classes
  • Exception handling uses try, catch, finally, and throw statements

Data Types

  • Integral types include byte, short, int, and long
  • Characters are represented by char and String
  • Boolean type is boolean
  • Floating-point types are float and double

Type Casting

  • Widening (implicit) casting automatically converts smaller data types to larger ones (e.g., int to double)
  • Narrowing (explicit) casting converts larger data types to smaller ones, which may lead to loss of precision.

Control Flow Statements

  • If statement executes a block of code if a specified condition is true and can include an optional else block

Switch Statement

  • Switch statement executes one of many code blocks based on the value of an expression
  • If statements are more flexible for complex logical conditions
  • Switch statements are useful for single variables with multiple possible values
  • Switch requires constant values in cases (e.g., integers, characters, enums)
  • Break is important to exit the switch block after a match

Loops

  • For loop is used when the number of iterations is known
  • While loop continues as long as a condition is true
  • Do-while loop executes at least once, then checks the condition

Loop Control Statements

  • Break statement terminates a loop prematurely
  • Continue statement skips the rest of the loop body for the current iteration
  • Enhanced for loop simplifies iteration over arrays and collections

Arrays

  • Arrays store multiple values of the same data type in a single variable
  • Arrays are fixed in size once initialized
  • Single-dimensional array example: int[] numbers = {1, 2, 3, 4, 5};
  • Multi-dimensional array is an array of array and commonly used for matrices or tables

Accessing Elements

  • Access the first element in a single-dimensional array: numbers[0]
  • Access an element in a 2D array: matrix[1][2]

Length

  • Get the length of a single-dimensional array: numbers.length
  • Get the number of rows in a 2D array: matrix.length
  • Get the number of columns in a 2D array: matrix[0].length

Iterating Over Arrays

  • Display all elements of an array using a for loop:
    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
    
  • Display all elements using a for-each loop:
    for (int num : numbers) {
        System.out.println(num);
    }
    

Arrays Class

  • Java provides a utility class called Arrays for common array operations
  • Importing Arrays: import java.util.Arrays;

Sorting

  • Sort the array in ascending order: Arrays.sort(arr);

Notes on Arrays

  • Arrays have a fixed size after initialization
  • Array indices start at 0
  • Arrays can store primitives or objects
  • Multi-dimensional arrays are arrays of arrays

Varargs (Variable-Length Argument Lists)

  • Declared using three dots (...) after the data type
  • A method can have only one varargs parameter, which must be the last parameter in the method signature
  • Use varargs by passing zero or more arguments of the specified type, or an array of the specified type
  • Java internally treats varargs as an array

Syntax

  • void methodName(DataType... variableName) { // Method body }

Intro to Array

  • Arrays store multiple values in a single variable
  • An array is a collection of similar data elements in contiguous memory locations
  • Arrays have a fixed size sequential collection of elements of the same type
  • Can be referred to as a collection of variables of the same type

Types of Arrays

  • Single-dimensional array: a normal array with sequential elements, also known as a linear array where elements are stored in a single row or adjacent memory locations
  • Two-dimensional array: stores data in rows and columns
  • Multi-dimensional array: an array of arrays

Basic Operations on Arrays

  • Visit each element of the array at least once is array traversal
  • Add an element at a given index is insertion
  • Delete an element at a given index is deletion

Array Traversal

int[] arr = {2, 3, 5, 7, 11, 13, 17, 19};
for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
}

Array Insertion

int[] arr = new int[5];
arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; arr[4] = 5;
int pos = 3, x = 24;
for (int i = arr.length - 1; i >= pos - 1; i--) {
    arr[i + 1] = arr[i];
}
arr[pos - 1] = x;

Array Deletion

int[] arr = {1, 2, 3, 4, 5};
int[] arr_new = new int[arr.length - 1];
int j = 3;
for (int i = 0, k = 0; i < arr.length; i++) {
    if (i != j) {
        arr_new[k] = arr[i];
        k++;
    }
}
  • To look for an element using its value or index is searching

Search code

int search_ele = 15;
int[] arr = {10, 15, 20, 25, 30};
for (int i = 0; i < arr.length; i++) {
    if (arr[i] == search_ele) {
        System.out.println("Element Found");
        break;
    }
}

Update

  • update an element at a given index

Update code

int search_ele = 15;
int[] arr = {10, 15, 20, 25};
int x = 20;
for (int i = 0; i < arr.length; i++) {
    if (arr[i] == search_ele) {
        arr[i] = x;
        break;
    }
}

10 Array Methods

  • String[] aArray = new String[5]; declares an array
  • String[] bArray = {"a", "b", "c", "d", "e"}; declares an array
  • String[] cArray = new String[]{"a", "b", "c", "d", "e"}; declares an array
  • Print Arrays
int[] intArray = {1, 2, 3, 4, 5};
String intArrayString = Arrays.toString(intArray);
System.out.println(intArrayString); // [1, 2, 3, 4, 5]

Checking Arrays

String[] stringArray = {"a", "b", "c", "d", "e"};
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b); // true

Array Operations

  • Concatenate Two Arrays: int[] combinedIntArray = ArrayUtils.addAll(intArray1, intArray2);
  • Declare an Array Inline: method(new String[]{"a", "b", "c", "d", "e"});
  • Join Array Elements into a String:
String j = StringUtils.join(new String[]{"a", "b", "c"}, ", ");
System.out.println(j); // a, b, c
  • Create an ArrayList from an Array: ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(stringArray));
  • Convert ArrayList to Array
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
  • Convert Array to Set: Set<String> set = new HashSet<>(Arrays.asList(stringArray));
  • Reverse an Array
int[] intArray = {1, 2, 3, 4, 5};
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray)); // [5, 4, 3, 2, 1]

Key Array Notes

  • Arrays have a fixed size once initialized
  • Array indices start from 0
  • Arrays can store primitive data types or objects
  • Multi-dimensional arrays are arrays of arrays

Java Method

  • A method is a block of code that runs when called by name
  • Data passed into a method are parameters
  • Methods perform actions and are also known as functions
  • Methods allow to reuse code: write ones, use many times

Return Values

  • The void keyword states that the method will not return anything
  • For when a method should return a value, state a primitive data type and use the return keyword inside the method

Syntax guide

returnType methodName(parameterType1 parameterName1) {
    // method body
    // code to perform a specific task
    return returnValue; // optional, depending on the returnType
}
  • returnType: The returned type of value, else use void
  • methodName: The name of the method used to call it
  • parameterType: The data type the method accepts as input
  • parameterName: The name assigned to each input parameter
public static String sayHello(String name) {
    return "Hello, world! " + name;
}

Types of Methods

  • Instance methods belong to an instance of a class, and needs an object to be created
  • Return Type Methods return a value

Key Terms for Methods

  • VarArgs allows to accept a variable number of arguments
  • Method Overloading allows for methods to have the same name but differing parameters
  • Method Scope: Variables declared inside a method are accessible anywhere in the method after their declaration
  • Block Scope: Variables declared inside a block {} are only accessible within that block

Recursion

  • A method that calls itself to solve a problem
  • Used for repetitive processes

Parameter vs Argument

  • Parameters are placeholder variables declared in a method’s definition
  • Arguments are are the actual values that are passed to a new method
  • When the called method executes, the values replace their corresponding parameters

Introduction to Object Oriented Programming(OOP)

  • OOP is focusses on creating obects that interract with each other
  • OOP uses classes and objects to create real-world entities
  • OPP models entities using objects and classes

Key Terms

  • Encapsulation hides data
  • Inheritance inherets objects from annother class
  • Polymorphism has different multiple forms
  • Abstraction hids away unnessecary details and data

Why use OOP

  • Code Reusability: Write once, reuse multiple times.
  • Better Organization: Code is structured in logical components.
  • Data Security: Private data is protected using encapsulation.
  • Scalability: Makes it easier to manage and expand large programs.

Terminology

  • Class is a blueprint for creating variables
  • Object is a form of class, with its own attributes

Instance Variables and Methods

  • Instance Variables: Each object gets its own copy of the variables
  • Methods: Define what an object can do
  • Methods act on instance variables

Constructor

  • A constructor is a method called at aumatically when a new object is created
  • Names are the same as the class
  • There is no return type
  • Used to initialize objects
  • Default Constructor
class Person {
    Person() {
       System.out.println("Default Constructor called");
    }
}
  • Parameterized Constructor
class Person {
    String name;
    Person(String personName) {
       name = personName;
    }
}

Encapsulation

  • OOP principle that combines data and methods in a class
  • Hides the internal details

Features of Encapsulation

  • Data Hiding:: Prevents direct variable modifications
  • Access Control: Getter and Setters
  • Security: Protects data and modifications
  • Maintainability: Changes to the class internals don’t affect external code

Code Example

  • Using 'private' restrics access directly
  • Public getter and setter methods allow controlled access

Practice of OOP

  • Data Hiding: The name variable cannot be accessed directly.
  • Controlled Access: Only setter/getter methods control modifications.
  • Security & Flexibility: You can add validation inside setters

Understanding Inheritance

  • OOP principles alongisde Encapsulation
  • It allows a subclass to be inhereted by a superclass
  • Code is more reusable

Important Terms

  • Superclass also known as Parent
  • Subclass also known as Child

Why use Inheritance

  • Code is morereusable, making common subclasses
  • Method Overriding

Example on how to inherit

class DerivedClass extends BaseClass {
    // methods and fields
}

Inheritance Types

  • Can be Single, Mulitple and Hierachical

Code Example For Inheritance Types

class Animal {
    void eat() {
      System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
     void bark() {
       System.out.println("The dog barks.");
}

Multilevel Inheritance:

  • A class inherits from another class, which itself is inherited from another.
class Animal {
    void eat() {
      System.out.println("This animal eats food.");
    }
}
class Mammal extends Animal {
    void walk() {
      System.out.println("Mammals can walk.");
        }
}

class Dog extends Mammal {
    void bark() {
      System.out.println("The dog barks.");
}

Hierarchical Inheritance:

  • Multiple classes inherit from a single parent class.
class Animal {
  void eat() {
      System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
  void bark() {
   System.out.println("The dog barks.");
   }
}

class Cat extends Animal {
   void meow() {
     System.out.println("The cat meows.");
    }
}

Important Note

  • Java does not do multiple inheretence, insteasd uses INTERFACES

Polymorphism

  • OOP that allows methods to perform different aspects based on the object calling them
  • Can be acheived by way of Method Overloading or Method Overriding(Dynamic or Runtime)

Key terms

  • Code to be reusable

Implementation

  • Polymorphism allows methods to perform different tasks based on the object calling them
  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)
  • Compile-Time Polymorphism (Method Overloading); multiple methods in the same class have the same name but different parameters (method signature)

Method Executing

  • determined at compile time

Example

class Calculator {
 // Method Overloading
  int add(int a, int b) {
    return a + b;
  }
 double add(double a, double b) {
   return a + b;
 }
}

Runtime Polymorphism

  • subclass provides a specific implementation of a method
  • method call is resolved at runtime

Example Code

class Animal {
 void sound() {
  System.out.println("Animal makes a sound");
 }
}

class Dog extends Animal {
  // Method Overriding
    void sound() {
      System.out.println("Dog barks");
   }
 }

public class Main {
 public static void main(String[] args) {
  Animal myAnimal = new Dog(); // Upcasting
  myAnimal.sound(); // Output: Dog barks
 }
}

Essential Notes

  • Overloaded methods must have different method signatures
  • Method overriding allows a subclass to provide a specific implementation of a method in the superclass
  • the overridden method must have same signature

Abstraction

  • Hides the data
  • Abstract classes and Interfaces

Abstraction Rules

  • Java must declare abstract class
  • Not instantiated
  • Methods are either abstract or nor abstract
  • Constructors and Instance Variables

Java Best Practices

  • Promote organizaiton
  • Enforce common sctructure and subclass

Implementation

  • Java provides 2 ways to achieve
    1. Abstract Classes
    2. Interfaces

Interfaces

  • Anotheer way to do abstaction o Key Points: o To implement an interface, use the keyword implements with a class. o All methods in an interface are public and abstract by default. o A class can implement multiple interfaces o Used when classes share some common behavior but have differences in specific implementations.

Key Notes on Abstraction

  • interfaces are good to have

Arrays vs Lincked lists

  • Both implement Java collection Framework for different data manipulaition

Array List Key Characteristics

  • Data is allocated dynamically and assigned with an index
import java.util.ArrayList;
  public class Main {
 public static void main(String[] args) {
       ArrayList<String> list = new ArrayList<>();
       list.add("Apple");
      list.add("Banana");
    list.add("Cherry");

System.out.println(list.get(1)); // Output: Banana

Array Proformance

  • Easy Random Access thanks to use of index, O(1)
  • Can resize quick, but costly at middle indexes O(n) memory

Linked List Characteristics

import java.util.LinkedList;

public class Main {
 public static void main(String[] args) {
  LinkedList<String> list = new LinkedList<>();
  list.add("Apple");
 list.add("Banana");
list.add("Cherry");
  • Data is stord in sequential order from start to finnish hence more overheads to read, uses refernce.
  • Pro: Fast add and removal in middle indexes, con longer time to perform, O(n)

Summary

  • Array list better for fast index reads at memory
  • Link list better for queques or stacks

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser