Docsity

Java at a Glance: Java Basics, OOP, and Code Examples for Beginners, Quizzes of Education & Teaching

Toggle sidebar
bg1
Java at a Glance · 1
Java at a Glance
Core Concepts and Code Examples
Use this guide to review the Java language, read short code examples, and explain how classes, objects,
and exceptions work.
Language Basics
What Java is
Java is a general-purpose, statically typed programming language that supports object-oriented
programming. Java compilers typically produce bytecode that runs on the Java Virtual Machine (JVM).
Developers use Java for backend services, enterprise systems, desktop software, and Android applications.
Syntax and variables
Syntax is the set of rules for writing valid Java code. A variable has a name and a type. Primitive variables
hold values directly, and reference variables hold references to objects or the value null.
int score = 85;
boolean passed = true;
String studentName = "Maya";
Primitive and reference types
Java has eight primitive types: byte, short, int, long, char, float, double, and boolean. Class types, interface
types, and array types are reference types. String is a class, so String variables are reference variables.
In everyday usage, an integer is a whole number. Java groups byte, short, int, long, and char as integral
types. The char type represents a UTF-16 code unit.
Methods and parameters
A method groups code into a named operation. A declaration gives each parameter a type and a name. The
return type describes the result, and void indicates that the method returns no value.
Place the method below inside a class. The call is shown inside main so you can see the difference between
a parameter (marks) and an argument (59).
static String getGrade(int marks) {
return marks >= 60 ? "Pass" : "Needs improvement";
}
public static void main(String[] args) {
System.out.println(getGrade(59));
}
pf3
pf4
pf5

Partial preview of the text

Download Java at a Glance: Java Basics, OOP, and Code Examples for Beginners and more Quizzes Education & Teaching in PDF only on Docsity!

Java at a Glance

Core Concepts and Code Examples

Use this guide to review the Java language, read short code examples, and explain how classes, objects,

and exceptions work.

Language Basics

What Java is

Java is a general-purpose, statically typed programming language that supports object-oriented

programming. Java compilers typically produce bytecode that runs on the Java Virtual Machine (JVM).

Developers use Java for backend services, enterprise systems, desktop software, and Android applications.

Syntax and variables

Syntax is the set of rules for writing valid Java code. A variable has a name and a type. Primitive variables

hold values directly, and reference variables hold references to objects or the value null.

int score = 85; boolean passed = true; String studentName = "Maya"; Primitive and reference types

Java has eight primitive types: byte, short, int, long, char, float, double, and boolean. Class types, interface

types, and array types are reference types. String is a class, so String variables are reference variables.

In everyday usage, an integer is a whole number. Java groups byte, short, int, long, and char as integral

types. The char type represents a UTF-16 code unit.

Methods and parameters

A method groups code into a named operation. A declaration gives each parameter a type and a name. The

return type describes the result, and void indicates that the method returns no value.

Place the method below inside a class. The call is shown inside main so you can see the difference between

a parameter (marks) and an argument (59).

static String getGrade(int marks) { return marks >= 60? "Pass" : "Needs improvement"; } public static void main(String[] args) { System.out.println(getGrade(59)); }

Control Flow and Arrays Four loop forms

A loop repeats work while an expression is true or for each element in a group. Choose the form that

matches how the repetition should start and stop.

int[] scores = {10, 20, 30, 40}; for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); // Use the index. } for (int score : scores) { System.out.println(score); // Read each value. } int i = 0; while (i < scores.length) { // Check before each iteration. System.out.println(scores[i++]); } int attempts = 0; do { // Run the body at least once. attempts++; } while (attempts < 3); The switch statement

A switch selects a branch based on a value. With traditional colon-style cases, break exits the switch and

prevents execution from continuing into the next case. The default branch handles values that match no

case.

int priority = 2; switch (priority) { case 1: System.out.println("High"); break; case 2: System.out.println("Normal"); break; default: System.out.println("Unknown"); } Array indexing and assignment

An array holds a fixed number of elements of one declared type. Its first index is 0 and its last is length

minus one. Use new int[4] to allocate four elements with initial values of zero. Assignment changes an

existing element. For example, scores[0] = 15 replaces the first element of the four-element array above.

Inheritance and Abstraction Inheritance

A subclass uses extends to inherit accessible members of a superclass. For example, Bus extending

Vehicle illustrates single inheritance. SchoolBus extending Bus creates a multilevel chain. If Truck also

extends Vehicle, Bus and Truck illustrate hierarchical inheritance.

Abstraction

Abstraction defines the operations callers need and leaves implementation details to the class that provides

them. An abstract class can contain both implemented and abstract methods. A concrete subclass must

implement any abstract methods that remain.

abstract class Shape { abstract double area(); } class Rectangle extends Shape { private final double width, height; Rectangle(double width, double height) { this.width = width; this.height = height; } @Override double area() { return width * height; } } Interfaces

An interface defines a contract. A class can use implements to fulfill multiple interface contracts while

extending one superclass. Interfaces can declare abstract, default, static, and private methods. A class

implementing a public interface method must declare it public.

interface Printable { void print(); } class Report implements Printable { @Override public void print() { System.out.println("Report ready"); } }

Object Behavior and Exception Handling Encapsulation and accessors

Encapsulation controls access to an object’s state. A class can keep fields private and expose methods that

enforce its rules. A getter reads a value. A setter updates it and can validate the input before saving it.

class Settings { private int volume; int getVolume() { return volume; } void setVolume(int volume) { if (volume < 0 || volume > 100) { throw new IllegalArgumentException("Volume must be 0 to 100"); } this.volume = volume; } }

Abstraction gives callers a simple operation such as setVolume. Encapsulation keeps the volume field

private and applies validation when its value changes.

Polymorphism

Polymorphism lets code use a common type while different objects provide their own behavior. In the

example below, the variable is declared as Shape and the JVM calls the Rectangle implementation of

area().

Shape shape = new Rectangle(3, 4); System.out.println(shape.area()); // Prints 12. Handling exceptions

An exception is an object that signals a problem and interrupts the current flow of execution. A try block

contains code that may throw an exception. A matching catch block can respond to the specific problem.

String input = "abc"; try { int quantity = Integer.parseInt(input); System.out.println("Quantity: " + quantity); } catch (NumberFormatException e) { System.out.println("Enter a whole number."); } References Dev.java language tutorials · https://dev.java/learn/language/ Oracle Java Language Specification · https://docs.oracle.com/javase/specs/